text stringlengths 8 267k | meta dict |
|---|---|
Q: Recursive method will not move on and remains in an infinite loop (Java ) I'm learning about recursion as part of a Java tutorial and I am looking for a little help.
We need to make a recursive Java program which will work out how to get from one city to the other when there is no direct flight.
My problem is that Im getting an infinite loop that only seems to try two cities and then the code repeats itself again and again.
I would appreciate some help on this if you could.
I do not want to overflow you guys with code so i'll put up the method that you should need. If you need more I will happily add some more code.
public boolean determineRoute(City from, City to, ArrayList<City> flightRoute) {
int i = 0;
ArrayList<City> Connections = new ArrayList<City>();
// the Connections value takes all the connecting cities we can travel to from a departure point
Connections = from.getConnections();
// searches in the connecting cities from the current city as to if it contains the city we wish to travel to
if (Connections.contains(to)) {
System.out.println("Congrats you can go their cause one of its connecting cities is the to city that u wanna go to");
return true;
} else {
// add connecting city to list for future reference
flightRoute.add(Connections.get(i));
System.out.println(Connections.get(i) + " added to flight route");
// saves current connection
City theCity = Connections.get(i);
// recursive part which sends a new from city for analysis until the city we want to travel to arises
determineRoute(from = Connections.get(i), to, flightRoute);
return true;
}
}
A: Just a hint: Do you think it is appropriate to have a city twice on the route? You are currently building such flight routes.
A: This code makes no sense whatsoever.
Variable i is never incremented. The only one of the connections of a city will ever be used.
Why are you setting from in the recursive call?
Why are you creating an array list simply to overwrite the only reference to it in the next line?
What you want is Dijkstra's algorithm.
This algorithm is iterative and will find the shortest path length, which could be lowest cost, fewer changes or shortest duration.
A: Detect the cycle and break it.
You have cursed yourself with the one thing that kills any recursive method: you don't have a stopping condition.
Before you add a city to the list of connections, check to see if it already appears. If it does, there's no need to add it again by recursing.
You keep recreating the list of Connections each time you enter the method, so the previous call's values are forgotten each time. You can prove this quickly by firing up a debugger and adding a breakpoint at the start of your method. You'll see that the connections list is empty each time you enter the method.
A better solution would be to pass that list into the method so new values can be appended to the growing list each time.
A: In short: the recursive method will stop recursing only when Connections contains the city you want to go to. Since nothing is ever added to Connections, this will never become true, if it's not true initially.
You've got sort of the same issue with the variable i: its value never changes, so again, nothing different ever happens.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: jQuery custom background through a cookie I'm making background changing script for my site. Everything works fine except the cookie which should store the required value. I'm using jQuery 1.3. IE 8 says: 'object doesn't support this property or method on line 47 char 118567432'!? Any help will be greatly appreciated. Working example without cookie:
function images(which,image) {
if (which == 't1')image = images[0];
else if (which == 't2')image = images[1];//and etc...
}
$('html').css("background-image", image);
Example with cookie (not working):
function images(which,image) {
if (which == 't1')image = images[0];
{$.cookie("html_img", "" + image + "", { expires: 7 });
imgCookie = $.cookie("html_img");}
else if (which == 't2')image = images[1];
{$.cookie("html_img", "" + image + "", { expires: 7 });
imgCookie = $.cookie("html_img");}
}
$('html').css("background-image", imgCookie);
A: I've converted your code to a more efficient, and syntactically valid JavaScript code.
function images(which){
var image = /^t\d+/i.test(which) ? images[which.substr(1)-1] : null;
if(image !== null) {
$.cookie("html_img", image, {expires:7})
} else {
image = $.cookie("html_img");
if(!image) image = images[0]; //If the image doesn't exist, use default=0
}
$('html').css("background-image", image);
}
$(document).ready(function(){
images(); //Load image default from cookie
}
//If you want to change the image+cookie: images("t2");
A: May be your "cookie plugin" script is not imported correctly? Can you give more details on the error you get. Use Firebug for Firefox or Chrome Dev tools to get a better error trace.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Identify if the process in User Interface Process? How can I get information from a process that it is UI(User Interface) process or non-ui?
With UI process I mean, Finder, Dock, System UI server, or any other mac application which has UI interface and it is used by Window Server.
I want to determine this information from ProcessID.
I am using mac os x.
A: There is no way to determine based purely on the PID number what a specific process is. The reason for this: Process IDs are assigned (somewhat) sequentially from PID=1 on startup, and startup can be different for different systems. The process ID will also be reassigned if, for example, Finder or Dock crashes and has to be restarted.
If you can run a terminal command with a specific pid that you have, though, do this:
ps -p <pid> -o ucomm=
You'll get the filename of the process, which you can check against a list of ones you know are UI processes. For example, here is the output of certain ps commands on my system for my current login session:
> ps -p 110 -o ucomm=
Dock
> ps -p 112 -o ucomm=
Finder
And the following command will give you a list of processes in order of process ID, with only the name:
> ps -ax -o pid=,ucomm=
1 launchd
10 kextd
11 DirectoryService
...
EDIT: You may be able to do what you ask, though it is convoluted. This answer mentions:
The function CGWindowListCopyWindowInfo() from CGWindow.h will return an array of dictionaries, one for each window that matches the criteria you set, including ones in other applications. It only lets you filter by windows above a given window, windows below a given window and 'onscreen' windows, but the dictionary returned includes a process ID for the owning app which you can use to match up window to app.
If you can obtain all the CGWindows and their respective pids, then you will know the pids of all UI applications without needing to run ps at all.
Rahul has implemented the following code for this approach, which he requested I add to my answer:
CFArrayRef UiProcesses()
{
CFArrayRef orderedwindows = CGWindowListCopyWindowInfo(kCGWindowListOptionAll, kCGNullWindowID);
CFIndex count = CFArrayGetCount (orderedwindows);
CFMutableArrayRef uiProcess = CFArrayCreateMutable (kCFAllocatorDefault , count, &kCFTypeArrayCallBacks);
for (CFIndex i = 0; i < count; i++)
{
if (orderedwindows)
{
CFDictionaryRef windowsdescription = (CFDictionaryRef)CFArrayGetValueAtIndex(orderedwindows, i);
CFNumberRef windowownerpid = (CFNumberRef)CFDictionaryGetValue (windowsdescription, CFSTR("kCGWindowOwnerPID"));
CFArrayAppendValue (uiProcess, windowownerpid);
}
}
return uiProcess;
}
A: Kind of resurrecting this one... But for macOS, to get the process ids of various elements of the UI, you can use lsappinfo since maybe Tiger? The manpage says April, 2013, but I think it was around at the time of this question being asked and probably earlier. The command should be run as the user who currently owns the loginwindow process.
lsappinfo info -only pid Dock
"pid"=545
A: Try the following.
#include <unistd.h>
if (isatty(STDIN_FILENO) || isatty(STDOUT_FILENO) || isatty(STDERR_FILENO))
// Process associated with a terminal
else
// No terminal - probably UI process
A: On the lines of darvidsOn, below is the answer to your question.
CFArrayRef UiProcesses()
{
CFArrayRef orderedwindows = CGWindowListCopyWindowInfo(kCGWindowListOptionAll, kCGNullWindowID);
CFIndex count = CFArrayGetCount (orderedwindows);
CFMutableArrayRef uiProcess = CFArrayCreateMutable (kCFAllocatorDefault , count, &kCFTypeArrayCallBacks);
for (CFIndex i = 0; i < count; i++)
{
if (orderedwindows)
{
CFDictionaryRef windowsdescription = (CFDictionaryRef)CFArrayGetValueAtIndex(orderedwindows, i);
CFNumberRef windowownerpid = (CFNumberRef)CFDictionaryGetValue (windowsdescription, CFSTR("kCGWindowOwnerPID"));
CFArrayAppendValue (uiProcess, windowownerpid);
}
}
return uiProcess;
}
Just compare the processid you have against the array items to get the desired result.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: I want the stage to react every time some changes are made to certain objects. Is there a way to write custom Event? I want the stage to react every time some changes are made to certain objects. Is there a way to write custom Event? I could of course modify this object, but I would like to know if there is any more OOP way to do it. And events ARE OOP, ain't they?
A: A custom event class can be written like this:
public class MyEvent extends Event
{
private var evtData:Object;
public function MyEvent(type:String, data:Object)
{
super(type);
//fill this.evtData here
}
override public function clone():Event
{
return new MyEvent(type, evtData);
}
}
then dispatch this event by:
dispatch(new MyEvent("someName", obj))
and catch it like
myObj.addEventListener("someName", handleMyEvent);
function handleMyEvent(evt:MyEvent):void
{
//do something with evt
}
A: Lets say you have a property count in some class. Easiest way is to generate setter and getter for this property and inside the setter to dispatch some custom event.
protected var _count:Number;
public function get count():Number
{
return _count;
}
public function set count(value:Number):void
{
_count = value;
dispatchEvent(new CountEvent(CountEvent.COUNT_CHANGED, value, true));
}
This is the custom event class:
public class CountEvent extends Event
{
public static const COUNT_CHANGED:String = "countChanged";
public var data:Object;
public function CountEvent(type:String, data:Object, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
this.data = data;
}
override public function clone():Event
{
return new CountEvent(type, data, bubbles, cancelable);
}
}
Note that if you need the value of the property and don't have reference to the object itself, you can create a data-object event. In order for this kind of custom event to work properly you need to override the clone method, which is used every time the event is re-dispatched.
If you are looking for more advanced way of "observing" something is by using some custom code, e.g.
http://code.google.com/p/flit/source/browse/trunk/flit/src/obecto/utility/observe/Observe.as?r=190
In either way you must decide whether you want to modify your class by adding a dispatcher (if your class is not a EventDispatcher subclass) and dispatch an event or use some other techniques. Another way is to make the property [Bindable] and use a binding between your property and some function to watch if something changes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: FB JavaScript SDK is giving wrong permissions dialog for my friend, but new one for me Currently, I'm using
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId: '214620658601362',
cookie: true,
status: true,
xfbml: true,
oauth: true
});
$(function() {
$("#login").click(function() {
FB.login(function() {
alert('logged in');
}, {
scope: 'publish_actions'
});
});
});
code to get authenticated into my dummy application. Problem is that my friend see the old permissions dialog, it means he can't approve my application's "publish_actions" permission. I see the new one. When I try to publish action, error appears:
FB.ApiServer._callbacks.f3209b810({"error":{"message":"(#200) Requires extended permission: publish_actions","type":"OAuthException"}});
however, it works for me
My friend (wrong one):
Me (correct one):
am I missing something in my login code?
A: The second screenshot is a dialog which hasn't launched for every application/user; if your friend enabled the Timeline beta as a developer, he'd likely be seeing the new dialog.
It's not clear if he's a developer of the app you're trying to authorize; if so, it makes it even more likely.
A: Your friend probably needs to clear their browser cache so that it has to reload the page from its source, not from what is cached on disk.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: specify which vim is called from a command like git I'm doing some rails dev on mac osx. I have an alias for vim that calls the version in homebrew
vim: aliased to /usr/local/Cellar/vim/7.3.266/bin/vim
But if I execute say git rebase -i [sha] then it will call a different vim from the one that's aliased. It's calling /usr/bin/vim which is NOT what I want.
How do I fix this?
A: You can use:
git config --global core.editor /usr/local/Cellar/vim/7.3.266/bin/vim
A: Create an alias (and make sure you export it) and set this as your editor of choice inside your .gitconfig file.
A: On most UNIX/Linux systems, there is a variable
export EDITOR=/usr/bin/gvim
This editor ought to be used by all programs requiring input (qmv, visudo, crontab -e, git commit etc. etc.)
On debian there is
sudo update-alternatives --config editor
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Clicking game - Operator '-' cannot be applied to operands of type 'string' and 'int' error Iam making a clicking game, but there is an error i can't get working correctly.
The error is:
Operator '-' cannot be applied to operands of type 'string' and 'int'
in the private void timer1.tick.
i have been looking on google and this site, but didnt manage to find a compareable error. i've tried the longer minus and the short minus sign.
(made in visual c# 2010 express)
public partial class Form1 : Form
{
int timeLeft;
int counter = 10;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Interval = 1000;
timeLabel.Text = timeLabel.Text - 1;
{
if (timeLeft > 0)
{
timeLeft--;
timeLabel.Text = timeLeft + " seconds";
}
else
{
timer1.Stop();
timeLabel.Text = "Score";
MessageBox.Show(Score.Text, "Score");
Plus.Enabled = false;
}
}
}
private void Plus_Click(object sender, EventArgs e)
{
timer1.Start();
Score.Text = Score.Text + 1;
Score.Text = counter.ToString();
}
}
A: Score.Text is a string; you can't subtract a number from a string. You have to convert the string to a number before you can do math on it.
Note that Score.Text + 1 doesn't do math; the + operator concatenates strings, rather than doing arithmetic.
A: My recommendation - don't use the timeLabel to store the "truth" about the time remaining.
Instead, do something like:
timeLeft--;
if (timeLeft > 0)
{
timeLabel.Text = timeLeft + " seconds";
}
else
{
timer1.Stop();
timeLabel.Text = "Score");
}
The error is telling you that there's no operator- that takes an int there - essentially, whatever operator- means for the class, in this case string, it doesn't know what to do with an integer argument.
Again, don't do it that way. You've already got the integer value. The timeLabel is a presentation thing, the timeLeft int is a business logic piece. Let the timeLabel do what it does best - showing text to the user - and let the integer field, timeLeft manage what the new seconds value should be.
Same thing with your score text. You're mixing presentation and business logic here. Just make an int for your score and then do something like:
Score.Text = currentScore.ToString();
As an aside, the Score.Text line in Plus_Click probably doesn't work as you intend. I'm assuming Score is a text box or something like that. It's not going to show whatever Score.Text + 1 is because it's going to be overwritten by whatever counter.ToString() is. Not trying to beat on you here, just pointing it out.
A: timeLabel.Text = Int32.Parse(timeLabel.Text) - 1;
Likewise in other places. HTH.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.NET + C# HttpContext.Current.Session is null (Inside WebService) this is how I initiate the session
protected void Session_Start(object sender, EventArgs e)
{
HttpContext.Current.Session["CustomSessionId"] = Guid.NewGuid();
}
in my solution under a class library i am triyng to access it and getting null exception:
string sess = HttpContext.Current.Session["CustomSessionId"] ;
this is my config in web.config and app.config (in my library)
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
<system.web>
<pages enableSessionState = "true" />
<httpModules>
<add type="System.Web.SessionState.SessionStateModule" name="Session"/>
</httpModules>
<compilation debug="true" targetFramework="4.0" />
</system.web>
(app.config)
A: According to your comments it seems that you are trying to access the session in a web service. Web services are stateless and that's how they should be. If you want to violate this rule and make them stateful you could enable sessions in a classic ASMX web service like this:
[WebMethod(EnableSession = true)]
public void SomeMethod()
{
... invoke the method in your class library that uses Session
}
This being said, using HttpContext.Current in a class library is a very practice that should be avoided at all price.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: SSL, getting an upper bound on the length of a decoded message based on the encoded message Simply put, when given an encoded message of length n, is there anyway I can bound in advance the length of the decoded message (for memory allocation purposes)?
I thought that the length of the message added to the length of the cipher bits should be enough, but apparently it isn't...
Thanks in advance
A: No, since SSL supports compression.
Also, I'm not sure exactly what you're coding, but typically you have no idea what the length of the encoded message is. You can't assume that whatever chunk of data you just handed the SSL engine is the entire encoded message -- it can just be part of it.
A: In theory the cyphertext is at most (IV + plaintext + padding), where the IV and the padding are up to one block each. In practice things may be different: the plaintext may be zipped and automatically expanded on decompression. Or, as David said, the cyphertext may be split into chunks, each sent separately.
Better to use some flexible container to receive the message and later resize to the appropriate fixed size container if you need to. It is easier to avoid buffer overflow that way as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use jquery method in asp.net Q:
I wanna to know how to use this jquery in asp.net.(steps)
$(...).scollTo( $('<%= txt_evaluateWeights.ClientID %>') )
My original question is How to prevent the Focus() method from scrolling the page to the top
My aspx:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Panel ID="pnl_research" runat="server" CssClass="pnl">
<div id="detailsDiv" align="center" style="width: 800px;">
<table border="0" width="98%">
<tr>
<td align="center">
<div class="grid" dir="rtl">
<div class="grid" dir="rtl">
<div class="rounded">
<div class="top-outer">
<div class="top-inner">
<div class="top">
<h2>
<asp:Label ID="Label35" runat="server" Text="Evaluation"></asp:Label></h2>
</div>
</div>
</div>
<div class="mid-outer">
<div class="mid-inner">
<div class="mid">
<asp:GridView Width="100%" ID="gv_Evaluation" CssClass="datatable" AllowSorting="True"
runat="server" AutoGenerateColumns="False" AllowPaging="True" GridLines="None"
OnRowDataBound="gv_Evaluation_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="s">
<ItemTemplate>
<asp:Label ID="lblSerial" runat="server"></asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="activity type" DataField="activityType" />
<asp:BoundField HeaderText="weight" DataField="activityWeight" />
<asp:TemplateField HeaderText="eval">
<ItemTemplate>
<telerik:RadTextBox ID="txt_evaluateWeights" runat="server" AutoPostBack="True" OnTextChanged="txt_evaluateWeights_TextChanged">
</telerik:RadTextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txt_evaluateWeights"
Display="Dynamic" ErrorMessage="*" SetFocusOnError="True"></asp:RequiredFieldValidator></ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="mine" DataField="activitySelf" />
<asp:BoundField HeaderText="head" DataField="activityBoss" />
<asp:BoundField HeaderText="dean" DataField="activityDean" />
</Columns>
<RowStyle VerticalAlign="Top" CssClass="row" />
</asp:GridView>
</div>
</div>
</div>
<div class="bottom-outer">
<div class="bottom-inner">
<div class="bottom">
</div>
</div>
</div>
</div>
</div>
</div>
</td>
</tr>
</table>
</div>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
My .cs:
protected void txt_evaluateWeights_TextChanged(object sender, EventArgs e)
{
calc();
int index = ((System.Web.UI.WebControls.GridViewRow)(((RadTextBox)sender).Parent.NamingContainer)).DataItemIndex;
((RadTextBox)gv_Evaluation.Rows[index + 1].Cells[3].FindControl("txt_evaluateWeights")).Focus();
}
A: Well you need to use an id selector, i.e. prefix with #:
$(...).scollTo($('#<%= txt_evaluateWeights.ClientID %>'));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create this custom edittext ? Please help In an application I wish to create an edit text control like shown here http://www.customeuropeanplates.com/images/UK-License-Plate.jpg can anybody please suggest how should this be done? I know this is something easy but I am new to android.
A: Create a 9-patch drawable for the EditText's background (yellow background with black border). You can create 9-patch images with 9-patch tool (draw9patch) that is located under the SDK Tools folder. And then you'll need custom font for the text. Text is aligned to the center of EditText.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C#: Calling method in another thread
Possible Duplicate:
How to update GUI from another thread in C#?
Following scenario:
I have a class with some GUI elements (winforms). This class has a update method which changes things on the controls.
I also have a FileSystemWatcher. This object gives me a callback whenever a file changes. In that case I call the update method.
As you might guess this makes the application crash. The reason: the callback from the FileSystemWatcher is in another thread that the one that created the controls. If I then call the update method it can't access the controls.
What is the way to fix this? Thanks!
A: You should call Control.Invoke or BeginInvoke, see in-depth reference Here
A: The top voted answer this this Question looks like it might do the trick:
C# Windows Forms Application - Updating GUI from another thread AND class?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: USB Detection on MAC cocoa application using NSWorkspace notification I am trying to implement USB detection using NSworkspacenotification method, using this code
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
[[[NSWorkspace sharedWorkspace] notificationCenter]addObserver: [NotifTarget class] selector: @selector(mountNotification:) name: NSWorkspaceDidMountNotification object: nil];
[[[NSWorkspace sharedWorkspace] notificationCenter]
addObserver: [NotifTarget class]
selector: @selector(unmountNotification:)
name: NSWorkspaceDidUnmountNotification object: nil];
[[NSRunLoop currentRunLoop] run];
NSLog(@"Hello, World!");
[pool drain];
return 0;
}
This code does not detect USB and outputs:
Hello, World!
Program ended with exit code: 0
What's wrong with this code?
A: You have added no input sources or timers to your run loop, so it's exiting immediately.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Write a comma in a CSV File with PHP i am sending a csv file as a header and i want to use a comma (not to seperate, just to use). how would i do that?
i'm using PHP and i can not use fputcsv because i'm sending it as a header.
A: Either write the CSV to file first and then send it via readfile or write it to the output stream directly:
fputcsv(
fopen('php://output', 'w+'),
array(
'Some text',
'Some text with commas ,,,,,',
'Other text'
)
);
which will then print
"Some text","Some text with commas ,,,,,","Other text"
Note that fputcsv will also allow you to change delimiters and enclosures, so in addition to just wrapping the value in quotes you can also just change the delimiter to, for instance, a semicolon.
See the PHP Manual on supported wrappers in fopen:
*
*http://php.net/manual/en/wrappers.php.php
A: Just use '"'.$value.'"' around it and it will be fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Updating a ProgressDialog using an AsyncTask I need a AsyncTask to run my ProgressDialog while I'm fetching data from the network.
I understand the AsyncTask. But I have the network calls in more than a dozen places. How can I reuse a single AsynchTask class for all these calls as my call to the network is from different Activity?
This made me rewrite the AsyncTask wherever in the Activities there is a network call.
A: Without knowing the full details of your code it does sound to me as though you might be using AsyncTask in a way it was never intended.
From the docs:
This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
In my mind AsyncTask is suitable for relatively simple asynchronous tasks such as single file download/stream etc. Once there is a need for more complicated asynchronous tasks then perhaps utilising the full functionality of Threads is called for. It all comes down to design and correct choice of available tool for the task...
A: It really all depends how involved your network calls are. If they are quick and you're not pulling a lot of data, then the AsyncTask will be fine.
Ultimately, what you need to do is clean up you code and make sure you're not repeating any logic. Make sure you're putting all the repeated logic in a single method.
So that you're not rewriting the AsyncTask for each Activity, make a "parent" Activity class where you define you're AsyncTask (and any other repeated logic). Then have the activities that need to run your AsyncTask extend this Activity.
If, however, your network calls are somewhat involved, you're probably going to want to look into another way of doing it. You may want to define a Service and bind all of your Activities to that service.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: DataContractJsonSerializer leaving quotes in strings I am using the DataContractJsonSerializer on Windows Phone 7.1 (Mango RC) to pull data from a web service. The data from my web service looks like this:
[
{
"Color":"\"black\"",
"CurrentPlayerTurn":1,
"GameId":"\"3adbffa7b5744634aca0e4b743014247\"",
"GameState":0,
"OtherPlayerId":null
},
{
"Color":"\"black\"",
"CurrentPlayerTurn":1,
"GameId":"\"a292247719e34811a93598d2ff3eb13c\"",
"GameState":0,
"OtherPlayerId":"\"shmoebob\""
}
]
In case you're wondering, this data is downstream of a CouchDB map/reduce query, whose output looks like this:
{"total_rows":4,"offset":1,"rows":[
{"id":"3adbffa7b5744634aca0e4b743014247","key":"kotancode","value":[0,1,"black",null]},
{"id":"a292247719e34811a93598d2ff3eb13c","key":"kotancode","value":[0,1,"black","shmoebob"]}
]}
What's happening in my WP7.1 client is that when I deserialize the object array from the first blob of JSON, I am actually getting the quotes inside the strings and I'm having to manually strip them out property by property.
The web service that my WP7.1 client is hitting is a v0.5 WCF Web API RESTful service and I am exposing that data as JSON.
Is there something I'm doing wrong somewhere in this pipeline that is causing the quotes to be treated literally ... or is there something I can do with the DataContractJsonSerializer to make it not actually give me the quotes?
A: This happens to me all the time.. as soon as I post the question, I figure out the answer. The problem was in how I was using JsonValue to parse the information from CouchDB.
the WRONG way:
string color = (row["value"] as JsonArray)[2].ToString(); // this embeds double-quotes
the RIGHT way:
string color = (row["value"] as JsonArray)[2].ReadAs<String>(); // this doesn't embed double-quotes.
Hope this helps someone else who might run into the same issue...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Create and Write to Files with JavaScript/JQuery A few days ago I started to build a "Talk To Us Page" In c#.
So, I did a few buttons and text arena options..
And it was easy as C# should be. You just use a system IO or any thing and write to files..
I tried to do some thing very similarly with JS\jQuery and had no idea how to do so.
I looked around google a bit, and found nothing. Really, found about 30 people who are saying things that are really not working.
And I have to do is write a few lines of text from textbox..
The textboxes look like this:
<input type="text" name="">
<input type="text" name="">
and when you clicked of a button it will write it all down to a file in driver c, or anything like that.
I really thinks its not that hard, but I need a hand.
Please help me. thanks!
A:
and when you clicked of a button it will write it all down to a file in driver c, or anything like that.
Forget about it. For security reasons javascript that runs in a browser has no access to client and server files. Just think of the consequences if this was possible. You visit some site on the internet and all of a sudden files start to popup up and out of existence from your hard drive. Definitely something that should be forbidden.
A: Outside of Internet Explorer, you cannot use JavaScript to write to the local file system. This is a security feature of the sandbox in which in-browser JS runs.
A: javascript cant access the files contents, atleat on the client machine.
here is a helpful link http://en.wikipedia.org/wiki/JavaScript#Security
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to format localized text in JSF I'd like to keep localized text in a formatted manner (Using the <resource-bundle> in JSF)
For example:
in english.txt:
welcome_msg = <p>Hello <b>Friend</b></p>
in spanish.txt:
welcome_msg = <p> Ola <b>Hombre</b> commo esta? </p>
(Just random examples)
If I just use <h:outputText value="#{text.welcome_msg}" /> I will simply get the meta tags in the web page.
How can I achieve this?
Thanks!
A: By default, <h:outputText/> escapes the <, >, and & characters. Use the escape attribute to disable this:
<h:outputText value="#{text.welcome_msg}" escape="false"/>
Be aware that this is now a potential security hole, depending on the source of the text that you are outputting.
See also: http://download.oracle.com/javaee/6/javaserverfaces/2.0/docs/pdldocs/facelets/h/outputText.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I create a DLNA server application in Android? I am looking to add DLNA server capabilities of one of my current applications (for movie management), and I've tried to do some searching for any documentation on it, but so far I've only found a project called Cling, which should support Android. I have yet to try it out, so if anyone has any comments on the project, I'd be really happy.
I'd also love if anyone had some more documentation on adding DLNA server functionality to an Android application. I know there are quite a few applications that make use of this, so I know it's possible.
A: I use this code for my project.
A: I think you should search for some Linux libraries that implement DLNA. This will be the easiest way to go. DLNA specification cost lots of money and implementation and tests could not be trivial.
Of course you should check license of available software, because some of them could have restrictions.
Check the links from this wiki http://elinux.org/DLNA_Open_Source_Projects
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How and when are shared memory backing files removed in Linux? I am using the combination of shm_open() and mmap() to create a shared memory segment for IPC. What I'm wondering is how the backing files (in /dev/shm in my system, Linux kernel 2.6.31) are cleaned up.
My questions are threefold:
1) Is it the process's responsibility to unlink the files upon termination? If so, what if the process dies before it unlinks them?
2) Since I suspect the answer to #1 is "yes, it's the program's responsibility", is it considered "good practice" for my program to remove any stale files it notices before creating a new one, in case previous instances died uncleanly?
3) Is there a way to ask the kernel to remove the backing file after the last process unmaps the memory? I am thinking of something similar to shmctl(id, IPC_RMID, ...) in SysV style shared memory.
A: The answers are as following:
*
*Yes, it is the program's responsibility, although it may be possible to ensure cleanup, see my answer to 3.
*You could remove the stale files, You could also just use the existing shared memory object (which I assume you were going to recreate anyway).
*If you know that no other users for the shared section will exist after it is initially created, you can use shm_unlink right after mapping your shared memory. The memory region will be deallocated once all users unmap (and close) it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Mongoose: Suggested database schema Ok so I am coming from a mySQL background and am now trying to rebuild a site using nodeJS and Mongoose. My old mySQL schema looked something like this (simplified):
users
user_ID
user_name
user_email
user_password
groups
group_ID
group_name
group_description
groupusers
groupuser_ID
group_ID
user_ID
comments
comment_ID
group_ID
user_ID
comment_txt
Can anyone suggest the best way to restructure this old mySQL schema to work with Mongoose?
A: users
user_ID
user_name
user_email
user_password
Groups
- grupid 1
- grupid 2
- grupid 3
groups
group_ID
group_name
group_description
comments
1 -
user_ID
comment_txt
2 -
user_ID
comment_txt
If you are worried about the comment size (currently mongodb max document size is 16 mb), you can move it to other doc
In this way you can find the users of the group by
db.users.find({Groups:'groupid1'})
also the groups the user belongs to
db.users.find({id:userid},{Groups:1})
if you wanted to retrieve the group relevent info with the above query, i suggest you to store most frequently access group fields also with users.groups, like this
users
user_ID
user_name
user_email
user_password
Groups
- { grupid 1,name}
- {grupid 2,name}
- {grupid 3,name}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to search text surrounded by double-quotes with RegEx? I have a string with some HTML code in, for example:
This is <strong id="c1-id-8">some</strong> <em id="c1-id-9">text</em>
I need to strip out the id attribute from every HTML tag, but I have zero experience with regular expressions, so I searched here and there from the internet and I wrote this pattern: [\s]+id=\".*\"
Unfortunately it's not working as I would expect. Infact, I was hoping that the regular expression would catch the id=" followed by any character repeated for any number of times and terminated with the nearest double quote; Practically in this example I was expecting to catch id="c1-id-8" and id="c1-id-9".
But instead the pattern returned me the substring id="c1-id-8">some</strong> <em id="c1-id-9", it finds the first occurrence of id=" and the last occurrence of a double quote character.
Could you tell me what is wrong in my pattern and how to fix it, please?
Thank you very much
A: In .* the asterisk is a greedy quantifier and matches as many characters as it can, so it only stops at the last " it finds.
You can either use ".*?" to make it lazy, or (better IMO), use "[^"]*" to make the match explicit:
" # match a quote
[^"]* # match any number of characters except quotes
" # match a quote
You might still need to escape the quotes if you're building the regex from a string; otherwise that's not necessary since quotes are no special characters in a regex.
A: The quantifier .* in your regex is greedy (meaning it matches as much as it can). In order to match the minimum required you could use something like /\s+id=\"[^\"]*\"/. The brackets [] indicate a character class. So it will match everything inside of the brackets. The carat [^] at the beginning of your character class is a negation, meaning it will match everything except what is specified in the brackets.
An alternative would be to tell the .* quantifier to be lazy by changing it to .*? which will match as little as it can.
A: A parser is the best solution in the general case, but they to take time to write. There are cases where writing one would take more time than the parser would save; perhaps this is such a time.
What you want is a either a non-greedy match or a more precise match. /[\s]+id=\".?\"/ will do the trick, but [\s]+id=\"[^"]\" will be faster.
Note that a full regex that takes into account the possibility of escaped quotes characters, allows single quotes instead of double quotes, and allows for the absence of quotes entirely would be much more complex. You would really want a parser at that point.
A: example with grep: (but the point is the expression)
kent$ echo 'This is <strong id="c1-id-8">some</strong> <em id="c1-id-9">text</em>'|grep -oP '(?<= id=")[^"]*(?=">)'
c1-id-8
c1-id-9
A: If you know that your id is always 7 characters, you could do this.
/\sid=".{7}"/g
So..
var a = 'This is <strong id="c1-id-8">some</strong> <em id="c1-id-9">text</em>';
var b = a.replace(/\sid=".{7}"/g, '');
document.write(b);
Example: http://jsfiddle.net/jasongennaro/XPMze/
Check the inspector to see the ids removed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: why does this query return a row with nulls compare
SELECT distinct u_id,timestamp as time
FROM my_table;
and
SELECT distinct u_id,max(timestamp) as time
FROM my_table;
When my table has no rows at all (or if I add a where clause that matches no rows):
The former returns an empty results set (which is what I expect)
while the later returns a single row that has null as the value for both its fields.
Can someone please explain to me why does the second one acts as it does?
A: MySQL documentation says
MAX() returns NULL if there were no matching rows.
And if you have no data then it just returns both values as NULL.
If you want the second query return the empty resultset too, then you must filter out the NULL values for example with HAVING clause that you can use with aggregate functions:
SELECT DISTINCT u_id, MAX(timestamp) as time FROM my_table GROUP BY u_id HAVING time IS NOT NULL;
A: This actual answer to this question is quite complicated to explain, for me anyhow :) Headline points: SQL does not support aggregate operators as found in the relational model, rather merely supports a special case of summarization. Further, because SQL has but one data structure -- the table -- SQL aggregate operator invocations (loosely speaking) must appear as part of some table expression, hence why your second table returns a 'dummy' single row.
For a fuller/better explanation, see SQL and Relational Theory: How to Accurate SQL Code - C. J. Date (2009), section 7.5. Aggregate Operators.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Text::MicroTemplate and Server side validation [Perl] I have a form, which I use Text::MicroTemplate to add some fields to it, such as:
User Name
Last Name
Email
the fields are added using a loop inside a <form> tag, the data for these is validated using a regex (sent as a parameter to the template and "hidden" in the HTML in <span> tag with style display:none), so far, all is fine.
suddenly I have to add another field, for which the data has to be validated on the server side, what is the best approach for doing so? (I can of course, check the POST data, and if its incorrect, can send back the form with the relevant error message, but then, I will have to render the whole page again, which I dont do for the other fields...)
probably something with ajax?
thanks,
A: AJAX can avoid the whole page rendering which is a good thing™.
You know for sure that writing AJAX code working with different browser implementations, will lead to spaghetti-JavaScript-code, so my advice is to level differences with a good JavaScript library. I have chosen jQuery, because is easy to learn and fun to use if you alredy know CSS2 selectors. There there are other good libraries YUI, Prototype, MooTools, just choose one.
With jQuery, you can invoke an AJAX call in various ways including this simple version:
$.post( url, parameters, callback, returned_type );
where
*
*url: URL of server side resource that validates input
*parameters: an object whose properties are serialized into encoded parameters
*callback: callback invoked when request completes ( response body and status are passed to the callback as first and second parameter ).
*type: a string like 'html', 'text', 'xml', 'json', that tells what kind of response to expect from server.
Usually, to send a form, you have to hook an event handler to the submit button: the event handler hijacks the submit event, giving the opportunity to validate values client-side and send them with an AJAX call.
$( '#my_form' ).submit( function( event ) {
// Prevent classic submission that ends with whole page render
event.preventDefault();
// Here iterate through form elements and do a client-side check
...
$ajax.post( ... );
}
I can understand that my example is oversimplifed, but that pattern is rather common: hijack-submit-event-and-do-it-another-way.
You'll find more examples ( including those with powerful jQuery plugins ) in chapter 11 of jQuery Cookbook, entitled Html form enhancements with plugins.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Applet works in IDE, but not in browser I have created a simple applet and HTML document, but when I open the HTML document, the applet will not show. Java is enabled, and the code should be correct. but I just get a blank page. The applet runs fine in eclipse. I tried removing the stop and destroy methods which did nothing, not sure that it would anyway, this is my first ever applet code.
I did compile the .java file using the javac command and placed the html document and .class file in the same directory.
When using IE9 it gives me the error: Lamp (wrong name: mondrian/Lamp)
APPLET CODE
package mondrian;
import java.applet.*;
import java.awt.*;
public class Lamp extends Applet {
public void init() {
setBackground(Color.BLACK);
}
public void start() {
}
public void paint (Graphics g) {
g.setColor(Color.YELLOW);
g.fillRect(0, 0, 90, 90);
g.fillRect(250, 0, 40, 190);
g.fillRect(80, 110, 100, 20);
}
public void stop() {
}
public void destroy() {
}
}
HTML DOCUMENT
<html>
<body>
<APPLET CODE="Lamp.class" WIDTH=200 HEIGHT=50>
</APPLET>
</body>
</html>
A: I see that the class is in a package.
If you are running the class file place the html one directory below
and refer to the class together with its package as in:
<applet code=mondrian.Lamp.class
width=1200 height=1200>
</applet>
if you prefer to run from a jar place the html in the same directory and write
<applet code=mondrian.Lamp.class
archive="myarchive.jar"
width=1200 height=1200>
</applet>
jar is more portable of course than the numerous class files in a directory that needs to carry the package name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Socket.BeginReceive callback - message separator When the callback assigned by Socket.BeginReceive() gets some bytes, what is the best way to know I have the whole message? Should I have the first 4 bytes of each message I send hold the length of the message?
I am sending an XML file in each message so there is no unique character I can use as a message separator.
A: Follow the specification for the protocol you are using. If it's an original protocol, write a specification. It's a bit of extra work, but it's well worth it.
In that specification, you can specify a message length. You can also prohibit a particular byte (you could user zero) in the payload and use that as a message separator. Since you're using XML, you could simply define a tag that indicates a message -- the close of that tag would indicate a complete message.
It's up to you. But spend the time to specify your protocol in detail. I promise you it will pay off.
A: I would use a header containing two integers (4 bytes each). The first one would indicate protocol version and the second one would indicate message length. The good thing with using a header length instead of a delimiter is that you can allocate a buffer for the entire message before you start parsing it.
Using a version integer as the first header let's you change the rest of the headers, and the body, in any newer version of the protocol.
Update in reply to the comment
There is a difference between version number in the header and the one in the actual message. The message version is for the document, but the header version is for the protocol itself. By using a protocol version you could switch message transport from XML to Protobuf or something else for the message. You could also add a header identifying the target of the actual message.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to loop through all controls in a Windows Forms form or how to find if a particular control is a container control? I will tell my requirement. I need to have a keydown event for each control in the Windows Forms form. It's better to do so rather than manually doing it for all controls if what I have to do for all keydown events is the same.
So I could basically do this:
foreach (Control c in this.Controls)
c.KeyDown+= new KeyEventHandler(c_KeyDown);
But here, the foreach doesn't loop inside those controls which reside inside a groupBox or a tabControl. I mean if the form (this) contains a groupBox or some other container control, then I can get a keydown event for that particular container control. And the foreach doesn't loop through controls that reside inside that container control.
Question 1: How do I get a keydown event for "all" the controls in a form?
If the above puzzle is solved, then my problem is over.
This is what I can otherwise do:
Mainly pseudo code
foreach (Control c in this.Controls)
{
c.KeyDown += new KeyEventHandler(c_KeyDown);
if (c is Container control)
FunctionWhichGeneratesKeyDownForAllItsChildControls(c)
}
I know I will have to go through FunctionWhichGeneratesKeyDownForAllItsChildControls(c) many times over to get keydown for all controls if there are groupboxes inside a groupbox or so. I can do it. My question is,
Question 2: How do I check if c is a container control?
A: This is the same as Magnus' correct answer but a little more fleshed out. Note that this adds the handler to every control, including labels and container controls. Those controls do not appear to raise the event, but you may want to add logic to only add the handler to controls that accept user input.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
RegisterKeyDownHandlers(this);
}
private void RegisterKeyDownHandlers(Control control)
{
foreach (Control ctl in control.Controls)
{
ctl.KeyDown += KeyDownFired;
RegisterKeyDownHandlers(ctl);
}
}
private void KeyDownFired(object sender, EventArgs e)
{
MessageBox.Show("KeyDown fired for " + sender);
}
}
A: A simple recursive function should do it.
private void AddEvent(Control parentCtrl)
{
foreach (Control c in parentCtrl.Controls)
{
c.KeyDown += new KeyEventHandler(c_KeyDown);
AddEvent(c);
}
}
A: Here are some non-recursive options for traversing the control collection. My particular implementation is doing interface validation, but could be adapted to your purpose.
Why even mess with a non-recursive solution you say? Well I got a stack overflow error when debugging one day, so I looked at replacing it with a loop (which is considerably more difficult). As it turns out that error was a fluke and has never happened again
//recursive
//This is the simplest implementation, but the most memory hungry
private IEnumerable<DataObjects.Error> CheckErrors(Control.ControlCollection controls, ErrorProvider errorProvider)
{
var errors = new List<DataObjects.Error>();
foreach (var control in controls.Cast<System.Windows.Forms.Control>())
{
//insert your own business logic in here
var error = errorProvider.GetError(control);
if (!string.IsNullOrEmpty(error))
{
errors.Add(new DataObjects.Error(error, DataObjects.ErrorLevel.Validation));
}
//recursive call
errors.AddRange(CheckErrors(control.Controls, errorProvider));
//insert your own business logic in here
}
return errors;
}
//Breadth first - Does NOT require child node to have knowledge of parent
//Read through the controls at a given level and then blindly delve
//deeper until you reach the end of the rainbow
//order(max-tree-level-size) memory usage?
//tree-level-size, as in the # of nodes at a given depth
private IEnumerable<DataObjects.Error> CheckErrors_NonRecursive_NeverLookBack(Control control, ErrorProvider errorProvider)
{
var currentControls = control.Controls.Cast<Control>();
var errors = new List<DataObjects.Error>();
while (currentControls.Count() > 0)
{
foreach (var currentControl in currentControls)
{
//insert your own business logic in here
var error = errorProvider.GetError(currentControl);
if (!string.IsNullOrEmpty(error))
{
errors.Add(new DataObjects.Error(error, DataObjects.ErrorLevel.Validation));
}
//insert your own business logic in here
}
//replace currentControls with ALL of the nodes at a given depth
currentControls = currentControls.SelectMany(x => x.Controls.Cast<Control>());
}
return errors;
}
//Depth first - Does NOT require child to have knowledge of parent
//Approximate recursion by keeping a stack of controls, instead of a call stack.
//Traverse the stack as you would have with recursion
//order(tree-branch-size) memory usage? tree-branch-size as in the number of nodes
//that it takes to get from the root to the bottom of a given branch
private IEnumerable<DataObjects.Error> CheckErrors_NonRecursive(Control.ControlCollection controls, ErrorProvider errorProvider)
{
var controlStack = new Stack<Control.ControlCollection>();
var controlIndicies = new Stack<int>();
var errors = new List<DataObjects.Error>();
controlStack.Push(controls);
controlIndicies.Push(0);
while(controlStack.Count() > 0)
{
while(controlIndicies.First() < controlStack.First().Count)
{
var controlIndex = controlIndicies.Pop();
var currentControl = controlStack.First()[controlIndex];
//insert your own business logic in here
var error = errorProvider.GetError(currentControl);
if (!string.IsNullOrEmpty(error))
{
errors.Add(new DataObjects.Error(error, DataObjects.ErrorLevel.Validation));
}
//insert your own business logic in here
//update the fact that we've processed one more control
controlIndicies.Push(controlIndex + 1);
if(currentControl.Controls.Count > 0)
{
//traverse deeper
controlStack.Push(currentControl.Controls);
controlIndicies.Push(0);
}
//else allow loop to continue uninterrupted, to allow siblings to be processed
}
//all siblings have been traversed, now we need to go back up the stack
controlStack.Pop();
controlIndicies.Pop();
}
return errors;
}
//Depth first - DOES require child to have knowledge of parent.
//Approximate recursion by keeping track of where you are in the control
//tree and use the .Parent() and .Controls() methods to traverse the tree.
//order(depth(tree)) memory usage?
//Best of the bunch as far as I can (in memory usage that is)
private IEnumerable<DataObjects.Error> CheckErrors_NonRecursiveIndicesOnly(Control control, ErrorProvider errorProvider)
{
var errors = new List<DataObjects.Error>();
var controlIndicies = new Stack<int>();
var controlCount = new Stack<int>();
Control currentControl = control;
var currentControls = currentControl.Controls;
controlCount.Push(currentControls.Count);
controlIndicies.Push(0);
while (controlCount.Count() > 0)
{
while (controlIndicies.First() < controlCount.First())
{
var controlIndex = controlIndicies.Pop();
currentControl = currentControls[controlIndex];
//insert your own business logic in here
var error = errorProvider.GetError(currentControl);
if (!string.IsNullOrEmpty(error))
{
errors.Add(new DataObjects.Error(error, DataObjects.ErrorLevel.Validation));
}
//insert your own business logic in here
//update the fact that we've processed one more control
controlIndicies.Push(controlIndex + 1);
if (currentControl.Controls.Count > 0)
{
//traverse deeper
currentControls = currentControl.Controls;
controlCount.Push(currentControl.Controls.Count);
controlIndicies.Push(0);
}
else
{
//allow loop to continue uninterrupted, to allow siblings to be processed
}
}
//all siblings have been traversed, now we need to go back up the stack
controlCount.Pop();
controlIndicies.Pop();
//need to check our position in the stack... once we get back to the top there is no parent of parent.
if (controlCount.Count() > 0)
{
currentControls = currentControl.Parent.Parent.Controls;
}
//do nothing, believe it or not once you've gotten to this level you have traversed the entire stack
}
return errors;
}
A: The answer to question 2 is to use the GetType() method of the control you are checking.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: C++ error cleanup If I have a function I call when there is an error in my app, and I call ExitProcess in that function to exit. Do I need to find a way to have it call things like WSACleanup() and ReleaseMutex and RemoveFontMemResourceEx, and free other manually allocated variables?
I believe the system does this automatically when my application exits, but is there a reason i'd want to call these cleanup functions anyways?
And if I don't, do I need to even call them right before my application exits?
A: The title is "C++ error cleanup question", and there is a [c++] tag on it, so... Why aren't your resources (memory, network connections, mutexes, critical sections, etc.) handled by RAII?
If you have an error, then throw an exception, handle it higher on the stack if you can handle it, and let it crash the app if you can't (or catch it in the main, and exit the main gracefully with an error code).
Upon stack unwinding, all your RAII-protected resources will be cleaned away (so you won't have any resource leak).
The advantage of the solution is:
*
*You don't have to deal with resources yourself, as RAII does it automatically.
*If one day you believe you can handle an error, just catch the exception at the point you can handle it, and recover.
A: Most (all?) modern operating systems release most resources when a process exits, so most of the time it's safe to just exit. But there are reasons to release them explicitly.
First, if you use resource leakage detection tools (like valgrind for memory leaks for example), it's gonna give you false positives.
Second, if your code gets refactored in the future, you may forget about some resources and cause leakage.
So I think it's always a good idea to release resources as soon as you're done with them.
A: The atexit function might be useful - http://www.cplusplus.com/reference/clibrary/cstdlib/atexit/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Google map w/ circle that changes every second? How do I create a google map with a circle whose center changes every
second? I tried the below: (also at
http://test.barrycarter.info/sunstuff2.html)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
function updateJ () {
j = j+0.5;
x.center = new google.maps.LatLng(j,0);
}
function initialize() {
var myLatLng = new google.maps.LatLng(0,0);
var myOptions = {zoom:2,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
j = 20.18
x = new google.maps.Circle({
center: new google.maps.LatLng(j,-18.5037550725315),
radius: 10018760,
map: map,
strokeWeight: 2,
fillOpacity: 0.2,
fillColor: "#ffffff"
});
}
</script>
</head>
<body onload="initialize(); updateJ(); setInterval('updateJ()', 1000)">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
Firebug confirms that 'j' increases every second, but this line:
x.center = new google.maps.LatLng(j,0);
does nothing. Is there a google.maps.PleaseRedrawThisObjectBecauseIHaveChangedStuff method?
A: The API functions generally don't support manually setting properties. Try using the getter/setter functions like so:
x.setCenter(new google.maps.LatLng(j, 0));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: read xml in UTF-8 in scala I am trying to read a file to xml with the following code:
import scala.xml._
object HebrewToEnglishCityTranslator {
val data = XML.loadFile("cities_hebrew_utf.xml");
for(val entry <- data \\ "city") {
val hebrewName = (entry \\ "hebrew_name").text
val englishName = (entry \\ "english_name").text
println(hebrewName + "=" + englishName) }
However, my file is encoded in UTF-8 (hebrew chars) and XML encoding is val encoding = "ISO-8859-1"
what should I do?
A: Use the InputStream constructor instead of the String constructor. Good explanation of Stream vs. Reader xml reading here: Producing valid XML with Java and UTF-8 encoding
A: You should use XML.load(reader: java.io.Reader), which allows you to specify the file encoding:
XML.load(new java.io.InputStreamReader(new java.io.FileInputStream("cities_hebrew_utf.xml"), "UTF-8"))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Get local time from UTC datetime in ActionScript 3 Does AS3 have a way of converting a datetime variable into local time?
A: //Some date string you got from somewhere
var dateStr:String = "Sun Sep 25 22:30:33 GMT+0600 2011";
var date:Date = new Date(dateStr);
//Use date.toLocaleString() to get a local time string and create a new date from it
var localDate:Date = new Date(date.toLocaleString());
trace(localDate);'
Here's a link to date.toLocaleString() from Adobe
date.toLocaleString() Documentation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to select multiple columns without duplicates in one column in Oracle The problem:
I need find top client for supplier.
Top client has max items sum on all orders.
If supplier has 2 top clients, then top client will be with min order id, which means - who first created order and get max items - it will be top.
I was writing this sql code:
select s.s_id, c.c_id, min(o.o_id), count(*)
from suppliers s, clients c, orders o, items i
where s.s_id=c.id_s and c.c_id=o.id_c and o.o_id=i.id_o
group by s.s_id, c.c_id
order by 4 desc, 3
and get this result: http://imageshack.us/photo/my-images/148/32969388.jpg/
but i need to get: http://imageshack.us/photo/my-images/842/51815927.jpg/
A: You need to rank the order count and ID. So you should use an analytic and inline views. Something like:
select s_id
, c_id
, min_order_id
, no_of_orders
from (
select s_id
, c_id
, min_order_id
, no_of_orders
, rank() over (partition by s_id
order by no_of_orders DESC, min_order_id ASC) rnk
from (
select s.s_id
, c.c_id
, min(o.o_id) as min_order_id
, count(*) as no_of_orders
from suppliers s, clients c, orders o, items i
where s.s_id=c.id_s and c.c_id=o.id_c and o.o_id=i.id_o
group by s.s_id, c.c_id
)
)
where rnk=1
/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Modeless, parentless wxDialog still always above wxFrame window in z-order? My program opens a wxFrame-based window and multiple modeless and parentless wxDialog-based windows. It all works beautifully, except that the wxDialog-based windows insist on always being on top of the wxFrame-based one.
I know about wxDIALOG_NO_PARENT, and I'm using it. The dialogs stay open when I close the wxFrame, so they definitely don't have the wxFrame window as a parent.
(If it matters, I'm using C++, wxWidgets 2.8.something, and running it on Ubuntu Linux. My program isn't ready to compile on any other platform, so I haven't tested it on others yet.)
I want all the windows to operate entirely independently, so the user can use the wxFrame window as well as the wxDialog ones. Can anyone point me in the right direction?
A: It seems that this behavior comes from a difference in how Gnome handles windows with different "type hints"...it puts them into their own z-index groupings:
https://developer.gnome.org/gdk3/stable/gdk3-Windows.html#GdkWindowTypeHint
The dialog is created with GDK_WINDOW_TYPE_HINT_DIALOG while your other window is most likely created with GDK_WINDOW_TYPE_HINT_NORMAL. The point where this decision is made is in gtk/toplevel.cpp and it's being cued by the fact that the "extra" style flags contain wxTOPLEVEL_EX_DIALOG:
toplevel.cpp#L594
Those are the only two calls to gtk_window_set_type_hint in the wxWidgets GTK codebase, except for in the splash screen code. So changing the "extra" style bits after the fact isn't going to help. (The "correct" solution would be to patch wxWidgets so that adjusting wxTOPLEVEL_EX_DIALOG in the extra styles would do the proper adjustment to the window type hint.)
You can't use the wxDialog class without running through its constructor, which calls the non-virtual method wxDialog::Create, which sets the extra style to wxTOPLEVEL_EX_DIALOG and then goes directly to top level window creation:
dialog.cpp#L54
So I guess you have the option of trying this, which works if you haven't shown the dialog window yet:
#ifdef __WXGTK__
gtk_window_set_type_hint(
GTK_WINDOW(iShouldBeUsingQtDialog->GetHandle()),
GDK_WINDOW_TYPE_HINT_NORMAL);
#endif
...and if you have shown the dialog already, you need to use this for it to work:
#ifdef __WXGTK__
gdk_window_set_type_hint(
iShouldBeUsingQtDialog->GetHandle()->window,
GDK_WINDOW_TYPE_HINT_NORMAL);
#endif
Both cases will require you to add an include file into your source:
#ifdef __WXGTK__
#include "gtk/gtkwindow.h"
#endif
...and you'll have to update your build to find the GTK includes. On the command line for G++ I tried this and it worked:
pkg-config --cflags --libs gtk+-2.0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: iPhone how to invoke a classes static function by string? I have a static function defined in a class called "Character" as:
+ (UIImage) getImage;
I have a set of other classes that extend the “Character” class called “Bob” and “Jim”, each of these classes define a different file to get the image from. I need to be able to call get image based on the string e.g.
UIImage* image = [@“Jim” getImage];
However the above calls the getImage on the string class. I know it can be done like the following code snippet:
UIImage* image = [Jim getImage];
However I have a string not the object Jim. I suppose I could do a if statement that maps the string to a class but im wondering if there is a better way of dynamically calling a classes static function based on a string.
A: Use NSClassFromString:
UIImage* image = [NSClassFromString(@“Jim”) getImage];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: do you think http protocol mix character stream with byte stream is not a good design Firstly,when I say http protocol mix character stream with byte stream,I mean request head is character stream and request body is byte stream(specified by content-length ),they are seperated by an empty line.
This design make http implementation more difficult.For example,if you use java to implement an http server,you can't use such code because BufferedReader will buffer some bytes for read a line.
InputStream stream=socket.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(stream));
String line;
while( !(line=reader.readLine()).equals("") ){
//do something with line
}
//from stream to read content-length bytes
stream.read(...)
It would be more easy to implement http protocol if it use first two bytes to specified length of request head instead of use empty line.
A: It is not just bad design ... it is broken. The chances are that the BufferedReader will read the first part of the request body into its buffer. So when you read from the stream at the end, you won't get all of the body.
Once you have wrapped an InputStream you shouldn't use it directly ... especially if the wrapper does buffering.
The best way to implement this is to use an existing HTTP Server-side implementation. The Apache HTTP Components library is a good alternative to consider.
If you have to implement this yourself, then the simple solution is to:
*
*Wrap the InputStream in a BufferedInputStream.
*Use the BufferedInputStream to read the header lines a byte at a time and build up the lines and convert to a String yourself.
*Use the BufferedInputStream to read the body.
I feel that the stupid design of HTTP protocol makes the java.io library useless.
I wouldn't say that. The problem is that the HTTP protocol potentially requires a client to switch the way it interprets the characters / bytes of a request or response message halfway through the message. But if you think about it, that is not an unreasonable thing to do. The alternatives would be:
*
*to send separate messages which would increase the protocol overheads, or
*encode and send the request / response line and the headers as bytes rather than as characters.
What we really have is a tricky use-case that is too unusual to be supported in the generic java.io libraries. A protocol support library would take care of this ... if you were able to use one.
A: Yes, but it also would be easier to produce broken messages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Copying a file multiple times using loop; C/C++ I wanted to copy a file multiple times using different names.
The program is this:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include <sstream>
#include<cstring>
using namespace std;
main()
{
string text;
int i;
char ch;
ostringstream oss;
FILE *fp1,*fp2;
if((fp1=fopen("One Dollar.jpg", "rb"))==NULL)
{
cout<<"Error";
exit(-1);
}
for(i=1; i<=5; i++)
{
oss << "C:\\5241 Dollar\\One Dollar " << i << ".jpg";
text = oss.str();
if((fp2=fopen(text.c_str(), "wb"))==NULL)
{
cout<<"Error "<<i;
exit(-1);
}
while(!feof(fp1))
{
fread(&ch, 1, 1, fp1);
fwrite(&ch, 1, 1, fp2);
}
fclose(fp2);
/* for(int j=0;j<30000;j++)
for(int k=0;k<30000;k++)
if(k==3000)
cout<<k; */
}
fclose(fp1);
}
In this there are two file streams one of which is source and the other is destination.. I loaded the actual file in binary read mode and the destination as binary write mode. I used a for loop to do the work. But as soon as the loop iterates 2nd time, the file opening of fp2 fails. I'm getting the output: Error 2.
How can I make the code work?
A: You should open and close the first file in each iteration of the loop.
....
for(i=1; i<=5; i++)
{
if((fp1=fopen("One Dollar.jpg", "rb"))==NULL)
{
cout<<"Error";
exit(-1);
}
....
The reason is because at the end of the first iteration, the first file pointer is at the end of the file, so it won't see any data at the second iteration. You have to close and reopen the file (OR you can use seek to jump to the front of the file, but this is the simpler change since its a copy-and-paste)
EDIT: to the new question:
you need to reset the stringstream. In the second iteration you are trying to open
C:\\5241 Dollar\\One Dollar 1.jpgC:\\5241 Dollar\\One Dollar 2.jpg
which is invalid.
One solution is to bring the ostringstream declaration into the loop:
....
for(i=1; i<=5; i++)
{
if((fp1=fopen("One Dollar.jpg", "rb"))==NULL)
{
cout<<"Error";
exit(-1);
}
ostringstream oss;
oss << "C:\\5241 Dollar\\One Dollar " << i << ".jpg";
A: int main()
{
string text;
int i;
char ch;
ostringstream oss;
FILE *fp1,*fp2;
if((fp1=fopen("/home/maru/fact.cpp", "rb"))==NULL)
{
cout<<"Error";
exit(-1);
}
for(i=1; i<=5; i++)
{
oss << "/home/maru/fact" << i << ".cpp";
text = oss.str();
rewind(fp1);
cout<<text<<"\n";
if((fp2=fopen(text.c_str(), "wb"))==NULL)
{
cout<<"Error "<<i;
exit(-1);
}
while(!feof(fp1))
{
fread(&ch, 1, 1, fp1);
fwrite(&ch, 1, 1, fp2);
}
fclose(fp2);
oss.str("");
}
fclose(fp1);
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: libdvm.so location I have a linker error when trying to build my JNI application:
undefined reference to `JNI_GetCreatedJavaVMs'
From this thread I figured out that I need to use libdvm.so to resolve the issue. But I can't figure out where the libdvm.so is located.
I'm using Android NDK r6 on MacOS.
A: libdvm.so is part of Android's full build and it is available in build output folder at:
out/target/product/*/symbols/system/lib/libdvm.so
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Total Number of Row Resultset getRow Method Read the Following Code:
public class selectTable {
public static ResultSet rSet;
public static int total=0;
public static ResultSet onLoad_Opetations(Connection Conn, int rownum,String sql)
{
int rowNum=rownum;
int totalrec=0;
try
{
Conn=ConnectionODBC.getConnection();
Statement stmt = Conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
String sqlStmt = sql;
rSet = stmt.executeQuery(sqlStmt);
total = rSet.getRow();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println("Total Number of Records="+totalrec);
return rSet;
}
}
The folowing code dos't show actual total:
total = rSet.getRow();
my jTable display 4 record in jTable but total = 0; when I evaluate through debug, it shows:
total=(int)0;
rather than total=(int)4
And if I use
rSet=last(); above from the code total = rSet.getRow();
then total shows accurate value = 4 but rSet return nothing. then jTable is empty.
Update me!
A: The getRow() method retrieves the current row number, not the number of rows. So before starting to iterate over the ResultSet, getRow() returns 0.
To get the actual number of rows returned after executing your query, there is no free method: you are supposed to iterate over it.
Yet, if you really need to retrieve the total number of rows before processing them, you can:
*
*ResultSet.last()
*ResultSet.getRow() to get the total number of rows
*ResultSet.beforeFirst()
*Process the ResultSet normally
A: As others have answered there is no way to get the count of rows without iterating till the end. You could do that, but you may not want to, note the following points:
*
*For a many RDBMS systems ResultSet is a streaming API, this means
that it does not load (or maybe even fetch) all the rows from the
database server. See this question on SO. By iterating to the
end of the ResultSet you may add significantly to the time taken to
execute in certain cases.
*A default ResultSet object is not updatable and has a cursor
that moves forward only. I think this means that unless you
execute
the query with ResultSet.TYPE_SCROLL_INSENSITIVE rSet.beforeFirst() will throw
SQLException. The reason it is this way is because there is cost
with scrollable cursor. According to the documentation, it may throw SQLFeatureNotSupportedException even if you create a scrollable cursor.
*Populating and returning a List<Operations> means that you will
also need extra memory. For very large resultsets this will not
work
at all.
So the big question is which RDBMS?. All in all I would suggest not logging the number of records.
A: BalusC's answer is right! but I have to mention according to the user instance variable such as:
rSet.last();
total = rSet.getRow();
and then which you are missing
rSet.beforeFirst();
the remaining code is same you will get your desire result.
A: One better way would be to use SELECT COUNT statement of SQL.
Just when you need the count of number of rows returned, execute another query returning the exact number of result of that query.
try
{
Conn=ConnectionODBC.getConnection();
Statement stmt = Conn.createStatement();
String sqlStmt = sql;
String sqlrow = SELECT COUNT(*) from (sql) rowquery;
String total = stmt.executeQuery(sqlrow);
int rowcount = total.getInt(1);
}
A: You need to call ResultSet#beforeFirst() to put the cursor back to before the first row before you return the ResultSet object. This way the user will be able to use next() the usual way.
resultSet.last();
rows = resultSet.getRow();
resultSet.beforeFirst();
return resultSet;
However, you have bigger problems with the code given as far. It's leaking DB resources and it is also not a proper OOP approach. Lookup the DAO pattern. Ultimately you'd like to end up as
public List<Operations> list() throws SQLException {
// Declare Connection, Statement, ResultSet, List<Operation>.
try {
// Use Connection, Statement, ResultSet.
while (resultSet.next()) {
// Add new Operation to list.
}
} finally {
// Close ResultSet, Statement, Connection.
}
return list;
}
This way the caller has just to use List#size() to know about the number of records.
A: The getRow() method will always yield 0 after a query:
ResultSet.getRow()
Retrieves the current row number.
Second, you output totalrec but never assign anything to it.
A: You can't get the number of rows returned in a ResultSet without iterating through it. And why would you return a ResultSet without iterating through it? There'd be no point in executing the query in the first place.
A better solution would be to separate persistence from view. Create a separate Data Access Object that handles all the database queries for you. Let it get the values to be displayed in the JTable, load them into a data structure, and then return it to the UI for display. The UI will have all the information it needs then.
A: I have solved that problem. The only I do is:
private int num_rows;
And then in your method using the resultset put this code
while (this.rs.next())
{
this.num_rows++;
}
That's all
A: The best way to get number of rows from resultset is using count function query for database access and then rs.getInt(1) method to get number of rows.
from my code look it:
String query = "SELECT COUNT() FROM table";
ResultSet rs = new DatabaseConnection().selectData(query);
rs.getInt(1);
this will return int value number of rows fetched from database.
Here DatabaseConnection().selectData() is my code for accessing database.
I was also stuck here but then solved...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: Get child element in another child element of XML I have a XML file that goes like this... (the XML file was taken from web services [WCF] after passing some value into it.)
<Title>
<Questions>
<QuestionID> 1 </QuestionID>
<QuestionType> Quiz </QuestionType>
<Question> What is the shape? </Question>
<SubQuestionSequence> Part 1 </SubQuestionSequence>
<SubQuestions>
<Keywords> Ring </Keywords>
<ParentQuestionID> 1 </ParentQuestionID>
</SubQuestions>
<SubQuestionSequence> Part2 </SubQuestionSequence>
<SubQuestions>
<Keywords> Round </Keywords>
<ParentQuestionID> 1 </ParentQuestionID>
</SubQuestions>
</Questions>
</Title>
The methods to take child elements as below (written in C#), the commented area is supposed to call the class of subQuestion, but i'm not sure how to write that part :
public class Questions {
public int QuestionID { get; set; }
public string QuestionType { get; set; }
public string Question { get; set; }
public string SubQuestionSequence { get; set; }
//suppose to call subQuestion here
}
public class SubQuestion {
public string Keywords { get ; set ; }
public int ParentQuestionID { get; set; }
}
The actual code behind of the file, also the query area, i does not know how to call if they have another sub section:
void client_GetQuestionCompleted(object sender, GetQuestionCompletedEventArgs e)
{
if (e.Error != null)
return;
string result = e.Result.Nodes[0].ToString();
XDocument doc = XDocument.Parse(result);
var QuestionDetails = from Query in doc.Descendants("QuestionDetail")
select new Questions
{
QuestionID = (int)Query.Element("QuestionID"),
QuestionType = (string)Query.Element("QuestionType"),
Question = (string)Query.Element("Question"),
SubQuestionSequence = (string)Query.Element("SubQuestionSequence")
};
int z = 0;
foreach (var QuestionDetail in QuestionDetails)
{
qID = QuestionDetail.QuestionID;
qType = QuestionDetail.QuestionType;
quest = QuestionDetail.Question;
subQS = QuestionDetail.SubQuestionSequence;
z++;
}
}
As you can see from the top, how can i take the child elements of SubQuestions (The keywords and ParentQuestionID) where SubQuestion itself already is a child element ?
[edit] how can i retrieve the repeated element in the child element ? I want some part to loop and retrieve data, and some doesn't need to loop to retrieve.
int z = 0;
foreach (var QuestionDetail in QuestionDetails)
{
qID = QuestionDetail.QuestionID;
qType = QuestionDetail.QuestionType;
quest = QuestionDetail.Question;
subQS[z] = QuestionDetail.SubQuestionSequence;
//doing it this way, i can only retrieve one row of record only,
//even though i used an array to save.
subKeyword[z] = QuestionDetail.SubQuestion.Keywords;
z++;
}
A: As long as there is only a single SubQuestions element you can simply access Query.Element("SubQuestions").Element("Keywords") respectively Query.Element("SubQuestions").Element("ParentQuestionID").
[edit]
As for you class with an object of the type SubQuestion you would simply use
public class Questions {
public int QuestionID { get; set; }
public string QuestionType { get; set; }
public string Question { get; set; }
public string SubQuestionSequence { get; set; }
public SubQuestion SubQuestion{ get; set; }
}
public class SubQuestion {
public string Keywords { get ; set ; }
public int ParentQuestionID { get; set; }
}
and then in your query you can use e.g.
var QuestionDetails = from Query in doc.Descendants("QuestionDetail")
select new Questions
{
QuestionID = (int)Query.Element("QuestionID"),
QuestionType = (string)Query.Element("QuestionType"),
Question = (string)Query.Element("Question"),
SubQuestionSequence = (string)Query.Element("SubQuestionSequence"),
SubQuestion = new SubQuestion() {
Keywords = (string)Query.Element("SubQuestions").Element("Keywords"),
ParentQuestionID = (int)Query.Element("SubQuestions").Element("ParentQuestionID")
}
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: bring page to foreground? multipage editor I'm develpping an RCP user interface. I have a multipage editor in which pages are editors (EditorPart). From a first page in my multipage editor I want to open a second one if a button is pressed. I've managed to do that but the problem that I'm facing is that the created page is visible only if we switch to it, i.e only the tab is visble.. what I want is to directly switch to the new page automatically after its creation. In other words, how can I bring the new page to foreground exactly when it is created.
Can you help me please
Kind Regards,
Jean
A: It seems to me that the calling the method org.eclipse.ui.part.MultiPageEditorPart.setActivePage(int) should do the trick.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Entity Error in GDataDB example Im getting the error "the type or namespace name 'Entity' could not be found" from the following code snippet.
So ive added the reference "System.Data.Entity" but its still not working...
Why is that?
Error 1 The type or namespace name 'Entity' could not be found (are you missing a using directive or an assembly reference?)...
using System;
using System.Linq;
using GDataDB;
using GDataDB.Linq;
using System.Data.Entity;
....
Console.WriteLine("Connecting");
var client = new DatabaseClient("you@gmail.com", "password");
const string dbName = "testing";
Console.WriteLine("Opening or creating database");
var db = client.GetDatabase(dbName) ?? client.CreateDatabase(dbName);
const string tableName = "testtable";
Console.WriteLine("Opening or creating table");
var t = db.GetTable<Entity>(tableName) ?? db.CreateTable<Entity>(tableName);
Console.WriteLine("Feed url for this table is '{0}'", t.GetFeedUrl());
var all = t.FindAll();
Console.WriteLine("{0} elements", all.Count);
....
A: There is no using System.Data.Entity; in the GDataDB sample app, and never has been, so either you or some automated tool added it.
So simply remove it.
If you're missing the Entity type, make sure you get the whole sample project and not just Program.cs
GDataDB has no relationship to EF or LINQ-to-SQL at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Xcode: Loading TabBarItem titles after ordering I'm using this [tutorial] to save user's customized TabBarItems order as my app has more than 5 tabs
The tutorial's concept is to save the TabBarItem titles in the NSUserDefault and load them next time app is opened.
It's working great for english language as my TabBarItem titles are set initially in the XIB file
But the problem is that when my app's other language is loaded, as TabBarItem titles are changed to the selected language upon starting the app
Thus when the titles got saved after re-ordering the TabBarItems for the language that is different than the titles set in the XIB file, the TabBarItem are not loaded at all next time the app started! Which I think the tutorial I used is only work for TabBarItem titles when they are identical to TabBarItem titles defined in XIB file, not when those TabBarItem titles got changed programmatically based on the app language!
- (void)applicationWillTerminate:(UIApplication *)application {
NSMutableArray *savedOrder = [NSMutableArray arrayWithCapacity:tabController.viewControllers.count];
NSArray *tabOrderToSave = tabController.viewControllers;
for (UIViewController *aViewController in tabOrderToSave) {
[savedOrder addObject:aViewController.tabBarItem.title];
}
[[NSUserDefaults standardUserDefaults] setObject:savedOrder forKey:@"savedTabOrder"];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self setTabOrderIfSaved];
}
- (void)setTabOrderIfSaved {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *savedOrder = [defaults arrayForKey:@"savedTabOrder"];
NSMutableArray *orderedTabs = [NSMutableArray arrayWithCapacity:tabController.viewControllers.count];
if ([savedOrder count] > 0 ) {
for (int i = 0; i < [savedOrder count]; i++) {
for (UIViewController *aController in tabController.viewControllers) {
if ([aController.tabBarItem.title isEqualToString:[savedOrder objectAtIndex:i]]) {
aController.tabBarItem.title = NSLocalizedString(aController.tabBarItem.title, nil);
[orderedTabs addObject:aController];
}
}
}
tabController.viewControllers = orderedTabs;
}
}
A: Try using the tabBarItem's tag property instead.
aController.tabBarItem.tag
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create custom annotation and callout bubble in iphone? I want to create a customized annotation and callout bubble on MKMapView. I need to use a customized view rather than default annotation pin and annotaion view(which is limited to show only title and a single line description). When user tap on an annotation, I would like to display more information on the callout bubble.
A: I passed by this control but I haven't used it:
http://cocoacontrols.com/platforms/ios/controls/custom-callout
I've found some pretty good controls at that site.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wait for ajax to complete before method return I know I can set the call to synchronous, or wrap everything preceeding in the complete() callback, but it seems inelegant. Here's what i've got:
_loadShader: (url) ->
(@_loadResource url, false).complete (e) ->
vert = e.responseText.split '[Vertex shader]'
frag = vert[1].split '[Fragment shader]'
vertex: frag[0]
fragment: frag[1]
_loadResource: (url, async) ->
url = 'Public/' + url
$.ajax
url: url
dataType: 'text'
async: async or true
complete:
@
_loadShader() returns the XHR object, but what I really want is for it to not return until complete() gets fired - even if that means locking the browser. What I do with the result is important, and I don't want to start wrapping my code up in callbacks.
edit: re-jigged to this, does precisely what I was after:
_loadShader: (url, e) ->
result = @_loadResource url, false
vert = result.split '[Vertex shader]'
frag = vert[1].split '[Fragment shader]'
shader =
vertex: frag[0]
fragment: frag[1]
_loadResource: (url, async = true) ->
url = 'Public/' + url
xhr = $.ajax
url: url
dataType: 'text'
async: async
return xhr.responseText
A: What happens is
*
*You call $.ajax with async: false
*The server responds, and jQuery runs any callbacks you've passed to $.ajax
*The _loadResource function returns. You then attach a complete callback to the XHR object it returned. But because all XHR callbacks were already run, this has no effect.
You should, instead, pass in your complete callback as an argument to _loadResource, and have it provide that callback to $.ajax. So the call becomes
@_loadResource url, false, (e) -> ...
and the function definition becomes
_loadResource: (url, async = true, complete = (->)) ->
$.ajax {url, dataType: 'text', async, complete}
A: I never found better solution, than setting private variable to function and then setting that variable to data in jquery callback.
Code would look like this:
_loadResource: (url) ->
resource = null #will cause resource to be private variable of _loadResource, not of callback.
$.ajax
url: url
async: false
success: (data) ->
resource = data #setting resource to what jquery got from server.
resource #returning resource.
It compiles to:
_loadResource: function(url) {
var resource;
resource = null;
$.ajax({
url: url,
async: false,
success: function(data) {
return resource = data;
}
});
return resource;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create a basic application that will act as a tutorial for how to use another app I have a very particular application I have developed. I want to create a second app, ideally in visual basic, that provides a tutorial/ guide on how to use my original app step by step.
I imagine PowerPoint slide style images embedded in a simple window with forward & back controls.
I have experience in java, C & VB. Ideally the app needs be be kept simple and written in VB. Can anyone recommend a starting point, or if any tutorials for such exist? I've had a search and nothing stands out.
Thanks.
A: So, if this essentially just has slides and annotations and forward/backward buttons, why try to write an app for this? (I get that it might be fun to try.) You could simply do screen captures and annotate them and use PowerPoint and create an executable out of that to run.
You can even, I understand, create hyperlinks and such to allow the slide show to progress more like the real app does. I'm no "power point ranger" so I'd point you at the Office docs to learn about that, but I've seen some pretty good tutorials using this method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Password strength validator, how would you improve this? First of all, I am validating password length with StringLength validator so I want to keep that out of the PasswordStrength validator. Any ideas how to improve this?
I think my approach with arrays and array_diff is not very elegant but the only other way I can think of are regular expressions which is even more ugly.
<?php
class My_Validate_PasswordStrength extends Zend_Validate_Abstract
{
const MSG_NO_NUMBER = 'msgNoNumber';
const MSG_NO_LOWER_CASE_LETTER = 'msgNoLowerCaseLetter';
const MSG_NO_UPPER_CASE_LETTER = 'msgNoUpperCaseLetter';
protected $_messageTemplates = array(
self::MSG_NO_NUMBER => "'%value%' must contain at least one number",
self::MSG_NO_LOWER_CASE_LETTER => "'%value%' must contain at least one lower case letter",
self::MSG_NO_UPPER_CASE_LETTER => "'%value%' must contain at least one upper case letter"
);
public function isValid($value)
{
$this->_setValue($value);
$arr = str_split($value);
$numbers = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
$lowerCaseLetters = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
$upperCaseLetters = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
if (count(array_diff($numbers, $arr)) === 10) {
$this->_error(self::MSG_NO_NUMBER);
return FALSE;
}
if (count(array_diff($lowerCaseLetters, $arr)) === 26) {
$this->_error(self::MSG_NO_LOWER_CASE_LETTER);
return FALSE;
}
if (count(array_diff($upperCaseLetters, $arr)) === 26) {
$this->_error(self::MSG_NO_UPPER_CASE_LETTER);
return FALSE;
}
return TRUE;
}
}
A: I don't think regular expressions have to be ugly.
public function isValid($value)
{
$this->_setValue($value);
if (preg_match('/[0-9]/', $value) !== 1) {
$this->_error(self::MSG_NO_NUMBER);
return FALSE;
}
if (preg_match('/[a-z]/', $value) !== 1) {
$this->_error(self::MSG_NO_LOWER_CASE_LETTER);
return FALSE;
}
if (preg_match('/[A-Z]/', $value) !== 1) {
$this->_error(self::MSG_NO_UPPER_CASE_LETTER);
return FALSE;
}
return TRUE;
}
A: How about these tests to improve strength? At a customer we had the requirement "passwords must contain at least 1 number, 2 capital letters, at least 1 'special character' and be longer than 8 characters"
These expressions count each of those requirements - the third counting all non letters/numbers
$capCount = preg_match_all("/[A-Z]/", $newPassword, $matches);
$numCount = preg_match_all("/[0-9]/", $newPassword, $matches);
$specCount = preg_match_all("/[^0-9a-zA-z]/", $newPassword, $matches);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: NSArrayController for polymorphic class I have the following (stripped down) class interfaces:
@interface ScriptEvent : NSObject {
...
}
@interface SingleLine : ScriptEvent {
NSString *line;
}
@interface MultiLine : ScriptEvent {
NSArray *lines;
}
Another parent class holds an NSArray containing a list of ScriptEvents (which will either be SingleLine or MultiLine).
In my XIB I have an NSArrayController bound to this list of ScriptEvents and I want to set up a master/detail arrangement. So I have an NSTableView linking to this NSArrayController and I want to show a different detail panel depending on whether the selected member of the NSArrayController is a SingleLine or a MultiLine.
Is this possible?
A: Check if the selected member is a SingleLine or a MultiLine with:
if([objectToCheck isKindOfClass:[SingleLine class]]){
//Do some staff
}else if([objectToCheck isKindOfClass:[MultiLine class]]){
//
}else{
//
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Validation only in specific form Is there any way to trigger validation only in specific forms(controller's action), not globally at every save or update?
Something like User.create(:validate=>true) flag.
A: Yes, you can supply conditionals to the validations, eg:
validates_presence_of :something, :if => :special?
private
def make_sepcial
@special = true
end
def special?
@special
end
Now all you have to do to turn on these validations is:
s = SomeModel.new
s.make_special
A: As you explained in the comments, you want to skip validation for new records. In that case, you can use thomasfedb's answer, but don't use the @special variable, but:
validates_presence_of :something, :if => :persisted?
This will validate only for saved Users, but not for new Users. See the API documentation on persisted?.
A: This is a bit old. But I found http://apidock.com/rails/Object/with_options to be a good way of handling this sort of behaviour.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Simulate more than 2 touches on iPad/iPhone simulator Is it possible to simulate more than 2 touches on either the iPad or iPhone simulators?
Holding down the ALT key allows 2 touches but no more.
A: The default sim doesn't support more than 2 touches. But there is a 3rd party simulator called iSumulate which supports multi-touch.
Website: http://www.vimov.com/isimulate/
iTunes App Page: http://itunes.apple.com/us/app/isimulate/id306908756?mt=8
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem using regex to remove number formatting in PHP I'm having this issue with a regular expression in PHP that I can't seem to crack. I've spent hours searching to find out how to get it to work, but nothing seems to have the desired effect.
I have a file that contains lines similar to the one below:
Total','"127','004"','"118','116"','"129','754"','"126','184"','"129','778"','"128','341"','"127','477"','0','0','0','0','0','0
These lines are inserted into INSERT queries. The problem is that values like "127','004" are actually supposed to be 127,004, or without any formatting: 127004. The latter is the actual value I need to insert into the database table, so I figured I'd use preg_replace() to detect values like "127','004" and replace them with 127004.
I played around with a Regular Expression designer and found that I could use the following to get my desired results:
Regular Expression
"(\d+)','(\d{3})"
Replace Expression
$1$2
The line on the top of this post would end up like this: (which is what I am after)
Total','127004','118116','129754','126184','129778','128341','127477','0','0','0','0','0','0
This, however, does not work in PHP. Nothing is being replaced at all.
The code I am using is:
$line = preg_replace("\"(\d+)','(\d{3})\"", '$1$2', $line);
Any help would be greatly appreciated!
A: There are no delimiters in your regex. Delimiters are required in order for PHP to know what is the pattern to match and what is a pattern modifier (e.g. i - case-insensitive, U - ungreedy, ...). Use a character that doesn't occur in your pattern, typically you'll see a slash '/' used.
Try this:
$line = preg_replace("/\"(\d+)','(\d{3})\"/", '$1$2', $line);
A: You forgot to wrap your regular expression in front-slashes. Try this instead:
"/\"(\d+)','(\d{3})\"/"
A: use preg_replace("#\"(\d+)','(\d+)\"#", '$1$2', $s); instead of yours
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why are pointers not needed for structures and primitve types? On C and Objective-C, why aren't pointers needed for structures and primite types?
A: Primitive types can be on the stack (no pointer) or on the heap (pointer), Obj-C objects can only be on the heap (pointer).
In some languages such as C++ objects can be on either the stack or heap. In yet other languages all objects are on the heap and no pointer (*) character is required.
There is a minor exceptions for blocks in Obj-C in that they can be on either the stack or heap.
A: Because that is the nature of those objects.
structs and arrays, in most ways are pointers to memory configured in the order you describe when you define the struct or array.
primitive types just hunks of memory big enough to store the type of information you request.
Obj-c objects are pointers because you only get their address and then send them messages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Rendering tabs (jquery ui) with Backbone.js & underscore.js I'm currently playing with strophe.js, backbone.js & wijmo (UI library based on jquery UI) and working on a chat interface. I have two dialog boxes, one is the contacts list, the other one will be the chat container. Chat will be organized in tabs with the classic jquery UI markup:
<div id="tabs">
<ul>
<li><a href="#tabs-1">Chat 1</a></li>
<li><a href="#tabs-2">Chat 2</a></li>
<li><a href="#tabs-3">Chat 3</a></li>
</ul>
<div id="tabs-1"><!-- Content chat 1 --></div>
<div id="tabs-2"><!-- Content chat 2 --></div>
<div id="tabs-3"><!-- Content chat 3 --></div>
</div>
Each individual chat container will contain a participants list (multi-user chat), the messages and a form.
Being fairly new to Backbone & underscore, I'm wondering what's the best way to handle this. I started with a Chat model, a Chats collection, a chat view and a chat list view but I don't find a proper way to render the tabs and keep it updated.
Any ideas ?
A: Use a router.
Create a View class for a chat. Each chat will get its own view and its own tabs. On update, the render() function for the view updates the chat, even if it's not visible to the user.
The code I use for managing tabs looks like this:
hide: ->
if @el.is(":visible") == false
return null
$('#' + @id + '-tab').removeClass('activetab').addClass('inactiveTab')
$.Deferred((dfd) =>
@el.fadeOut('fast', dfd.resolve)
).promise()
show: ->
if (@el.is(':visible'))
return
$('#' + @id + '-tab').removeClass('inactiveTab').addClass('activetab')
$.Deferred((dfd) =>
@el.fadeIn('fast', dfd.resolve)
).promise()
This is what goes into the view. Each view gets a slugified name. Note the use of "Deferred," the jQuery library. I'll discuss that later.
In your Router, define a route for chats:
'chat/:chatid': 'switchOrStartChat'
And the methods:
fadeAllViews: () ->
_.select(_.map(@views, (v) -> v.hide()), (t) -> t != null)
switchOrStartChat: (chatid) ->
chat = @views[chatid] ||= new ChatView({chatid: chatid})
$.when.apply(null, this.fadeAllViews()).then(() -> view.show())
You can generalize this further, of course, but the idea is that whenever you switch tabs, you just toggle a method to hide everything that's visible, and then (the Deferred makes sure this happens in the right order) show the one thing that's not. The tabs are maintained by each view; you'll have to do a little finagling as they'll probably be outside the actual DIV maintained by the View, but that's pretty simple. You'll have to write a separate template for your tab objects to create tab DOM objects with IDs that contain your chatid slug, but that's easily managable.
I wrote a tutorial on this kind of one-page design: The Backbone Store (link goes to the Javascript version, although I'm a coffeescript partisan these days), where I also discuss using this technique to find and modify slug-based navigation aids such as tabs, breadcrumbs, and the like.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: is there anyway to have just right or just left horizontal space using ckeditor I am using ckeditor and I have a number of pictures in my content. One issue i see is that you have the ability to add horizontal or vertical space around a picture but you can't just set a right or just a left horizontal picture. Normally if I have a picture on the left side of a page and the content to the right, I would just want to set the right margin (to avoid the image being indented on the left)
from looking at the ckeditor demo, I only see the ability to set the space on both sides of the picture. Is there anyway around this without having to do custom css as I want to give this feature for non technical users?
A: this uses custom css, but its in the ckeditor ui; right click on the image, click on the advanced option tab; change the margins to fit your needs. flushed left, margin-left:0; flushed right will be margin-right:0
A: When we right click image in ckeditor demo, It is showing one option as image properties. When we click on this a model window will popup. This model window has alignment property. One can set it to left or right as required.
Hope this will help you.
A: What if we put 0 in hspace and 0 in vspace and adjust alignment = left|right.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: heapq.merge: after merge the result of merge, the original merge is empty First I created two results of a & b by using heapq.merge, but after mergeing a&b, I found the list of a is empty.
>>> a=merge([1,2],[3,4])
>>> b=merge([4,5],[6,7])
>>> list(a)
[1, 2, 3, 4]
>>> merge(a,b)
<generator object merge at 0x365c370>
>>> list(a)
[]
>>>
The final result of list(a) is empty, why does merge(a,b) change a?
A: As the documentation (and the output on merge(a,b) in your example) indicates, the result of merge is an iterator. Iterators can only be consumed once, you can't reset or rewind them, and even if you could, your code doesn't do it. (Of course you can have several independent iterators for a given collection, at least if the collection supports it).
The first two merge calls return generators, the third call consumes those generators, and hence a and b are exhausted afterwards. (Actually, list(a) consumes a first, so in that snippet merge(a, b) will only see the items of b, but the idea is the same.) It doesn't mean to, and if you pass e.g. a list it won't be changed. But consuming an iterator means mutating it.
A: >>> a=heapq.merge([1,2],[3,4])
>>> b = heapq.merge([4,5], [6,7])
>>> list(a)
[1, 2, 3, 4]
>>> heapq.merge(a,b)
<generator object merge at 0x7f083da50f50>
>>> list(a)
[]
>>> list(b)
[4, 5, 6, 7] // before you consume the iterator of b
>>> list(b)
[] // after you consume the iterator of b
A: Your a is not a list but an iterator. If you use it once, you cannot iterate with it a second time. This has nothing to do with merge; you see the same effect here:
>>> a=merge([1,2],[3,4])
>>> list(a)
[1, 2, 3, 4]
>>> list(a)
[]
A: The return value of heapq.merge is an iterator. When you apply list to an iterator, it is consumed. An iterator is good for one pass over the set of values. So the second time list(a) is called, the result is empty.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Canvas distorts drawing. How do I get the scale factor between the set size and the styled size? I have this canvas:
<canvas id="game" width="280" height="280"></canvas>
The css styles the canvas via:
canvas
{
width: inherit;
height: 280px;
}
As the width can change, the canvas distorts the drawing. I need to know how to compensate for this. Anyone who can help me?
A: This is the same problem that the Mozilla Bespin team ran into. (back when they were using Canvas, before it merged with Ace)
Don't give the Canvas any CSS width/height rules. Doing so usually ends up as a pain. Put the Canvas in a Div that only has a single thing in it (the canvas itself)
As the canvas-parent div changes size, change the size of the canvas (canvas.width and canvas.height) to match the size of the div.
Since most browsers do not fire an event when a div changes size, you'll simply have to check, say, every half second with a timer to see if the div has changed size. If it has, then you resize the canvas accordingly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Why does this image not displaying (broken image icon)? I am trying to display an image that I saved to Datastore with DisplayImage handler below but I only see a broken image link. Do you know why? Thanks!
class HomePage(db.Model):
thumbnail = db.BlobProperty()
firm_name = db.StringProperty()
...
class ImageUpload(webapp.RequestHandler):
def get(self):
...
self.response.out.write("""
<form action="/imagesave" enctype="multipart/form-data" method="post">
<div><label>firm name:</label> <input type="text" name="firm_name" size=40></div>
<div><input type="file" name="img" /></div>
<div><input type="submit" value="Upload image"></div>
</form>
""")
class ImageSave(webapp.RequestHandler):
def post(self):
homepage = HomePage()
thumbnail = self.request.get("img")
firm_name = self.request.get("firm_name")
homepage.thumbnail = db.Blob(thumbnail)
homepage.firm_name = firm_name
homepage.put()
self.redirect("/imageupload")
class ImageResize(webapp.RequestHandler):
def post(self):
q = HomepageImage.all()
q.filter("firm_name", "mta")
qTable = q.get()
if qTable:
qTable.thumbnail = db.Blob(images.resize(self.request.get("img"), 32, 32))
db.put(qTable)
else:
self.response.out.write("""firm not found""")
self.redirect("/imageupload")
class DisplayImage(webapp.RequestHandler):
def get(self):
query = HomePage.all()
query.filter("firm_name", "mta")
result = query.get()
self.response.out.write("""firm name: %s""" % result.firm_name)
self.response.out.write("""<img src="img?img_id=%s"></img>""" %
result.key())
...
A: To serve an image from blobstore, use get_serving_urlor if you have a blobproperty you can have a look at my old code that used to serve my blobproperties from an image class back before when there was no blobstore:
class Image(db.Model):
name = db.StringProperty()
desc = db.StringProperty()
owner = db.UserProperty()
secret = db.StringProperty()
full = db.BlobProperty()
full_ext = db.StringProperty()
small = db.BlobProperty()
small_ext = db.StringProperty()
thumb = db.BlobProperty()
thumb_ext = db.StringProperty()
published = db.BooleanProperty()
added = db.DateTimeProperty(auto_now_add=True)
modified = db.DateTimeProperty(auto_now=True)
def thumb_name(self):
return '%s.%s' % (self.key(), self.thumb_ext)
def small_name(self):
return '%s_small.%s' % (self.key(), self.small_ext)
def full_name(self):
return '%s_full.%s' % (self.key(), self.full_ext)
class UploadImage(webapp.RequestHandler):
def post(self, key):
im = db.get(db.Key(key))
if not im:
self.error(404)
return
if self.request.POST['id'] != im.secret:
self.error(400)
return
file_data = self.request.POST['file'].file.read()
if self.request.POST['size'] == '100x100':
im.thumb = file_data
a = 'small'
elif self.request.POST['size'] == '500x500':
im.small = file_data
a = 'full'
if im.small and im.thumb:
im.published = True
im.save()
logging.info("%s updated %s" % (im.key(), a) )
self.response.out.write("ok")
mimetypes = {
'jpeg': 'image/jpeg',
'jpg': 'image/jpeg',
'tiff': 'image/tiff',
'tif': 'image/tiff',
'gif': 'image/gif',
'png': 'image/png',
}
class ServeImage(webapp.RequestHandler):
def get(self, key, sz, ext):
im = db.get(db.Key(key))
if not im:
self.error(404)
return
if sz == '.':
d = im.thumb
elif sz == '_small.':
d = im.small
elif sz == '_full.':
d = im.full
else:
raise Exception('wrong sz %r' % sz)
if not d:
d = im.full
else:
self.response.headers.add_header("Expires", "Thu, 01 Dec 2014 16:00:00 GMT")
self.response.headers["Content-Type"] = mimetypes[ext]
self.response.out.write(d)
A: This question was answered by systempuntoout in my followup question. He noted that I was pointing the image source to a not defined wrong img route.
The correct link should point to /image like this:
<img src="/image?img_id=%s"></img>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cropping tool/script for PHP/Javascript I am looking for a decent image cropping solution, ideally a script that would do the following :
Allow to upload an image (ideally via ajax), crop the image using some jQuery like cropping tool and then save the 'new' cropped image while retaining the image untouched.
Is there anything people could recommend?
A: Use Pixastic for client-side image processing.
Edit
It sounds like you might be looking for an image crop GUI for users, rather than a way to programmatically crop images (as I read your question originally). In that case, there are a variety of jQuery plugins that provide this; jrac seems to be a reasonably up-to-date one.
A: you can check here it is good tool
http://deepliquid.com/content/Jcrop_Download.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way to configure a JavaEE project to run with a default target runtime? I'm developing a JavaEE system with several applications which consists of many projects (EARs, EJBs, etc).
Whenever I change my runtime target of the Enterprise Server I have to reconfigure each project through Eclipse's wizards, and this takes forever.
For now I use a little script which updates the runtime target manually, although it says here:
The target runtime environment is specified in the org.eclipse.wst.common.project.facet.core.xml file in the project's .settings folder. You should not edit this file manually; instead, use the properties window as described in this topic.
Why am I changing the runtime target name?
1. I've upgraded the runtime target.
2. Another member of my team co the code from the SVN and he has a different name for the target runtime.
Is there a way to configure the projects to run with a default runtime target, which can be easily configured?
A: Possible workaround for 2: remove the org.eclipse.wst.common.project.facet.core.xml from SVN and put its name in the svn:ignore property.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: AS3: Random Point on Irregular Shape I have a MovieClip holding an irregular shape such as this one:
I need to generate a random point on this shape.
I can use brute force by generating points within the bounding box and then hitTesting to see if they reside on the irregular shape. However, I'm sure there's a more efficient way to tackle this problem.
What is the most efficient way to generate a random point on an irregular shape?
A: You mentioned hitTest, but I assume you meant hitTestPoint().
If so, a function go get the random points you mention, would look a bit like this:
function getRandomPointsInClip(target:MovieClip,numPoints:int):Vector.<Point>{
var points:Vector.<Point> = new Vector.<Point>(numPoints,true);
var width:Number = target.width,height:Number = target.height;
for(var i:int = 0; i < numPoints ; i++){
var point:Point = new Point(target.x+Math.random() * width,target.y+Math.random() * height);
if(target.hitTestPoint(point.x,point.y,true)) points[i] = point;//is the random coord inside ?
else i = i-1;//nope, go back one step - > retry above until it is inside
}
return points;
}
The other I hinted at in my comment involves looping through non transparent pixels in a bitmap data of your object. This method would insure you don't have many duplicates, as opposed to the previous method, but it also means, you have less control over the number of points created and there's extra memory used for creating the bitmap. Still, for documentation purposes, here is the function:
function getGridPointsInClip(target:MovieClip,res:int,offset:Number = 3):Vector.<Point>{
var points:Vector.<Point> = new Vector.<Point>();
var x:int,y:int,alpha:int,w:int = int(target.width),h:int = int(target.height);
var bmd:BitmapData = new BitmapData(w,h,true,0x00FFFFFF);bmd.draw(target);
var pixels:Vector.<uint> = bmd.getVector(bmd.rect),numPixels:int = w*h;
for(var i:int = 0; i < numPixels; i+=res) {
x = i%bmd.width;
y = int(i/bmd.width);
alpha = pixels[i] >>> 24;
if(alpha > 0) points.push(new Point(x+random(-offset,offset),y+random(-offset,offset)));
}
return points;
}
function random(from:Number,to:Number):Number {
if (from >= to) return from;
var diff:Number = to - from;
return (Math.random()*diff) + from;
}
And here'a very basic test:
var pts:Vector.<Point> = getRandomPointsInClip(mc,300);
//var pts:Vector.<Point> = getGridPointsInClip(mc,100,4);
for(var i:int = 0 ; i < pts.length; i++) drawCircle(pts[i].x,pts[i].y,3,0x009900);
function getRandomPointsInClip(target:MovieClip,numPoints:int):Vector.<Point>{
var points:Vector.<Point> = new Vector.<Point>(numPoints,true);
var width:Number = target.width,height:Number = target.height;
for(var i:int = 0; i < numPoints ; i++){
var point:Point = new Point(target.x+Math.random() * width,target.y+Math.random() * height);
if(target.hitTestPoint(point.x,point.y,true)) points[i] = point;//is the random coord inside ?
else i = i-1;//nope, go back one step - > retry above until it is inside
}
return points;
}
function getGridPointsInClip(target:MovieClip,res:int,offset:Number = 3):Vector.<Point>{
var points:Vector.<Point> = new Vector.<Point>();
var x:int,y:int,alpha:int,w:int = int(target.width),h:int = int(target.height);
var bmd:BitmapData = new BitmapData(w,h,true,0x00FFFFFF);bmd.draw(target);
var pixels:Vector.<uint> = bmd.getVector(bmd.rect),numPixels:int = w*h;
for(var i:int = 0; i < numPixels; i+=res) {
x = i%bmd.width;
y = int(i/bmd.width);
alpha = pixels[i] >>> 24;
if(alpha > 0) points.push(new Point(x+random(-offset,offset),y+random(-offset,offset)));
}
return points;
}
function random(from:Number,to:Number):Number {
if (from >= to) return from;
var diff:Number = to - from;
return (Math.random()*diff) + from;
}
function drawCircle(x:Number,y:Number,radius:Number,color:uint):void{
graphics.lineStyle(1,color);
graphics.drawCircle(x-radius,y-radius,radius);
}
HTH
A: If you think of some non-blob like shapes, it's clear the check random pixel, try again method isn't really a good way. The bounding box area could be huge compared to the shape area.
What you could do to improve the effectiveness is getting a vector of the BitmapData of the shape. It should contain all pixels of the bounding box. Update - it would be nice now if we could pick a random point, and remove it from the vector if it isn't inside the shape. Unfortunately the vector only contains the pixels' colour, not the position which is implicit and only correct if we don't change the vector's length. Since we don't need to know the actual colour, we can omit all transparent pixels and store an inside pixel's position as it's value in the vector. This way we don't need to create a new object for each pixel of the shape (that would be quite expensive!).
var v:Vector.<uint> shapeBoxBitmap.getVector(shapeBoxBitmap.rect);
var pixelNum:int = v.length;
for(var i:uint = 0; i < pixelNum; i++) {
if( v[i] && 0xFF000000 == 0) { // transparent pixel, outside off shape
v.splice(i,1);
} else {
v[i] = i;
}
}
//get random point
var randomPixel:int = v[Math.floor(Math.random()*v.length)];
var point:Point = new Point(randomPixel%shapeBitmap.width,int(randomPixel/shapeBitmap.width));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Output an array I have created a shortlist feature which acts a bit like a shopping cart. I output the items in the shortlist by:
$i = 0;
while ($i < $countArray){
echo $_SESSION['shortlistArray'][$i]." <a href='shortlistRemoveItem.php?arrayID=$i'>[x]</a><br />";
$i++;
}
and delete an item by
$arrayID = $_GET["arrayID"];
unset($_SESSION['shortlistArray'][$arrayID]);
The problem is that when I delete an item from an array such as $_SESSION['shortlistArray'][2] the output is all messed up as the array is no londer sequential. Should I recode the way my array is outputted or the way I am deleting an item from an array?
A: The most efficient solution would be simply changing the way your array is outputted:
foreach($countArray as $key => $item){
echo $_SESSION['shortlistArray'][$key]." <a href='shortlistRemoveItem.php?arrayID=$key'>[x]</a><br />";
}
If you insist on changing the way you are deleting an item from the array, consider this alternative:
$arrayID = $_GET["arrayID"];
$tempArray = array();
foreach($countArray as $key => $item){
if($arrayID == $key) continue;
$tempArray[] = $item;
}
$_SESSION['shortlistArray'] = $tempArray;
I' recommend the first option though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# generate a public and private keys for the DSA encryption algorithm How do I generate a public and a private key for the DSA algorithm in byte array format?
A: In DSA algorithm (from wiki):
*
*Public key is (p, q, g, y).
*Private key is x.
var dsa = new DSACryptoServiceProvider();
var privateKey = dsa.ExportParameters(true); // private key
var publicKey = dsa.ExportParameters(false); // public key
In publicKey it's P, Q, G, Y propertyes
In privateKey it's X
And don't forget to accept this answer!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: String to a HH:mm:ss time and finding the difference between 2 times public static void stringToDate(String time, String time2) {
try {
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Date t1 = formatter.parse(time);
System.out.println("Users first date: " + t1);
} catch (ParseException e){
System.out.println("Exception :" + e);
}
}
So above, I pass in 2 string parameters which are in the format of something like '17:23:56' and want them both converted into proper time objects that i can then find the difference between the 2, possibly in miliseconds or whatevers available if anyone knows how that'd be great.
Problem i'm having so far is that the output is: "Users first date: Thu Jan 01 17:23:56 GMT 1970", even though I thought I specified it to only parse it in HH:mm:ss. Anyone got the solution, thanks.
A: You're printing the result of Date#toString() ( <-- click the link!) which is indeed in the given format. If you want to present it in HH:mm:ss you have to use the format() method on the obtained Date.
System.out.println(formatter.format(t1));
Don't worry about this. Just parse the other time string to Date as well, do a getTime() on both and finally do the math.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem in update query in JSP all, i am writing an update query in jsp, but i am having a syntax error in it, can anybody help please. here is the query
<%
HttpSession ss=request.getSession();
String get_name=ss.getAttribute("key").toString().toUpperCase();
if(get_name == null)
{
response.sendRedirect("index.jsp");
}
else{
%>
<h2 align="left" style="color: white"><span style="background-color: blue">Welcome <%=get_name%></span></h2>
<%
}
int i=0;
String id=ss.getAttribute("id").toString();
int id_num=Integer.parseInt(id);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection("jdbc:odbc:database");
Statement s=c.createStatement();
String name_server=request.getParameter("name_ser");
String details_ser=request.getParameter("details_ser");
String date_ser=request.getParameter("date_ser");
String status_ser=request.getParameter("status_ser");
String subject_ser=request.getParameter("subject_ser");
String cost_ser=request.getParameter("cost_ser");
JOptionPane.showMessageDialog(null, name_server+","+details_ser+","+date_ser+","+status_ser+","+subject_ser+","+cost_ser+","+id_num+","+i);
i=s.executeUpdate("update RECORD set NAME='"+name_server+"' ,DETAILS='"+details_ser+"' ,DATEE='"+date_ser+"' ,Status='"+status_ser+"' ,Subject='"+subject_ser+"' ,COST='"+cost_ser+"' where ID="+id_num+"");
c.close();
s.close();
if(i>0)
{
response.sendRedirect("welcome.jsp");
}
%>
A: You didn't ask, but you should know that this code is a very bad idea. Scriptlet code in JSPs is the wrong way to go.
I'd recommend that you learn JSTL and Model-2 MVC. You should have servlets that do all the real work collaborating with JSPs. The page should be doing nothing more than displaying what it's told to by the controller/servlet.
A: Date is probably a reserved word in your database.
By the way, you should take care of SQL injections security issues and avoid mixing presentation and business logic.
A: As there is no exception so I can say following might be reasons.
*
*Your variable or variables has ' somewhere in string which is breaking the query.
*Your variable or variables has invalid type of data.
There can be other reasons too but first think about them.
A: this phrase
where ID="+id_num+"");
needs a closing single quote like :
where ID="+id_num+ "'");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Safari 5.1 cookie format specs the way of storing cookie for SAFARI has changed whith SAFARI 5.1
and that they add a kind of integrity control code
in the last 8 bytes of the file :
The file is %APPDATA%\Apple Computer\Safari\Cookies\Cookies.binarycookies
Does anybody know what s the last 8 bytes corresponds to ?
CRC32 check ?
Please help
A: This isn't going to answer your question exactly, but hopefully it gets to the heart of what you're trying to do.
You can read the contents of the binary cookie file located at ~/Library/Cookies/Cookies.binarycookies using the NSHTTPCookieStorage class, as shown in the following snippet:
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *c in [cookieStorage cookies])
{
NSLog(@"%@", c);
}
A: I've written a MacRuby script to do what you're looking for:
https://gist.github.com/1385008
#!/usr/bin/env macruby
require 'csv'
framework 'Foundation'
CSV_Headers = %w[domain path expiresDate name value].to_csv
class NSHTTPCookie
def to_csv
[domain, path, expiresDate, name, value].to_csv
end
end
store = NSHTTPCookieStorage.sharedHTTPCookieStorage
cookies = store.cookies
raw_csv = cookies.map(&:to_csv)
puts CSV_Headers
puts raw_csv.join
You need to install MacRuby, but then this will print out your cookies in a CSV format. It can easily be made to be cookies.txt compatible, as well.
A: Cookie.binarycookies:
I think this will be helpful. I reversed engineer the file with an hex-editor and start changing the cookies.
General description:
The file is composed of several pages, each one can have one or more cookies inside. Each page has a header, which is variable, 0x10, 0x14 and 0x1c are common values we can see.
File:
The file start with an 4 bytes header that is of no interest.
The next 4 bytes are of real interest because they indicate the number of pages there are in the file.
Then we have the length of each page, also represented by an 4 byte number. It's important to know that all these numbers are written in big-endian. So, we have 4*number of pages of bytes and then the pages.
We have 8 bytes at the end which also are of no interest.
Page:
Each page has a header whose length can change from one page to another. To know the length of the header, we must discard the first five bytes and the next 4 bytes will indicate the length of the header.
Following the header we will have the length of the cookie represented by 4 bytes, ordered in little-endian! This length also includes the 4 bytes needed for representing the length.
When this cookie ends another will start and so on to the end of the page.
Cookie:
The date of each cookies starts at 0x2B. The date is composed by 4 bytes ordered in little-endian. The date is represented in seconds but not since epoch so we need to subtract this number: 1706047360. (It only works for until some day in 2017)
The next field of interest starts from 0x38. This fields are dynamic fields so they are separated by an NULL “0x00” byte and are in this order: name, value, url, path.
Example:
http://i52.tinypic.com/2qcqix2.jpg
The length of the entire cookie will be 0x82.
Next to this cookie will start another one in exactly the same format if corresponds with the page length.
A: I wrote a parser for Swift that can do this for you. I needed this because NSHTTPCookieStorage.sharedHTTPCookieStorage() doesn't give you access to the global cookies when sandboxed.
https://github.com/icodeforlove/BinaryCookies.swift
You can use it like this
BinaryCookies.parse(NSHomeDirectory() + "/Library/Cookies/Cookies.binarycookies", callback: {
(error:BinaryCookiesError?, cookies) in
if let cookies = cookies {
print(cookies);
} else {
print(error);
}
});
Currently there are a few projects that can do this in other languages as well:
*
*node (https://github.com/jlipps/node-binary-cookies)
*python (https://github.com/mdegrazia/Safari-Binary-Cookie-Parser)
A: I just got a list of urls from:
$ strings Cookies.binarycookies | grep '^A\.' | uniq
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: C++ ofstream is changing output format randomly? I have a function that is writing to a .txt file.
ofstream fichier("C:\\users\\me\\Desktop\\test.txt", ios::app);
then :
fichier << "some text here";
The text i'm writing is a log file containing the history of my application changes.
As i'm french, i'm writing characters (latin ?) like "ê" or "ë". This works randomly...At first i get the correct format in notepad then when i append some others characters, it switches to another format so "ê" becomes "ê" and i don't understand why.
(In fact i can't even get "¨" to be compiled by code::blocks because it is a "multi characters constant")
What should i do ?
Thanks by advance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Raphael asp.net - Microsoft JScript runtime error: Object expected I am new to Raphael, as well as asp.net. I am trying to test a simple raphael example with asp.net, but I keep geting the following error: Microsoft JScript runtime error: Object expected
this error occurs in this line:
var paper = Raphael("diii", 320, 200);
this is the page full code:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master"AutoEventWireup="true" CodeFile="Lingua.aspx.cs" Inherits="Lingua" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<script type="text/javascript" src="Scripts/raphael.js"></script>
<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
function createCircle() {
var paper = Raphael("diii", 320, 200);
var circle = paper.circle(50, 40, 10);
cicle.attr("fill", "#f00");
circle.attr("stroke", "#fff");
}
</script>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="ger">one</asp:ListItem>
<asp:ListItem Value="ara">two</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" onClientClick="return createCircle();"
Text="Add" />
<div id="diii"></div>
</asp:Content>
The same error occurs if insted of the mentioned line above I use:
var paper = Raphael(10,50,320,200);
Does anyone know what is the problem?
A: There are two things which need to be fix in your code
*
*Check what is name of referenced Rafeal js file. Is it raphael-min.js or raphael.js.
*In your code you mistype circle as cicle. correct it
Your corrected code is here
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master"AutoEventWireup="true" CodeFile="Lingua.aspx.cs" Inherits="Lingua" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<script type="text/javascript" src="Scripts/raphael-min.js"></script>
<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
function createCircle() {
var paper = Raphael("diii", 320, 200);
var circle = paper.circle(50, 40, 10);
circle.attr("fill", "#f00");
circle.attr("stroke", "#fff");
}
</script>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="ger">one</asp:ListItem>
<asp:ListItem Value="ara">two</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" onClientClick="return createCircle();"
Text="Add" />
<div id="diii"></div>
</asp:Content>
If you want to see client side effects then do not trigger event from server side button.
A: It sounds like your raphael.js is not loading up, have you used the developer tools in your browser to check that all the scripts load (no 404s or 500s)?
Try accessing the scripts at their paths direct in the browser too.
Other than that, I would suggest the following;
*
*Use jQuery 1.6.4 (better supported, bug fixes etc).
*Use the jQuery ready function to make sure the page has finished loading before you have tried to call it.
It does look like your script is not loading fully first, so replace your js code with;
<script type="text/javascript">
$(document).ready(function () {
createCircle();
});
function createCircle() {
var paper = Raphael("diii", 320, 200);
var circle = paper.circle(50, 40, 10);
cicle.attr("fill", "#f00");
circle.attr("stroke", "#fff");
}
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery AJAX to call Java method Using jQuery AJAX, can we call a specific JAVA method (e.g. From an Action class)
The returned data from that Java method would be used to fill in some HTML code.
Please let me know if this can be done easily using jQuery (like it does in DWR)..Also for multiple data points in HTML, do we need to make multple AJAX requests?
A: The simple answer is you map your ajax calls to urls, which are in turned map to methods in your java code. The Ajax -> URI mapping happens on the client side (which ever js framework you are using, and the URI -> specific handler mapping happens within the java application)
What java framework are you using? There should be very clear and simple documentation on how to do this. For standard Java EE mappings (meaning you are not using any frameworks like Spring or Roo) I found this on google: http://javapapers.com/servlet/what-is-servlet-mapping/
"For multiple data points in HTML" I assume you are talking about having multiple parts of the html update. You can do this with multiple requests, or you can do it with one request. If you do the latter, the server needs to return all the data you need to update the dom appropriately.
A: It's not as transparent as with DWR--DWR handles making JavaScript look like Java. With jQuery you'll get JSON (or just HTML if/when it's easier that way). It's still pretty straight-forward, though. You'd send the Ajax request to a URL, rather than having it look like a local method call.
I'm not sure what you mean by "multiple data points in HTML" -- you get back whatever data you get back, and you can do with it whatever you want. If the response has all the data you need, then you wouldn't need to make multiple requests.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do add date and time stamp to an INSERT via PHP with mySQL? I have an insert script with mySQL. I need to place the date and time when the record is created in the 'add_time" column.
Can anyone show me how to modify my existing script to do this? Do I need a separate PHP script?
I would like the date to appear in standard formt: 09/25/11 6:54 AM
<?
$host="XXXXXXXXXXX";
$username="XXXXXXX";
$password="XXXXXXX";
$db_name="naturan8_hero";
$tbl_name="cartons_added";
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$order = "INSERT INTO cartons_added (
type,
part_no,
add_type,
add_qty,
add_ref,
add_by,
add_notes
) VALUES (
'$_POST[type]',
'$_POST[part_no]',
'$_POST[add_type]',
'$_POST[add_qty]',
'$_POST[add_ref]',
'$_POST[add_by]',
'$_POST[add_notes]'
)";
$result = mysql_query($order);
if ($result) {
$part_no = $_REQUEST['part_no'] ;
$add_qty = $_REQUEST['add_qty'];
header("location: inv_fc_add_success.php?part_no=" . urlencode($part_no) . "&add_qty=" . urlencode($add_qty));
}
else {
header("location: inv_fc_add_fail.php");
}
?>
A: You do not need to insert data to that column from PHP at all:
TIMESTAMP and DATETIME columns can be automatically initializated and updated to the current date and time (that is, the current timestamp).
So change the add_time column definition to
add_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
and then it will automatically populate the column for you when you insert a new row
See: MySql Manual on Timestamp Initializations
A: You got the "add_time" column set up in your database? Is it of DATETIME format?
In that case you may just modify your query like this:
$order = "INSERT INTO cartons_added (type, part_no, add_type, add_qty,
add_ref, add_by, add_notes, add_time)
VALUES
('$_POST[type]',
'$_POST[part_no]',
'$_POST[add_type]',
'$_POST[add_qty]',
'$_POST[add_ref]',
'$_POST[add_by]',
'$_POST[add_notes]',
NOW())";
Though you should be aware that executing queries like this is dangerous as you trust the user to input only nice things! Google "SQL Injection" to find out more about it, mysql_real_escape_string(), too.
A: Add 'time' column to your 'cartons_added' table.
And use this as order
$order = "INSERT INTO cartons_added (type, part_no, add_type, add_qty,
add_ref, add_by, add_notes, time)
VALUES
('$_POST[type]',
'$_POST[part_no]',
'$_POST[add_type]',
'$_POST[add_qty]',
'$_POST[add_ref]',
'$_POST[add_by]',
'$_POST[add_notes]',
'".time().")";
A: I like Sam's answer, as it is best - as an alternative, however, you could use date("m/d/Y H:i A"); as per your requirements - ie. it will output MM/DD/YYYY HH:MM AM/PM. Though if you use Sam's method, it will require less code, but you'd need to convert it to get you desired format.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Importing frameworks on xcode 4 issue Lately any framework I attempt to add to my project fails with "No such file or directory".
Eg for GameKit:
<GameKit/GameKit.h>: No such file or directory
The strange thing is that the frameworks that I added some time ago are found, but if i try to add the same framework now, I get this error. Where should I look? Hope I don't have to re-install xcode for this:(
To add a framework I use the steps described here (to remove the suspicion that I don't add it in the right manner):
How to "add existing frameworks" in Xcode 4?
Also I've checked here:
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/Frameworks/GameKit.framework/
and the framework does exist. The base SDK is set to 4.3(latest), so that's not the problem either.
A: It must not exist. It either got deleted or never existed to begin with, which makes me think it must have got deleted. Sorry, buddy.
A: I'm not sure if this is going to work, but I use another method to add frameworks, which is go to your project (The one with the xcodeproj icon), then click on your target. There, you can add the frameworks you want.
If that doesn't work, then try go to /Library/Frameworks to see if your framework you want is still there. If it's there and it's still getting that error, try manually adding the framework which is the add other button when you add a framework.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: GridView rows overlapping: how to make row height fit the tallest item? Like this previous person, I have unwanted overlap between GridView items:
Notice the text, in every column except the rightmost one.
Where I differ from that previous question is that I don't want a constant row height. I want the row height to vary to accommodate the tallest content in each row, for efficient use of screen space.
Looking at the source for GridView (not the authoritative copy, but kernel.org is still down), we can see in fillDown() and makeRow() that the last View seen is the "reference view": the row's height is set from the height of that View, not from the tallest one. This explains why the rightmost column is ok. Unfortunately, GridView is not well set-up for me to fix this by inheritance. All the relevant fields and methods are private.
So, before I take the well-worn bloaty path of "clone and own", is there a trick I'm missing here? I could use a TableLayout, but that would require me to implement numColumns="auto_fit" myself (since I want e.g. just one long column on a phone screen), and it also wouldn't be an AdapterView, which this feels like it ought to be.
Edit: in fact, clone and own is not practical here. GridView depends on inaccessible parts of its parent and sibling classes, and would result in importing at least 6000 lines of code (AbsListView, AdapterView, etc.)
A: I used a static array to drive max heights for the row. This is not perfect since the earlier columns will not be resized until the cell is redisplayed. Here is the code for the inflated reusable content view.
Edit: I got this work correctly but I had pre-measure all cells before rendering. I did this by subclassing GridView and adding a measuring hook in the onLayout method.
/**
* Custom view group that shares a common max height
* @author Chase Colburn
*/
public class GridViewItemLayout extends LinearLayout {
// Array of max cell heights for each row
private static int[] mMaxRowHeight;
// The number of columns in the grid view
private static int mNumColumns;
// The position of the view cell
private int mPosition;
// Public constructor
public GridViewItemLayout(Context context) {
super(context);
}
// Public constructor
public GridViewItemLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* Set the position of the view cell
* @param position
*/
public void setPosition(int position) {
mPosition = position;
}
/**
* Set the number of columns and item count in order to accurately store the
* max height for each row. This must be called whenever there is a change to the layout
* or content data.
*
* @param numColumns
* @param itemCount
*/
public static void initItemLayout(int numColumns, int itemCount) {
mNumColumns = numColumns;
mMaxRowHeight = new int[itemCount];
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Do not calculate max height if column count is only one
if(mNumColumns <= 1 || mMaxRowHeight == null) {
return;
}
// Get the current view cell index for the grid row
int rowIndex = mPosition / mNumColumns;
// Get the measured height for this layout
int measuredHeight = getMeasuredHeight();
// If the current height is larger than previous measurements, update the array
if(measuredHeight > mMaxRowHeight[rowIndex]) {
mMaxRowHeight[rowIndex] = measuredHeight;
}
// Update the dimensions of the layout to reflect the max height
setMeasuredDimension(getMeasuredWidth(), mMaxRowHeight[rowIndex]);
}
}
Here is the measuring function in my BaseAdapter subclass. Note that I have a method updateItemDisplay that sets all appropriate text and images on the view cell.
/**
* Run a pass through each item and force a measure to determine the max height for each row
*/
public void measureItems(int columnWidth) {
// Obtain system inflater
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Inflate temp layout object for measuring
GridViewItemLayout itemView = (GridViewItemLayout)inflater.inflate(R.layout.list_confirm_item, null);
// Create measuring specs
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(columnWidth, MeasureSpec.EXACTLY);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
// Loop through each data object
for(int index = 0; index < mItems.size(); index++) {
String[] item = mItems.get(index);
// Set position and data
itemView.setPosition(index);
itemView.updateItemDisplay(item, mLanguage);
// Force measuring
itemView.requestLayout();
itemView.measure(widthMeasureSpec, heightMeasureSpec);
}
}
And finally, here is the GridView subclass set up to measure view cells during layout:
/**
* Custom subclass of grid view to measure all view cells
* in order to determine the max height of the row
*
* @author Chase Colburn
*/
public class AutoMeasureGridView extends GridView {
public AutoMeasureGridView(Context context) {
super(context);
}
public AutoMeasureGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AutoMeasureGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if(changed) {
CustomAdapter adapter = (CustomAdapter)getAdapter();
int numColumns = getContext().getResources().getInteger(R.integer.list_num_columns);
GridViewItemLayout.initItemLayout(numColumns, adapter.getCount());
if(numColumns > 1) {
int columnWidth = getMeasuredWidth() / numColumns;
adapter.measureItems(columnWidth);
}
}
super.onLayout(changed, l, t, r, b);
}
}
The reason I have the number of columns as a resource is so that I can have a different number based on orientation, etc.
A: Based on the info from Chris, I used this workaround making use of the reference-View used by the native GridView when determining the height of other GridView items.
I created this GridViewItemContainer custom class:
/**
* This class makes sure that all items in a GridView row are of the same height.
* (Could extend FrameLayout, LinearLayout etc as well, RelativeLayout was just my choice here)
* @author Anton Spaans
*
*/
public class GridViewItemContainer extends RelativeLayout {
private View[] viewsInRow;
public GridViewItemContainer(Context context) {
super(context);
}
public GridViewItemContainer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public GridViewItemContainer(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setViewsInRow(View[] viewsInRow) {
if (viewsInRow != null) {
if (this.viewsInRow == null) {
this.viewsInRow = Arrays.copyOf(viewsInRow, viewsInRow.length);
}
else {
System.arraycopy(viewsInRow, 0, this.viewsInRow, 0, viewsInRow.length);
}
}
else if (this.viewsInRow != null){
Arrays.fill(this.viewsInRow, null);
}
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (viewsInRow == null) {
return;
}
int measuredHeight = getMeasuredHeight();
int maxHeight = measuredHeight;
for (View siblingInRow : viewsInRow) {
if (siblingInRow != null) {
maxHeight = Math.max(maxHeight, siblingInRow.getMeasuredHeight());
}
}
if (maxHeight == measuredHeight) {
return;
}
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
switch(heightMode) {
case MeasureSpec.AT_MOST:
heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.min(maxHeight, heightSize), MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
break;
case MeasureSpec.EXACTLY:
// No debate here. Final measuring already took place. That's it.
break;
case MeasureSpec.UNSPECIFIED:
heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
break;
}
}
In your adapter's getView method, either wrap your convertView as a child in a new GridViewItemContainer or make this one the top XML element of your item layout:
// convertView has been just been inflated or came from getView parameter.
if (!(convertView instanceof GridViewItemContainer)) {
ViewGroup container = new GridViewItemContainer(inflater.getContext());
// If you have tags, move them to the new top element. E.g.:
container.setTag(convertView.getTag());
convertView.setTag(null);
container.addView(convertView);
convertView = container;
}
...
...
viewsInRow[position % numColumns] = convertView;
GridViewItemContainer referenceView = (GridViewItemContainer)convertView;
if ((position % numColumns == (numColumns-1)) || (position == getCount()-1)) {
referenceView.setViewsInRow(viewsInRow);
}
else {
referenceView.setViewsInRow(null);
}
Where numColumns is the number of columns in the GridView and 'viewsInRow' is an list of View on the current row of where 'position' is located.
A: I did so many research but found incomplete answer or had tough with understanding what going on with solution but finally found an answer that fit perfectly with proper explanation.
My problem was to fit gridview item into height properly. This Grid-view worked great when all of your views are the same height. But when your views have different heights, the grid doesn't behave as expected. Views will overlap each other, causing an an-aesthetically pleasing grid.
Here Solution I used this class in XML layout.
I used this solution, and this is working very well, thanks a lot.--Abhishek Mittal
A: If you convert your GridView or ListView to a RecyclerView, this issue will not happen. And you won't need to make a custom GridView class.
A: This is not the correct solution which I am mentioned below, but can be workaround depends on your requirement.
Just set the height of view fix(in some dp i.e.- 50dp) from your child layout of gridview, so that it can be Wrapped.
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:ellipsize="end"
android:textColor="@color/text_color"
android:textSize="13dp"
android:textStyle="normal" />
A: Giving weight to your GridView also works on GridViews inside LinearLayouts as a child. This way GridView fills the viewport with its children so you are able to view it's items as long as they fit the screen (then you scroll).
But always avoid using GridViews inside ScrollViews. Otherwise you will need to calculate each child's height and reassign them as Chase answered above.
<GridView
android:id="@+id/gvFriends"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:clipChildren="false"
android:listSelector="@android:color/transparent"
android:scrollbarAlwaysDrawHorizontalTrack="false"
android:scrollbarAlwaysDrawVerticalTrack="false"
android:stretchMode="columnWidth"
android:scrollbars="none"
android:numColumns="4"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
} |
Q: How can parents waits all child processes finish then exit when it receives SIGINT? I'm writing a multi process program in C.
I hope parents process can wait all child processes finish then exit when
it receives SIGINT.
I have two questions.
*
*How can parents record each pid of child process it forked.
Child process may finish before recording function run on
main process.
*If parents has no idea about how many child processes it has. How can he wait
all child process finish.
Thanks in advance.
A: You record the pid of child processes as you fork them (if required).
call waitpid in a loop with pid = 0 it will either return a pid of a process that exited or return -1 and if errno = ECHILD you have no slaves left.
A: Keep calling wait(2) in a loop. Every time wait() returns, you'll get back the PID of the exited child and its status. The status will tell you, whether it exited normally (with an exit code) or due to a signal. Something like this (not tested):
#include <sys/types.h>
#include <sys/wait.h>
...
pid_t pid;
int status;
...
while ((pid = wait(&status)) > 0) {
printf("Child %lu ", (unsigned long)pid);
if (WIFEXITED(status))
printf("exited with status %d\n", WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf("killed by signal %d\n", WTERMSIG(status));
else if (WIFSTOPPED(status))
printf("stopped by signal %d\n", WSTOPSIG(status));
else if (WIFCONTINUED(status))
printf("resumed\n");
else
warnx("wait(2) returned for no discernible reason");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Default parameters for methods of template class Is there a way to provide default parameter values for methods of a template class? For example I have the following:
template<class T>
class A
{
public:
A foo(T t);
};
How should I modify this to give foo a default parameter of type T? For example: T is int then a default value of -23, or T is char* then default value of "something", etc. Is this even possible?
A: If you want the default parameter to be just the default value (zero, usually), then you can write A foo(T t = T()). Otherwise, I suggest a trait class:
template <typename T> struct MyDefaults
{
static const T value = T();
};
template <> struct MyDefaults<int>
{
static const int value = -23;
};
template<class T>
class A
{
public:
A foo(T t = MyDefaults<T>::value);
};
Writing the constant value inside the class definition only works for integral types, I believe, so you may have to write it outside for all other types:
template <> struct MyDefaults<double>
{
static const double value;
};
const double MyDefaults<double>::value = -1.5;
template <> struct MyDefaults<const char *>
{
static const char * const value;
};
const char * const MyDefaults<const char *>::value = "Hello World";
In C++11, you could alternatively say static constexpr T value = T(); to make the template work for non-integral values, provided that T has a default constructor that is declared constexpr:
template <typename T> struct MyDefaults
{
static constexpr T value = T();
};
template <> struct MyDefaults<const char *>
{
static constexpr const char * value = "Hello World";
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: php regex [b] to "'\[b\](.*?)\[/b\]'is",
Is my current RegEx working. But I want to change the [] to be <> instead. But it doesn't work... What more then just the [] do I need to change.
A: Try ~ as a delimiter instead
preg_match("~<b>(.*?)</b>~is", $text, $b);
A: There are various BBCode parsers available for PHP, for instance
*
*http://www.php.net/manual/en/book.bbcode.php
which allows you to simply define your replacement rules by hand:
echo bbcode_parse(
bbcode_create(
array(
'b' => array(
'type' => BBCODE_TYPE_NOARG,
'open_tag' => '<b>',
'close_tag' => '</b>'
)
)
),
'[b]Bold Text[/b]'
);
// prints <b>Bold Text</b>
Also check the various similar questions about BBCode Parsers:
*
*https://stackoverflow.com/search?q=bbcode+php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Working MDB example in JBoss 7.0.1? Here's an EJB3 MDB that used to work for me in JBoss 5.1:
@TransactionAttribute( TransactionAttributeType.NOT_SUPPORTED )
@org.jboss.ejb3.annotation.Depends("jboss.messaging.destination:service=Topic,name=IncomingArticleNotifications")
@MessageDriven(
activationConfig = {
@ActivationConfigProperty( propertyName="destinationType", propertyValue="javax.jms.Topic"),
@ActivationConfigProperty( propertyName="destination", propertyValue="topic/IncomingArticleNotificationsDest"),
@ActivationConfigProperty( propertyName="subscriptionDurability", propertyValue="Durable"),
@ActivationConfigProperty( propertyName="messageSelector", propertyValue ="type='IncomingArticleNotification'")
}
)
public class IncomingArticleHandler implements MessageListener
{
[...]
}
Try as I might, I can't migrate this to JBoss 7.0.1. JMS is set up OK, and I can publish to the destination OK (from my main JAR), but my EJB listener just isn't listening. I get no deploy or runtime errors for my EJB / WAR / EAR:
01:02:40,600 INFO [org.jboss.as.server.deployment] (MSC service thread 1-4) Starting deployment of "product-ear-1.0-SNAPSHOT.ear"
01:02:41,752 INFO [org.jboss.as.server.deployment] (MSC service thread 1-1) Starting deployment of "product-ejb-1.0-SNAPSHOT.jar"
01:02:41,753 INFO [org.jboss.as.server.deployment] (MSC service thread 1-1) Starting deployment of "product.war"
I've also fixed the JNDI names, as per instructions, so here's what I have now:
// Ignore for now: @TransactionAttribute( TransactionAttributeType.NOT_SUPPORTED )
@ResourceAdapter("ejb3-rar.rar") // ??? As per docs. No idea what this should be, an attempt to get something working.
@MessageDriven(
activationConfig = {
@ActivationConfigProperty( propertyName="destinationType", propertyValue="javax.jms.Topic"),
@ActivationConfigProperty( propertyName="destination", propertyValue="java:/topic/IncomingArticleNotificationsDest"), // updated
@ActivationConfigProperty( propertyName="subscriptionDurability", propertyValue="Durable")
// Ignore for now: @ActivationConfigProperty( propertyName="messageSelector", propertyValue ="type='IncomingArticleNotification'")
}
)
public class IncomingArticleHandler implements MessageListener
{
[...]
}
Setting all loggers to ALL before deploying reveals that the only time my MDB classes are mentioned is when the org.jboss.vfs.util.SuffixMatchFilter sees them - that can't be good.
I've been following the issue of MDB support since 7.0.0 and have read through dozens of JIRAs, not to mention the migration guide, EJB3 docs and so on, but I'm left confused. I know MDBs should work in 7.0.1, but is the above doable? I think mine is quite a simple case, so does anyone have a simple working example, a single document that states exactly what does / doesn't work in 7.0.1, or a migration guide?
Edit: just thought I'd add that this is my only EJB, so this is probably as much an EJB problem as a JMS/MDB one.
Updates:
I can deploy a dummy @Stateless with no problems, but no combination of @MessageDriven/@ActivationConfigProperty has had any effect at all (bodging the destinationType to javax.jms.XXX produces no errors!). I've tried setting the destination property to all possible JNDI combinations.
I've checked my standalone.xml against standalone-preview.xml and there are no substantial differences.
The nearest I get to any kind of error is this:
00:53:25,886 DEBUG [org.hornetq.ra.Util] (MSC service thread 1-4) org.jboss.as.messaging.jms.TransactionManagerLocator from [Module "org.hornetq.ra:main" from local module loader @15a62c31 (roots: /Users/andrewregan/Desktop/jboss-as-7.0.1.Final/modules)]: java.lang.ClassNotFoundException: org.jboss.as.messaging.jms.TransactionManagerLocator from [Module "org.hornetq.ra:main" from local module loader @15a62c31 (roots: /Users/andrewregan/Desktop/jboss-as-7.0.1.Final/modules)]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:191)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:358)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:307)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:101)
at org.hornetq.ra.Util.locateTM(Util.java:261) [hornetq-ra-2.2.7.Final.jar:]
at org.hornetq.ra.HornetQResourceAdapter.locateTM(HornetQResourceAdapter.java:1555) [hornetq-ra-2.2.7.Final.jar:]
at org.hornetq.ra.HornetQResourceAdapter.start(HornetQResourceAdapter.java:210) [hornetq-ra-2.2.7.Final.jar:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [:1.6.0_26]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [:1.6.0_26]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [:1.6.0_26]
at java.lang.reflect.Method.invoke(Method.java:597) [:1.6.0_26]
at org.jboss.jca.deployers.common.AbstractResourceAdapterDeployer.startContext(AbstractResourceAdapterDeployer.java:339) [ironjacamar-deployers-common-1.0.3.Final.jar:1.0.3.Final]
at org.jboss.jca.deployers.common.AbstractResourceAdapterDeployer.createObjectsAndInjectValue(AbstractResourceAdapterDeployer.java:1883) [ironjacamar-deployers-common-1.0.3.Final.jar:1.0.3.Final]
at org.jboss.jca.deployers.common.AbstractResourceAdapterDeployer.createObjectsAndInjectValue(AbstractResourceAdapterDeployer.java:825) [ironjacamar-deployers-common-1.0.3.Final.jar:1.0.3.Final]
at org.jboss.as.connector.services.ResourceAdapterActivatorService$ResourceAdapterActivator.doDeploy(ResourceAdapterActivatorService.java:140) [jboss-as-connector-7.0.1.Final.jar:7.0.1.Final]
at org.jboss.as.connector.services.ResourceAdapterActivatorService.start(ResourceAdapterActivatorService.java:93) [jboss-as-connector-7.0.1.Final.jar:7.0.1.Final]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1765) [jboss-msc-1.0.0.GA.jar:1.0.0.GA]
at org.jboss.msc.service.ServiceControllerImpl$ClearTCCLTask.run(ServiceControllerImpl.java:2291) [jboss-msc-1.0.0.GA.jar:1.0.0.GA]
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [:1.6.0_26]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [:1.6.0_26]
at java.lang.Thread.run(Thread.java:680) [:1.6.0_26]
Might that be a problem? I get that by adding @ResourceAdapter(value="hornetq-ra.rar") as I've seen suggested elsewhere.
A: I finally managed to solve this myself. JNDI was a red-herring. I didn't need to upgrade to JBoss 7.1.0alpha, nor did I need to change my project to use Java EE 6 deployment (moving my EJBs into the WAR).
In the end, all I needed to do was turn off JBoss's EJB3 "lite" mode (this was set to true in the standalone-preview.xml I copied from). Presumably MDBs are not supported in that mode. As soon as I did this, my MDBs became visible.
<subsystem xmlns="urn:jboss:domain:ejb3:1.1" lite="false">
[...]
</subsystem>
My working MDB now looks like this:
@TransactionAttribute( TransactionAttributeType.NOT_SUPPORTED )
@MessageDriven(
activationConfig = {
@ActivationConfigProperty( propertyName="destinationType", propertyValue="javax.jms.Topic"),
@ActivationConfigProperty( propertyName="destination", propertyValue="java:/topic/IncomingArticleNotificationsDest"),
@ActivationConfigProperty( propertyName="subscriptionDurability", propertyValue="Durable"),
@ActivationConfigProperty( propertyName="messageSelector", propertyValue ="type='IncomingArticleNotification'"),
@ActivationConfigProperty( propertyName="clientID", propertyValue="myValue") // See: http://jgurukulam.blogspot.com/2011/09/jboss-7.html
}
)
public class IncomingArticleHandler implements MessageListener
{
[...]
}
UPDATE:
"EJB lite" mode has been removed !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can i replace characters AND numbers at the same time I have a string that looks like - /celebrity.html#portfolios/jennifer-aniston-2006#img10
I want to remove #img10 (which can also be #img6; any number really).
I have used this code
var docLoc = document.location.href.replace("#img", '');
var docLoc2= docLoc.replace(/[0-9]+/,'');
when I log docLoc2 I get /celebrity.html#portfolios/jennifer-aniston-
I really want to combine these 2 replace functions so it does it all at once, and therefore will only remove #img10, I have also written this:
var docLoc = document.location.href.replace("#img"+/[0-9]+/, '');
This doesn't work (I think the syntax is wrong).
Can anyone provide me with a solution? Any replies are greatly appreciated.
A: Use
var docLoc = document.location.href.replace(/#img[0-9]+$/, '');
Demo at http://refiddle.com/1bq
update: added the $ at he end of the expression to only match the #img?? if it is at the end of the string, as suggested by Šime Vidas in the comments..
.replace MDN Docs works with either a string or a regular expression. You tried to combine both with the wrong syntax as you noted yourself..
A: Your regex could be this
#img\d*
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android: Scale fixed Layout down i want to scale my android application, basically i developed it for 800x480 display with a AbsoluteLayout. This is necessary for my Application, i can't change it.
Now the Problem:
When i start my app in the Emulator the buttons disappear and the images are extremly large. I thought android would scale applications with a fixed size down by default, but it does not work. I already tried to manipulate the manifest but this did not work.
I use a ImageView component for graphics.
Targeting Android 2.1
Cheers
Felix
A: It is definitely not ideal to use AbsoluteLayout. But, if you want to just push through with it, you should switch the units of all your co-ordinates and sizes away from px (pixels) to dp (density independent pixels). You will have to scale all of your existing co-ordinates by a factor of 2/3 to start, since 1 dp = 1.5px at the density that your layout targets (hdpi).
You will need to explicitly specify the sizes of all your images and layouts. If, for example, you had a button that was 30px wide and 120px tall, then it will become 20dp wide and 80dp tall.
Of course, the images won't look great on smaller (mdpi) screens, since they will be scaled to 2/3 size. Also, some devices are fixed to landscape mode, where you will definitely encounter layout problems. So it's not pretty, but it may get you over the finish line, depending on your requirements.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I add a scrollbar to my c# dockable forms when they are docked next to each other? I have some dockable forms that have a minimum size set so that when they are floating they always get the right size. But when I dock them next to each other some of the content is hidden. I want to add a scrollbar that shows the user that there is more content than currently showing on the form when they are docked next to each other.
I tried to set the AutoScroll property to true, but it never shows. Can I use the AutoScroll together with minimum size?
Thanks for any pointers!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to remove validation using instance_eval clause in Rails? I would like to enhance existing class using instance_eval. There original definition contains validation, which require presence of certain fields, ie:
class Dummy < ActiveRecord::Base
validates :field, :presence => true
end
Now I want to change that to optional using instance_eval (or any other method, really):
Dummy.instance_eval do
...
end
What would be the proper syntax to remove the validation, so the field is optional. I would rather do this directly on the model layer, instead doing weird hacks in controllers or views. The use of instance_eval is not really required, but as far as I know, this is generally the best way to enhance classes in Rails.
Edit #1
In general - the original class is part of the gem and I don't want to fork it, nor tie to specific release. The general cause is not really important. Simply editing the original model has far worse consequences than monkey patching.
A: I had a similar problem and was able to get past it using:
class MyModel << Dummy
# erase the validations defined in the plugin/gem because they interfere with our own
Dummy.reset_callbacks(:validate)
...
end
This is under Rails 3.0. The caveat: It does remove ALL validations, so if there are others you want to keep you could try Dummy.skip_callback(...), but I could not figure out the right incantation of arguments to make that work.
A: I found a solution, not sure how solid it is, but it works well in my case. @aVenger was actually close with his answer. It's just that the _validators accessor contains only information used for reflection, but not the actual validator callbacks! They are contained in the _validate_callbacks accessor, not to be confused with _validations_callbacks.
Dummy.class_eval do
_validators.reject!{ |key, _| key == :field }
_validate_callbacks.reject! do |callback|
callback.raw_filter.attributes == [:field]
end
end
This will remove all validators for :field. If you want to be more precise, you can reject the specific validator for _validators which is the same as the raw_filter accessor of validate callbacks.
A: One solution is to extend validates :
#no need of instance_eval just open the class
class Dummy < ActiveRecord::Base
#validates :field, :presence => true
def self.validates(*attributes)
if attributes.first == :field #=> add condition on option if necessary
return # don't validate
else
super(*attributes) #let normal behavior take over
end
end
end
And no that's not monkey-patching but extending or decorating a behavior. Rails 3.1 is built on the idea of "multi- inheritance" with module inclusion, specifically to allow this kind agility.
update #2
One caveat is you must load the class with the redefined validates method before the gem containing the call to validates. To do so, require the file in config/application.rb after require "rails/all" as suggested in the railsguides. Something like that :
require File.expand_path('../boot', __FILE__)
require 'rails/all' # this where rails (including active_record) is loaded
require File.expand_path('../dummy' __FILE__) #or wherever you want it
#this is where the gems are loaded...
# the most important is that active_record is loaded before dummy but...
# not after the gem containing the call to validate :field
if defined?(Bundler)
Bundler.require *Rails.groups(:assets => %w(development test))
end
Hope it works now!
A: Answer by aVenger has problems when you declare validations of more than one attribute in a line:
validates :name, :message, :presence => true
That's because this line creates a raw_filter with more than one attribute in attributes filter:
Model.send(:_validate_callbacks)
=> [#<ActiveSupport::Callbacks::Callback:0xa350da4 @klass=Model(...), ... , @raw_filter=#<ActiveModel::Validations::PresenceValidator:0x9da7470 @attributes=[:name, :message], @options={}>, @filter="_callback_before_75", @compiled_options="true", @callback_id=76>]
We have to delete the desired attribute from that array and reject the callbacks without attributes
Dummy.class_eval do
_validators.reject!{ |key, _| key == :field }
_validate_callbacks.each do |callback|
callback.raw_filter.attributes.delete :field
end
_validate_callbacks.reject! do |callback|
callback.raw_filter.attributes.empty? ||
callback.raw_filter.attributes == [:field]
end
end
I have this working on a Rails 3.2.11 app.
A: For rails 4.2 (~ 5.0) it can be used the following module with a method:
module ValidationCancel
def cancel_validates *attributes
attributes.select {|v| Symbol === v }.each do |attr|
self._validators.delete( attr )
self._validate_callbacks.select do |callback|
callback.raw_filter.try( :attributes ) == [ attr ] ;end
.each do |vc|
self._validate_callbacks.delete( vc ) ;end ;end ;end ;end
Note: Since the filtern can be a symbol of an association, or a specific validator, so we have to use #try.
Then we can use rails-friendly form in a class declaration:
class Dummy
extend ValidationCancel
cancel_validates :field ;end
Note: since removal of the validator is affecting to the whole class and its descendants globally, it is not recommended to use it to remove validations in such way, instead add if clause for the specific rule as follows:
module ValidationCancel
def cancel_validates *attributes
this = self
attributes.select {|v| Symbol === v }.each do |attr|
self._validate_callbacks.select do |callback|
callback.raw_filter.try( :attributes ) == [ attr ] ;end
.each do |vc|
ifs = vc.instance_variable_get( :@if )
ifs << proc { ! self.is_a?( this ) } ;end ;end ;end ;end
This restricts execution of the validation callback for the specified class and its descendants.
A: If you doesn't want to make any changes in Parent class then first clear all validations in child class and copy all required validation from parent class to child class
class Dummy < ActiveRecord::Base
validates :property, presence: true
validates :value, length: { maximum: 255 }
end
And override it in child class
Dummy.class_eval do
clear_validators!
validates :property, presence: true
end
A: I think this is the most actual solution at this moment (I'm using rails 4.1.6):
# Common ninja
class Ninja < ActiveRecord::Base
validates :name, :martial_art, presence: true
end
# Wow! He has no martial skills
Ninja.class_eval do
_validators[:martial_art]
.find { |v| v.is_a? ActiveRecord::Validations::PresenceValidator }
.attributes
.delete(:martial_art)
end
A: Easest way to remove all validations:
clear_validators!
A: As I was trying to do this to remove the phone validation from the spree Address model, below is the code I got to work. I added the type check for callback.raw_filter because I only wanted to remove the presence validator on the phone field. I also had to add it because it would fail when trying to run against one of the other validators specified in the Spree::Address model that did not have an 'attributes' key for callback.raw_filter, thus an exception was thrown.
Spree::Address.class_eval do
# Remove the requirement on :phone being present.
_validators.reject!{ |key, _| key == :phone }
_validate_callbacks.each do |callback|
callback.raw_filter.attributes.delete :phone if callback.raw_filter.is_a?(ActiveModel::Validations::PresenceValidator)
end
end
A: If you really want to do this then here would be a good place to start digging: https://github.com/rails/rails/blob/ed7614aa7de2eaeba16c9af11cf09b4fd7ed6819/activemodel/lib/active_model/validations/validates.rb#L82
However, to be honest, inside of ActiveModel is not where I'd be poking with a stick.
A: If you can edit the constraint on the original model to put an :if => :some_function on it, you can easily change the behavior of the function it calls to return false. I tested this and it works pretty easily:
class Foo < ActiveRecord::Base
validates :field, :presence => true, :if => :stuff
attr_accessor :field
def stuff
return true;
end
end
and then somewhere else:
Foo.class_eval {
def stuff
false
end
}
A: Why not use @dummy.save_without_validation method to skip validations altogether? I prefer do something like this:
if @dummy.valid?
@dummy.save # no problem saving a valid record
else
if @dummy.errors.size == 1 and @dummy.errors.on(:field)
# skip validations b/c we have exactly one error and it is the validation that we want to skip
@dummy.save_without_validation
end
end
You could put this code in your model or in the controller, depending on your needs.
A: In Rails 4.1,
I was able to do _validate_callbacks.clear. In my case, I wanted all the validations for a gem removed, so I could create my own. I did this in a module that was patched into the class.
Module #Name
extend ActiveSupport::Concern
included do
_validate_callbacks.clear
#add your own validations now
end
end
A: Wanted to add that, if you're trying to clear validations on a instance of your Model (not the entire model class), don't do my_dummy._validate_callbacks.clear, as that will clear validations on every instance (and future instance) of your Dummy model class.
For just the instance (and if you wanted to reinstate the validations later), try the following:
*
*Create a copy of the validate callbacks (if you want to reinstate later):
my_dummy_validate_callbacks = my_dummy._validate_callbacks.clone
*Set the validate callbacks on your instance to empty:
my_dummy._validate_callbacks = {}
*Do what you want on my_dummy validation free!
*Reinstate the callbacks: my_dummy._validate_callbacks = my_dummy_validate_callbacks
A: I'd have to look more into the code and help, but I'm thining it might be possible to inspect the list of validators of the class, and then modify the entry for the validation you want to change to add in an :if => :some_function conditional to it.
You'll need to do it only once for production (so it can be put inside an initializer, but for development you'll need to put it in the model, or somewhere else that will get loaded each time the corresponding model is (perhaps an observer?).
(I'll edit the answer with more information as I come to research it.)
A: Every Rails validator, pre-defined or custom, is an object, and is expected to respond to #validate(record) method. You can monkey patch or stub this method.
# MyModel.validators_on(:attr1, :attr2, ...) is also useful
validator = MyModel.validators.detect do |v|
validator_i_am_looking_for?(v)
end
def validator.validate(*_)
true
end
# In RSpec you can also consider:
allow(validator).to receive(:validate).and_return(true)
Tested in Rails 5.1.
Don't do this unless you understand what you're doing ;)
A: This does not directly answer the question but here's an option you should consider in such a situation: instead of disabling validation, you could set the required fields in a before_validation hook.
Since you don't need those required fields, set them with some dummy data that satisfies the validation and forget about them.
No ugly monkey patching.
A: Assuming the original implementation of Dummy is defined in an engine there is a nasty hack that will do what you want. Define Dummy in your application to keep the original implementation of Dummy from being auto-loaded. Then load the source to Dummy and remove the line that does the validation. Eval the modified source.
Put the following in your app/models/dummy.rb
class Dummy < ActiveRecord::Base
end
# Replace DummyPlugin with name of engine
engine = Rails::Application::Railties.engines.find { |e| e.class == DummyPlugin::Engine }
dummy_source = File.read File.join(engine.config.root, "app", "models", "dummy.rb")
dummy_source = dummy_source.gsub(/validates :field, :presence => true.*/, "")
eval dummy_source
If it is regular gem instead of an engine the same concept would apply, just would need to load the source for Dummy from the gem root instead of the engine root.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
} |
Q: How to change authenticate method on IIS 7? I've got an error which tells me unauthorized. How and where to change that webserver allows anonymous (public) access?
HTTP Error 401.2 - Unauthorized
401.2 - Logon failed due to server configuration.
Something has happened on my local machine when I made the latest update for IIS, but now I'm not sure what has happened.
A: Note the following methods here:
http://support.microsoft.com/kb/942043
A: Select your website on the tree left hand side inside IIS Manager.
Double click on Authentication section from the menu (Authentication section is under the IIS caregory)
Enable Anonymous Auth. there as follows :
You can bind a user to this app by Editing the Anonymous Auth. Section. this will gives you box like this :
This should be set to IUSR by default.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to check the registers value of the network card on ARM Linux? On our device, we observed that the IPv6 NS packet with multicast address of Layer2 were droped. The tcpdump cannot capture these packet so I guess the packets were dropped by the network card driver(correct me if I am wrong).
To verify this, I want to write a module to check the value of some registers in the network card. Since it is not possible for me to recompile the original driver I need a separate module to finish this job.
Is it possible to do that? How?
A: You can recompile the driver, adding printk with whatever it is you want to see.
If you are developing for an ARM target, it is possible you are using the Embedded Linux Dev Kit (ELDK), so you could look in the kernel source tree for the driver, modify it, and rebuild the kernel. Or you could remove the resident driver and compile it as a loadable module—which is a lot easier for tinkering with a driver.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Push just one file to GitHub from a local repository I have a repo with multiple scripts. One of them is especially useful and I want to share it using GitHub.
How can I export one file (with commit history) to a GitHub repo without sharing all other scripts from the same repo?
Something like:
git remote add 'origin' git@github.com:user/Project.git
git push -u 'origin' ./useful-script.sh
But how do I specify a single filename? Or should I create some kind of special 'partial' commit?
A: You'd have to use filter-branch to rewrite your history and strip everything but that single file:
git filter-branch --index-filter '
git rm --cached -f -r .;
git add ./useful-script.sh;
' --all
should do the job.
If --index-filter does not work (I'm not sure about that git add there), try `--tree-filter' with the same argument.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: AcceptButton doesn't work in case there are TabControl on the form In the following form, I want the AcceptButton to be OK button, but although I set the property to the Form that OK button is the accept button, the actual result is Test button.
How to fix it?
A: Earlier i got this kind of problem, but got solved easily. It is very much possible that Test button TabIndex is less than that of OK button. Just make it reverse. It should work. At least it worked for me. If not, just check the TabControl TabIndex, it should also be greate than your OK button.
Hope it helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: password reset url in asp.net I'm looking to send a user a link if they forget their password.
I have it that they enter their email address and an email is sent to them with a link to reset their password - although I want this link to expire in two days.
Looking at a password reset email I got sent from an online store, I was looking to keep it generally the same format, but I'm unclear how the the expiry part of the URL is created.
The example URL I got sent is:
http://www.mydomain.com/reset.aspx?expires=1317124368&passwordreset=1&username=thegunner%40yahoo.com&authCode=dfb83e3074d395a7606bdc1825d709197fa984ab
passwordreset=1 ...ok no prob
username = email address ...no prob
authcode ...I guess I could just generate GUID code.
expires=1317124368 ...how could this part be created? I guess it's a time stamp in some format of the day the email was sent - how could I recreate this?
Any ideas?
A: The expires in that URL may very well be the id of the record in the table that actually holds the date and time when the link expires.
You could do the same: send the link via email and store in a table the link, the date and time when it expires plus an identity column (autogenerated), and possibly some other information (email, etc).
When the person clicks on your link, you use that ID to get the expiration date and time to determine whether the person is allowed to use the same link or not.
Or... that number may represent a date and time measured in milliseconds, ticks, nanoseconds,etc, counting from a specific date and time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Looping with Conditions through a xml file using lxml etree I wonder if it's possible to make conditional statments connected with a tree.findall("...") statement in lxml library?
I have the following xml structure in a file
<sss version="1.2">
<date>2011-09-23</date>
<time>12:32:29</time>
<origin>OPST</origin>
<user></user>
<survey>
<name>Test</name>
<version>2011-09-02 15:50:10</version>
<record ident="A">
<variable ident="10" type="quantity">
<name>no_v</name>
<label>Another question</label>
<position start="23" finish="24"/>
<values>
<range from="0" to="32"/>
</values>
</variable>
<variable ident="11" type="quantity">
<name>v_683</name>
<label>another totally another Question</label>
<position start="25" finish="26"/>
<values>
<range from="0" to="33"/>
</values>
</variable>
<variable ident="12" type="quantity">
<name>v_684</name>
<label>And once more Question</label>
<position start="27" finish="29"/>
<values>
<range from="0" to="122"/>
</values>
</variable>
<variable ident="20" type="single">
<name>v_684</name>
<label>Question with alternatives</label>
<position start="73" finish="73"/>
<values>
<range from="1" to="6"/>
<value code="1">Alternative 1</value>
<value code="2">Alternative 2</value>
<value code="3">Alternative 3</value>
<value code="6">Alternative 4</value>
</values>
</variable>
</record>
</survey>
</sss>
What I want to do now is to get only survey/record/variable/name .text and survey/record/variable/values/value .text if the name starts with "v_"
So far i have the first part
from lxml import etree as ET
tree = ET.parse('scheme.xml')
[elem.text for elem in tree.getiterator(tag='name') if elem.text.startswith('v_')]
But how can I get the survey/record/variable/values/value .text of the SAME element...and use survey/record/variable/name .text like a filter?
Thanks a lot!
A: [(elem.text,elem.getparent().xpath('values/value/text()'))
for elem in tree.getiterator(tag='name') if elem.text.startswith('v_')]
yields
[('v_683', []),
('v_684', []),
('v_684',
['Alternative 1', 'Alternative 2', 'Alternative 3', 'Alternative 4'])]
elem is a name element. So to get the the associated values, you can first find its parent (variable), then search for the values child, and then the value subchild elements.
An alternative that removes the getparent call, but uses a slightly more complicated XPath is:
[(elem.text,elem.xpath('following-sibling::values/value/text()')) for elem in tree.getiterator(tag='name') if elem.text.startswith('v_')]
following-sibling:: tells xpath to generate all siblings of name.
following-sibling::values tells xpath to generate all siblings of name that are values elements.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Delete group containers in runtime in flex i am trying to make a some groups within a predefined group at run time. i can make groups, the code is working fine. Now i have added two buttons in each group which is created in run time. now the problem is one of the button is x . the property of button should be when i click on it it should delete the very specific group in which it is built. please check out the code and tell me what additions should i make.
public var n:Number = 0;
protected function remover (event:MouseEvent):void
{
}
protected function settings(g:Group):void
{
((DisplayObject)(g)).width = "200";
((DisplayObject)(g)).height = "140";
((DisplayObject)(g)).x = "200" ;
((DisplayObject)(g)).y = "200";
var s:String;
s = "NewGroup"+ "X"+ n.toString;
var mybutton1:Button = new Button();
mybutton1.id = s;
mybutton1.label ="X";
mybutton1.addEventListener(MouseEvent.CLICK, remover);
g.addElement(mybutton1);
// setting1(mybutton1);
n++;
}
public function addGroup(event:MouseEvent): void
{
var s:String;
n = n+1;
s = "NewGroup"+ "_"+ n.toString;
var myGroup:Group = new Group();
myGroup.id = s;
main.addElement(myGroup);
// setElementIndex(myGroup, n);
settings(myGroup);
}
]]>
</fx:Script>
<s:Button x="422" id="wow" y="139" label="Add Group" click="addGroup(event)"/>
<s:HGroup id="main" x="6" y="168" width="750" height="490">
</s:HGroup>
A: You need to look into using DataGroup to create ItemRenderers (your groups) which has a button within it. Everything is based on a data collection (like ArrayCollection) that you manage. It makes everything easier because if you bind the ArrayCollection to the dataProvider property of the DataGroup and remove an item from the collection, your DataGroup will automatically update and remove the display item for you.
A: This should work:
protected function remover(event:MouseEvent):void
{
main.removeElement(Group(Button(event.currentTarget).parent));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Data mining for significant variables (numerical): Where to start? I have a trading strategy on the foreign exchange market that I am attempting to improve upon.
I have a huge table (100k+ rows) that represent every possible trade in the market, the type of trade (buy or sell), the profit/loss after that trade closed, and 10 or so additional variables that represent various market measurements at the time of trade-opening.
I am trying to find out if any of these 10 variables are significantly related to the profits/losses.
For example, imagine that variable X ranges from 50 to -50.
The average value of X for a buy order is 25, and for a sell order is -25.
If most profitable buy orders have a value of X > 25, and most profitable sell orders have a value of X < -25 then I would consider the relationship of X-to-profit as significant.
I would like a good starting point for this. I have installed RapidMiner 5 in case someone can give me a specific recommendation for that.
A: A Decision Tree is perhaps the best place to begin.
The tree itself is a visual summary of feature importance ranking (or significant variables as phrased in the OP).
*
*gives you a visual representation of the entire
classification/regression analysis (in the form of a binary tree),
which distinguishes it from any other analytical/statistical
technique that i am aware of;
*decision tree algorithms require very little pre-processing on your data, no normalization, no rescaling, no conversion of discrete variables into integers (eg, Male/Female => 0/1); they can accept both categorical (discrete) and continuous variables, and many implementations can handle incomplete data (values missing from some of the rows in your data matrix); and
*again, the tree itself is a visual summary of feature importance ranking
(ie, significant variables)--the most significant variable is the
root node, and is more significant than the two child nodes, which in
turn are more significant than their four combined children. "significance" here means the percent of variance explained (with respect to some response variable, aka 'target variable' or the thing
you are trying to predict). One proviso: from a visual inspection of
a decision tree you cannot distinguish variable significance from
among nodes of the same rank.
If you haven't used them before, here's how Decision Trees work: the algorithm will go through every variable (column) in your data and every value for each variable and split your data into two sub-sets based on each of those values. Which of these splits is actually chosen by the algorithm--i.e., what is the splitting criterion? The particular variable/value combination that "purifies" the data the most (i.e., maximizes the information gain) is chosen to split the data (that variable/value combination is usually indicated as the node's label). This simple heuristic is just performed recursively until the remaining data sub-sets are pure or further splitting doesn't increase the information gain.
What does this tell you about the "importance" of the variables in your data set? Well importance is indicated by proximity to the root node--i.e., hierarchical level or rank.
One suggestion: decision trees handle both categorical and discrete data usually without problem; however, in my experience, decision tree algorithms always perform better if the response variable (the variable you are trying to predict using all other variables) is discrete/categorical rather than continuous. It looks like yours is probably continuous, in which case in would consider discretizing it (unless doing so just causes the entire analysis to be meaningless). To do this, just bin your response variable values using parameters (bin size, bin number, and bin edges) meaningful w/r/t your problem domain--e.g., if your r/v is comprised of 'continuous values' from 1 to 100, you might sensibly bin them into 5 bins, 0-20, 21-40, 41-60, and so on.
For instance, from your Question, suppose one variable in your data is X and it has 5 values (10, 20, 25, 50, 100); suppose also that splitting your data on this variable with the third value (25) results in two nearly pure subsets--one low-value and one high-value. As long as this purity were higher than for the sub-sets obtained from splitting on the other values, the data would be split on that variable/value pair.
RapidMiner does indeed have a decision tree implementation, and it seems there are quite a few tutorials available on the Web (e.g., from YouTube, here and here). (Note, I have not used the decision tree module in R/M, nor have i used RapidMiner at all.)
The other set of techniques i would consider is usually grouped under the rubric Dimension Reduction. Feature Extraction and Feature Selection are two perhaps the most common terms after D/R. The most widely used is PCA, or principal-component analysis, which is based on an eigen-vector decomposition of the covariance matrix (derived from to your data matrix).
One direct result from this eigen-vector decomp is the fraction of variability in the data accounted for by each eigenvector. Just from this result, you can determine how many dimensions are required to explain, e.g., 95% of the variability in your data
If RapidMiner has PCA or another functionally similar dimension reduction technique, it's not obvious where to find it. I do know that RapidMiner has an R Extension, which of course let's you access R inside RapidMiner.R has plenty of PCA libraries (Packages). The ones i mention below are all available on CRAN, which means any of the PCA Packages there satisfy the minimum Package requirements for documentation and vignettes (code examples). I can recommend pcaPP (Robust PCA by Projection Pursuit).
In addition, i can recommend two excellent step-by-step tutorials on PCA. The first is from the NIST Engineering Statistics Handbook. The second is a tutorial for Independent Component Analysis (ICA) rather than PCA, but i mentioned it here because it's an excellent tutorial and the two techniques are used for the similar purposes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to COUNT(*) from multi-table query? I have two tables, Snippets and Comments. Snippets has an Id column and Comments has a SnippetId column.
I want to count the number of comments for each snippet.
I tried this:
SELECT
S.Id,
S.Title,
COUNT(*) AS CommentCount
FROM
Snippets S,
Comments C
WHERE
S.Id = C.SnippetId
but it does not work. It returns the total number of comments, and only returns one row.
I want to have a result like this:
Id | Title | CommentCount
1 | Test | 314
2 | Test2 | 42
How can I achieve this?
A: You almost have it correct; you're just missing a GROUP BY clause:
SELECT
S.Id,
S.Title,
COUNT(*) AS CommentCount
FROM
Snippets S,
Comments C
WHERE
S.Id = C.SnippetId
GROUP BY S.Id, S.Title
A: how about add
group by S.Id ,S.Title
at the end of your sql
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Converting byte number to grayscale and vica versa I got a number between 0-255 and need to convert it to a RGB grayscale color. And how do I convert a RGB-color to a grayscale value between 0-255?
A: The common formula is luminosity = 0.30 * red + 0.59 * green + 0.11 * blue. Matches the human eye's color perception, doesn't otherwise correct for display device gamma.
A: If you have a number 0 <= x <= 255 representing a grayscale value, the corresponding RGB tuple is simply (x,x,x).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Which HTML DOM parser works best on Android? I need to process some HTML pages in my Android App and I would prefer to use XPath for extracting the relevant information. For regular J2SE there are a lot of possible implementations for parsing regular HTML into a org.w3c.dom.Document:
*
*jTidy
*TagSoup
*Jericho
*NekoHTML
*HTMLCleaner
(List may be incomplete - it has been extracted from https://stackoverflow.com/questions/2009897/recommend-an-alternative-to-jtidy)
But it is very complicated to estimate if and how good those libraries work on Android (library size, cpu and memory consumption).
Based on your experience - what is the library of your choice for Android?
A: OK, looks like no-one can answer that question - then I have to check it myself.
jTidy
I downloaded the latest jTidy sources, compiled them and added the created jar file as library to my Android app. There were no problems using jTidy in my App (emulator and real phone). At runtime jTidy also works fine - but it seems that it is not a good fit for the limited Android environment - it works really slow. Looking at the Logcat output even parsing a ~10kb html file causes the garbage collector to work heavily.
HTMLCleaner
From my experience HTMLCleaner works also nice on Android; the library size is relatively small (106KB for v2.2). However the parsed DOM it creates is not as expected - HTMLCleaner inserts for example additional <span> elements into the DOM. This may be OK if you want to display it as an HTML file but for my use case - extrecting information via XPath expressions - this is a no-go!
TagSoup
Not tested
Jericho
Not tested
NekoHTML
Not tested
JSoup
Not tested
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: What should I use for guest identifier? I'm opening up a feature on my site that will not require a user to create a profile. I need to create and track user ids so I'm curious what others use as an indentifier for guest accounts. Here are some of my thoughts:
*
*Capture the client IP address and use that
*Assign a unique ID
Just curious if anyone else has done the same and what they used.
A: Use cookies. But, anyway, it's exploitable.
Don't use IP, as the IP can change very often. And, in cookies, assing an unique ID, as you marked in your question.
A: These days user don`t like to register over and over again. More and more of the data over internet is going to the cloud. Rob W suggests openid some info about the openids on wikipedia. Why not use facebook, google accaunt. There are other solutions - more or less what you need - gravatar, disqus these are more "comment oriented".
A: is regular php session inefficient? you can add to it anything just to complicate the structure, but anyway it'll be always exploitable, so I would keep it as simple as possible - use session ;)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Move commits from one branch to another and then merge them back in I have a tree:
/--b1---b2 <-- topic b
/
a1---a2 <-- topic a
where 'b' depends on 'a'. Then I realize I need to do some changes related to topic 'a' in order to continue with 'b', but i'd like to do them on 'b' as a normal development course of 'b':
/--b1---b2---a3---a4---b3---b4---a5---b5 <-- topic b
/
a1---a2 <-- topic a
Then, when the thing I want to accomplish on 'b' is done, I'd like my tree to look like this:
/--b1---b2--------m---b3'---b4'---b5' <-- topic b
/ /
a1---a2---a3'---a4'---a5' <-- topic a
as if I actually did all the changes on 'a', then merged them on 'b' and then continued on 'b'.
I know I can do this manually doing:
1- rebase/cherry-pick 'a' commits from branch 'b' to 'a'
2- create a temporal branch 'b-tmp' on 'b'.
3- reset branch 'b' to 'b2'.
4- merge 'a' onto 'b'.
5- rebase/cherry-pick 'b' commits from 'b-tmp' onto 'b'.
6- delete branch 'b-tmp'.
I can create some script to do this, I'd just like to know if there are better ways/ideas to do this, other than this 6 steps.
A: Let me start out with saying that I'd rather integrate the topic branches often (Integrate Early, Build Often ... rings a bell?). So in fact, when there are changes that should go onto a eventually, I'd go back, do the changes on a, and rebase b on top of a.
If a needs to be stable for some other purpose, I'd make a a-for-b branch to contain the work temporarily, and rebase b on top of that.
If you really must work with 'topic-a' changes inside branch 'b', Here's what i'd do.
Note: screencasts included
Getting to the starting point
This is a simple working tree with the layout from the question:
mkdir /tmp/q
cd /tmp/q
git init .
touch f
git add f
git commit -am initial
git checkout -b a; for a in a{1,2}; do echo $a>$a; git add $a; git commit -am $a; git tag $a; done
git checkout -b b; for a in b{1,2} a{3,4} b{3,4} a5 b5; do echo $a>$a; git add $a; git commit -am $a; git tag $a; done
git show-branch
See screencast here
Reorganizing commits onto their topic branches
git checkout -b a_new a # for safety, work on a clone of branch a
git reset --hard b # start by moving it to the end of the b branch
git status # (just show where we are)
git log --oneline
git rebase -i a # rebase it on top of the original branch a
# not shown: delete every line with non-branch-a commits (b1-b5)
# see screencast
git log --oneline # (just show where we are again)
git checkout -b b_new b # for safety, work on a clone of branch b
git log --oneline # (just show where we are again: the end of branch b)
git rebase -i a_new # this time, rebase it on top of the new branch a_new
git log --oneline # (check results)
git show-branch b_new a_new
Again, see screencast
Inspecting results
We can now do a before/after tree comparison:
sehe@natty:/tmp/q$ git show-branch a b
! [a] a2
! [b] b5
--
+ [b] b5
+ [b^] a5
+ [b~2] b4
+ [b~3] b3
+ [b~4] a4
+ [b~5] a3
+ [b~6] b2
+ [b~7] b1
++ [a] a2
sehe@natty:/tmp/q$ git show-branch a_new b_new
! [a_new] a5
* [b_new] b5
--
* [b_new] b5
* [b_new^] b4
* [b_new~2] b3
* [b_new~3] b2
* [b_new~4] b1
+* [a_new] a5
Making it permanent:
for name in a b;
do
git branch -m $name ${name}_old &&
git branch -m ${name}_new $name
done
git branch -D a_old b_old # when sure
Notes
I have deliberately chosen to make non-conflicting changes for the demo. Of course in real life you'll get merge conflicts. Use git mergetool and git rebase --continue.
If your changes are hygienic and really belong on their respective topic branches, chances are that conflicts should be few and easily resolved. Otherwise, it is time to revise your branching scheme (see Martin Fowler e.a.)
Discussion
In response to
You also say that "when there are changes that should go onto 'a' eventually, I'd go back, do the changes on 'a', and rebase 'b' on top of 'a'". I'm not sure I understand this also. Could you explain?
I mean that I would try to make the a3,a4,a5 revisions on the a branch anyway, and rebase b onto that, so
*
*the person doing the merge is the same person doing the commits
*you do the commit and merge in succession (meaning you don't mess things up due to short-term-memory loss) <-- this is theMerge Early/Soon/Frequently mantra
*you avoid unnecessary merge conflicts
*you don't have to 'go back in time' later and rewrite the original commits: a3, a4, a5 would just be merged, not copied (see Git Cherry-pick vs Merge Workflow)
Here is the 'Getting to the starting' point, but adapted to my idealized workflow. Note that the end-result of this alternative result is already exactly what you end up after all the juggling shown under 'Reorganizing commits onto their topic branches' above!
mkdir /tmp/q
cd /tmp/q
git init .
touch f
git add f
git commit -am initial
git checkout -b a; # no change
echo a1>a1; git add a1; git commit -am a1
echo a2>a2; git add a2; git commit -am a2
git checkout -b b; # start off the a branch
echo b1>b1; git add b1; git commit -am b1
echo b2>b2; git add b2; git commit -am b2
git checkout a # go back to the a branch for a3 and a4
echo a3>a3; git add a3; git commit -am a3
echo a4>a4; git add a4; git commit -am a4
git checkout b
git rebase a # here is the magic: rebase early
echo b3>b3; git add b3; git commit -am b3
echo b4>b4; git add b4; git commit -am b4
git checkout a # go back to the a branch for a5
echo a5>a5; git add a5; git commit -am a5
git checkout b
git rebase a # again: rebase early
echo b5>b5; git add b5; git commit -am b5
git show-branch
Note that it is in practice not hard to go back to the a branch to commit your a3/a4/a5 commits:
*
*in case you only realized you touched things that belong on that branch, you can just switch to the a branch with pending local changes2
*you then selectively (!!) stage the parts that needed to go onto the a branch (git add -i or similar in git guis or e.g. vim fugitive)
*commit on a
*switch back to the b branch (git checkout b)
*commit the remaining bits
*rebase b onto the latest revision in a
2 as long as they don't conflict with other changes from a..b; in that case you'd git stash first and git stash apply when on the a branch
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to use BindingSource with not 1 to 1 set of columns between the list and the DataGridView I have the following situation working with winforms:
*
*I defined a DataGridView with X columns.
*Bind it to a list containing X-1 columns
dataGridViewMain.DataSource = _bindingSource;
_bindingSource.DataSource = _currentMediaItems;
*After a while I update the list and when performing the following call:
_bindingSource.DataSource = _currentMediaItems;
I get the following error : "At least one of the DataGridView control's columns has no cell template."
Someone can help with a workaround?
thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Convert Decimal to int in Crystal Report Formula i have used formula to generate a RowNumber for each Record
formula is like this:
shared numbervar rownum;
rownum := rownum + 1;
rownum;
But it displays decimal numbers : 1.00, 2.00, 3.00, 4.00
i want to display only Int numbers in RowNumber : 1,2,3,4,5
how can i do this?
Thanks in Advance
A: Select the formula field on the canvas, then click the Decrease Decimals toolbar icon twice.
You should the RecordNumber field instead of incrementing a variable--much less work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Handle multiple db updates from c# in SQL Server 2008 I like to find a way to handle multiple updates to a sql db (with one singe db roundtrip). I read about table-valued parameters in SQL Server 2008 http://www.codeproject.com/KB/database/TableValueParameters.aspx which seems really useful. But it seems I need to create both a stored procedure and a table type to use it. Is that true? Perhaps due to security? I would like to run a text query simply like this:
var sql = "INSERT INTO Note (UserId, note) SELECT * FROM @myDataTable";
var myDataTable = ... some System.Data.DataTable ...
var cmd = new System.Data.SqlClient.SqlCommand(sql, conn);
var param = cmd.Parameters.Add("@myDataTable", System.Data.SqlDbType.Structured);
param.Value=myDataTable;
cmd.ExecuteNonQuery();
So
A) do I have to create both a stored procedure and a table type to use TVP's? and
B) what alternative method is recommended to send multiple updates (and inserts) to SQL Server?
A: Yes, you need to create the types.
Alternatives are sending a big string sql batch or passing XML to sprocs.
The downside to big sql string batches is it can blow the sql proc cache and might cause sql to recompile - especially if the batch is unique because of input data being part of that large string. By definition each batch would be unique.
XML was the main alternative before TVPs. The one downside to XML, for at least awhile, sql azure didn't support it (that might change?) so it limits your options.
TVPs seem to be the way to do this. Our project just converted to using TVPs.
Hope that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I post adaptive payment information to paypal? I've managed to get an adaptive payments script to work in the apigee console, here is the request:
X-PAYPAL-REQUEST-DATA-FORMAT: JSON
X-PAYPAL-APPLICATION-ID: APP-80W284485P519543T
X-HostCommonName: svcs.sandbox.paypal.com
Host: svcs.sandbox.paypal.com
Content-Length: 428
X-PAYPAL-DEVICE-IPADDRESS: 127.0.0.1
X-Forwarded-For: 10.203.10.109
X-PAYPAL-REQUEST-SOURCE: APIGEE-CONSOLE-1.0
X-Target-URI: https://svcs.sandbox.paypal.com
X-PAYPAL-RESPONSE-DATA-FORMAT: JSON
Content-Type: text/plain; charset=ISO-8859-1
Connection: Keep-Alive
"{
"actionType":"PAY",
"currencyCode":"USD",
"receiverList":{"receiver":[{"amount":"5.00","email":"cam_1315509411_per@btinternet.com"}]},
"returnUrl":"http://apigee.com/console/-1/handlePaypalReturn",
"senderEmail":"qwom_1315508825_biz@btinternet.com",
"feesPayer":"SENDER",
"cancelUrl":"http://apigee.com/console/-1/handlePaypalCancel?",
"requestEnvelope":{"errorLanguage":"en_US", "detailLevel":"ReturnAll"}
}"
How do I actually post this information to the https://svcs.sandbox.paypal.com/AdaptivePayments/Pay url? I can't find the easiest way to do it, should I use cURL and what are the variables names for each post value?
A: That depends on the rest of your application. PHP with cURL is fairly straightforward, but it's not too much of a hassle in other languages either.
PayPal has sample code online at https://www.x.com/developers/PayPal/documentation-tools/code-sample/78
If you were to do this yourself, you'd need to (in a nutshell):
- Send a proper HTTP header with the X- headers as shown above including the application ID.
- Send the API call via JSON, SOAP or NVP as POST or GET to the API endpoint
- Decode the response and act accordingly
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SQLiteDatabase select rows where column is equal something I have a SQLiteDatabase and I want to select the rows where one of the row's column is equal to a text. I know to do this with integer but I don't know how to do this with text. And I would like to have more options as WHERE theColumn is equal a or b or c.
A: SELECT * FROM table WHERE theColumn IN ('text1', 'text2', 'text3')
Try to avoid selecting whole rows when not necessary. Also keep in mind string comparisons take longer than integer ones.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Xamdatagrid howto get the current Cell on right click here is the scenario I want ta achieve on some XamDataGrid
*
*Some Cells may be selected in the grid - cells and not records
*User right clicks on a cell in the grid
I would like to add the right clicked cell to the SelectedItems.Cells collection of the XamDataGrid if it was not selected before
BTW - I have no problem getting the entire Record, but what I require is the specific Cell.
any idea?
A: private void GridCellActivated(object sender, CellActivatedEventArgs e)
{
if (((UnboundField)((e.Cell).Field)).BindingPath.Path != null)
{
var _fieldPath = ((UnboundField) ((e.Cell).Field)).BindingPath.Path;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pointer to first element of C struct is the same as pointer to the struct. But not in C#: Interop problem Sorry for title, I have an interop problem.
The C dll that I'm using request, in a function, a pointer to the first element of a struct, however this in C can be cast to a pointer to that struct, while this is not the same in C#. How can I "simulate" this behavior (I need to use that function in C#).
I'll post here a code snippet:
[StructLayout(LayoutKind.Sequential)]
struct lgLcdBitmapHeader
{
public Formats Format;
}
[StructLayout(LayoutKind.Explicit)]
struct lgLcdBitmap
{
[FieldOffset(0)]
lgLcdBitmapHeader hdr;
[FieldOffset(0)]
lgLcdBitmap160x43x1 bmp_mono;
[FieldOffset(0)]
lgLcdBitmapQVGAx32 bmp_qvga32;
}
[StructLayout(LayoutKind.Sequential)]
struct lgLcdBitmap160x43x1 : IDisposable
{
/// <summary>
/// Format = LGLCD_BMP_FORMAT_160x43x1
/// </summary>
public lgLcdBitmapHeader hdr;
/// <summary>
/// byte array of size LGLCD_BMP_WIDTH * LGLCD_BMP_HEIGHT, use AllocHGlobal to make code safe
/// </summary>
public IntPtr pixels;
public void SetPixels(byte[] value)
{
if (value.Length < (int)BitmapSizes.Size)
throw new InvalidOperationException(string.Format("Byte array must be at least of size {0}", (int)BitmapSizes.Size));
if (pixels == IntPtr.Zero)
pixels = Marshal.AllocHGlobal((int)BitmapSizes.Size);
Marshal.Copy(value, 0, pixels, (int)BitmapSizes.Size);
}
public void GetPixels(byte[] arrayToBeFilled)
{
if (arrayToBeFilled.Length < (int)BitmapSizes.Size)
throw new InvalidOperationException(string.Format("Byte array must be at least of size {0}", (int)BitmapSizes.Size));
Marshal.Copy(pixels, arrayToBeFilled, 0, (int)BitmapSizes.Size);
}
public void Dispose()
{
if (pixels != IntPtr.Zero)
Marshal.FreeHGlobal(pixels);
}
}
[StructLayout(LayoutKind.Sequential)]
struct lgLcdBitmapQVGAx32 : IDisposable
{
/// <summary>
/// Format = LGLCD_BMP_FORMAT_160x43x1
/// </summary>
public lgLcdBitmapHeader hdr;
/// <summary>
/// byte array of size LGLCD_QVGA_BMP_WIDTH * LGLCD_QVGA_BMP_HEIGHT * LGLCD_QVGA_BMP_BPP, use AllocHGlobal to make code safe
/// </summary>
public IntPtr pixels;
public void SetPixels(byte[] value)
{
if (value.Length < (int)QVGABitmapSizes.Size)
throw new InvalidOperationException(string.Format("Byte array must be at least of size {0}", (int)QVGABitmapSizes.Size));
if (pixels == IntPtr.Zero)
pixels = Marshal.AllocHGlobal((int)QVGABitmapSizes.Size);
Marshal.Copy(value, 0, pixels, (int)QVGABitmapSizes.Size);
}
public void GetPixels(byte[] arrayToBeFilled)
{
if (arrayToBeFilled.Length < (int)QVGABitmapSizes.Size)
throw new InvalidOperationException(string.Format("Byte array must be at least of size {0}", (int)QVGABitmapSizes.Size));
Marshal.Copy(pixels, arrayToBeFilled, 0, (int)QVGABitmapSizes.Size);
}
public void Dispose()
{
if (pixels != IntPtr.Zero)
Marshal.FreeHGlobal(pixels);
}
}
The problem is that the function ask for lgLcdBitmapHeader pointer
public extern static uint lgLcdUpdateBitmap([In] int device, [In] ref lgLcdBitmapHeader bitmap, [In] Priorities priority);
But this in C can be easily casted to lgLcdBitmap160x43x1 or lgLcdBitmapQVGAx32, but not in C#
What should I do to effectively pass one of those 2 structs to the function?
A: You should declare two overloads of your extern function that take two different ref struct parameters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JFileChooser inside JPanel; how to get users choice The default JFileChooser works, but what I don't like is the fact that it pops up. I'd rather have one GUI in which all the action takes place.
Now, I did manage to do that. The code below places the FileChooser menu nicely inside the GUI, instead of popping up above it.
What I am having a hard time with is how to get my hands on the selected file. I do know the code that works when JFileChooser is not embedded in a Panel, but I cant get this to work.
Anybody??
ps. I did try and look it up, but though Oracle does mention the possibility to place it in a container, it doesnt supply an example. http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html
import java.awt.*;
import javax.swing.*;
class SplitPane extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JSplitPane splitPaneV;
private JSplitPane splitPaneH;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
public SplitPane() {
setTitle("Split Pane Application");
setBackground(Color.gray);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
topPanel.setPreferredSize(new Dimension(700, 500));
getContentPane().add(topPanel);
// Create the panels
createPanel1();
createPanel2();
createPanel3();
// Create a splitter pane
splitPaneV = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
topPanel.add(splitPaneV, BorderLayout.CENTER);
splitPaneH = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splitPaneH.setLeftComponent(panel1);
splitPaneH.setRightComponent(panel2);
splitPaneV.setLeftComponent(splitPaneH);
splitPaneV.setRightComponent(panel3);
}
public void createPanel1() {
panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
// Add some buttons
panel1.add(new JButton("North"), BorderLayout.NORTH);
panel1.add(new JButton("South"), BorderLayout.SOUTH);
panel1.add(new JButton("East"), BorderLayout.EAST);
panel1.add(new JButton("West"), BorderLayout.WEST);
panel1.add(new JButton("Center"), BorderLayout.CENTER);
}
public void createPanel2() {
panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
panel2.add(new JButton("Button 1"));
panel2.add(new JButton("Button 2"));
panel2.add(new JButton("Button 3"));
}
public void createPanel3() {
panel3 = new JPanel();
panel3.setLayout(new BorderLayout());
panel3.setPreferredSize(new Dimension(400, 100));
panel3.setMinimumSize(new Dimension(100, 50));
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser
.setDialogTitle("Browse naar de locatie waar je de gesorteerde bestanden wil zetten en klik op \"OPEN\"");
panel3.add(fileChooser, BorderLayout.NORTH);
}
// this is where my quest starts. Now, I would like to work with the file
// chosen...
// for my ordinary 'popup' fileChoosers the code below works, so I tried the
// code below
// int returnVal = fileChooser.showOpenDialog(panel3);
// if (returnVal == JFileChooser.APPROVE_OPTION)
// fileName = fileChooser.getSelectedFile().getPath();
// System.out.println(fileName);
// but in this case it messes everything up..., after uncommenting I lose
// the frames, and get a popup again...
// anybody a suggestion how to actually get the users chosen file?
public static void main(String args[]) {
// Create an instance of the test application
SplitPane mainFrame = new SplitPane();
mainFrame.pack();
mainFrame.setVisible(true);
}
}
A: Note that you can add an ActionListener to a JFileChooser that will respond to button press, and the ActionEvent's getActionCommand will tell you which button was pressed. E.G.,
public void createPanel3() {
panel3 = new JPanel();
panel3.setLayout(new BorderLayout());
panel3.setPreferredSize(new Dimension(400, 100));
panel3.setMinimumSize(new Dimension(100, 50));
final JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser
.setDialogTitle("Browse naar de locatie waar je de gesorteerde bestanden wil zetten en klik op \"OPEN\"");
panel3.add(fileChooser, BorderLayout.NORTH);
fileChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) {
System.out.println("File selected: " + fileChooser.getSelectedFile());
}
}
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: obtaining an AudioInputStream upto some x bytes from the original (Cutting an Audio File) How can i read an AudioInputStream upto a particular number of bytes/microsecond position ?
For example :
AudioInputStream ais = AudioSystem.getAudioInputStream( new File("file.wav") );
// let the file.wav be of y bytes
Now i want to obtain an AudioInputStream that has data upto some x bytes where x < y bytes.
How can i do that ?
I have been thinking hard but haven't got any method to do that ?
A: The code below shows you how to copy a part of an audio stream, reading from one file and writing to another.
import java.io.*;
import javax.sound.sampled.*;
class AudioFileProcessor {
public static void main(String[] args) {
copyAudio("/tmp/uke.wav", "/tmp/uke-shortened.wav", 2, 1);
}
public static void copyAudio(String sourceFileName, String destinationFileName, int startSecond, int secondsToCopy) {
AudioInputStream inputStream = null;
AudioInputStream shortenedStream = null;
try {
File file = new File(sourceFileName);
AudioFileFormat fileFormat = AudioSystem.getAudioFileFormat(file);
AudioFormat format = fileFormat.getFormat();
inputStream = AudioSystem.getAudioInputStream(file);
int bytesPerSecond = format.getFrameSize() * (int)format.getFrameRate();
inputStream.skip(startSecond * bytesPerSecond);
long framesOfAudioToCopy = secondsToCopy * (int)format.getFrameRate();
shortenedStream = new AudioInputStream(inputStream, format, framesOfAudioToCopy);
File destinationFile = new File(destinationFileName);
AudioSystem.write(shortenedStream, fileFormat.getType(), destinationFile);
} catch (Exception e) {
println(e);
} finally {
if (inputStream != null) try { inputStream.close(); } catch (Exception e) { println(e); }
if (shortenedStream != null) try { shortenedStream.close(); } catch (Exception e) { println(e); }
}
}
public static void println(Object o) {
System.out.println(o);
}
public static void print(Object o) {
System.out.print(o);
}
}
A: Now that you have the stream you can read one byte at a time up to the maximum number ob bytes you want using read(), or read a fixed number of bytes with read(byte[] b).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.