text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: problem with saving data at coredata? In my application there is searchBar. when we input a text, it will do functionGrab (grab data from internet and save it to coredata), example :
if we input "Hallo"
if([[dict objectForKey:@"Category"] isNotEmpty] && [[[dict objectForKey:@"Category"] objectAtIndex:0] class]!=[NSNull class]){
NSMutableArray * DownloadedTags =[dict objectForKey:@"Category"];
NSMutableSet * TagsReturn=[NSMutableSet set];
for(int i=0;i<[DownloadedTags count];i++){
NSString * Value=[DownloadedTags objectAtIndex:i];
Tag * thisTag= (Tag*)[GrabClass getObjectWithStringOfValue:Value fromTable:@"Tag" withAttribut:@"Name"];
[TagsReturn addObject:thisTag];
}
NSMutableSet * manyManagedObjects = [BusinessToSave mutableSetValueForKey:@"Tags"];
[self removeDifferenceBetween2MutableManagedObjectSets:manyManagedObjects withDownloadedVersion:TagsReturn];
}
So each biz has many categories. WHat happen in multi threaded application is one thread put category. The other thread also put the same category before committing.
So, [GrabClass getObjectWithStringOfValue:Value fromTable:@"Tag" withAttribut:@"Name"]; gives a new object even though some other thread already created the same object without knowing it.
If I synchronized the whole thing that the code would run serially and that'll be slow.
functionGrab:"H"
functionGrab:"Ha"
functionGrab:"Hal"
functionGrab:"Hall"
functionGrab:"Hallo"
something like,it do that functionGrab 5 times
I want to make functionGrab at background, but the problem is when I do that function without synchronized it will save more than one of data, so the result is there are 5 hallo words in my coredata, but if I do that with synchronized, it spent so much time, so slow..
is there any way to help my problem?
A: I do not recommended having more than one thread "creating" the same types of data for the exact reason you are running into.
I would suggest you queue all of your "creates" into a single thread and a single NSManagedObjectContext to avoid merge or duplication issues.
The other option would be to make the app Lion only and use the parent/child NSManagedObjectContext design and then your children will be more "aware" of each other.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to match 01-47 I have to grep some log files.
so I code this
egrep [0-4][0-7] log
bug this code has a bug for
08,09,18,19,28,29,38,39
Can I resolve this issue?
A: | allows you to specify alternatives in a regex.
0[1-9]|[1-3][0-9]|4[0-7]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MSBuild Compilation Error Weirdness I'm getting an error compiling a VB .NET project using the MSBuild command line. Running from devenv works perfectly fine:
error BC30518: Overload resolution failed because no accessible 'Invoke' can be called with these arguments:
Line in question:
Windows.Application.Current.Dispatcher.Invoke(Sub() InteractionManager.Current.DisplayException((DirectCast(e.ExceptionObject, Exception))))
Why is MSBuild balking at this when DevEnv/Visual Studio is not? And why is this a problem at all? It looks fine to me.... The ONLY thing I see interesting about this line is that Invoke takes a Delegate class object (not a strongly typed delegate)...so in C#, I wouldn't be able to use a lambda expression where I am now in VB .NET (I'd need to do something like new Action(() => ...)
A: I believe that you are mixing .NET versions.
System.Windows.Threading.Dispatcher has a single argument overload of the Invoke method in .NET 4.5. In .NET 4.0 or older, all available overloads take two or more arguments which rules then out and gives you the error message you see.
I therefore assume that the devenv you are executing is a VS2012 beta whereas the msbuild is something more conventional.
You should be able to resolve the discrepancy by adjusting your Path environment variable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Existing project which is having pom.xml file in it I have been given an existing project which is consisting of pom.xml file in it .
Can we manually run the pom.xml file , to create a war file and deploy it into Tomcat WEB Apps
Please tell me how to do this .
Thank you very much for reading .
(And also in our existing Application , we are having more than one POM.xml files in it )
A: Make sure you have (Maven)[http://maven.apache.org/] installed and set your environment variables for JAVA_HOME and M2_HOME or M3_HOME based on the version of Maven.
From the command line, navigate to the location that has the pom.xml file.
Type: mvn clean install.
This will create a target folder that has the .war in it.
Take the .war file and install in Tomcat.
Hope this helps.
Thanks...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Declaratively setting jQuery.Data property for a HTML link Assuming I have a HTML link in my rows inside a datagrid or repeater as such
<a href="javascript:void(0);" class="DoSomething">DoSomething</a>
Now also assuming that I have handled the click event for all my DoSomethings in jQuery as such
$(".DoSomething").click(function (e) {
//Make my DoSomethings do something
});
What is the correct technique for passing data to the click event that is dependent on the link clicked?
Without jQuery you would typically do something like this.
<a href="javascript:void(0);" class="DoSomething" onclick="DoSomething('<%# Eval("SomeValue") %>');">DoSomething</a>
but this technique obviously doesn't work in the jQuery case.
Basically my ideal solution would somehow add values for to the jQuery.Data property for the link clicked but doing so declaratively.
A: Use HTML5 data- attributes. jQuery support is built-in for 1.4.3+
http://api.jquery.com/data/#data2
<a href="#" class="product-link" data-productid="77">click here</a>
$('.product-link').click(function (e) {
alert($(this).data('productid'));
});
A: You could use the attr() function.
http://api.jquery.com/attr/
$("#Something").attr("your-value", "Hello World");
$("#Something").click(function (e) {
//Make my DoSomethings do something
var value = $(this).attr("your-value");
alert(value); // Alerts Hello World
});
A: your question was not clear to me but may be this will help
$(".DoSomething").click(function (e) {
//Make my DoSomethings do something
$(this).data("key","value");
//later the value can be retrieved like
var value=$(this).data("key");
console.log(value);// gives you "value"
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: "Like Button" does not appear when I paste plug-in code into HTML snippet on iweb? Please help. I've spent hours on this. With Twitter I had no trouble adding a button to my website using iWeb but with facebook.....
The best way I can describe my problem is this: I go through all of the required steps to obtain the plug-in for my facebook page (http://www.facebook.com/thekitchensinkwma). I then "get code", copy the code, drag HTML Snippet onto my desired page in iWeb, then paste the code into the appropriate window (BTW: I've tried all 3 codes several times). When Click the "Apply" button, the "Like" button does not appear.
I'm at my whit's end! Please help. Thanks.
Martin
A: Without seeing the page I have two initial thoughts you can run down:
*
*Your CMS [iWeb or whatever you are using] is altering the fb-root tag which is required for the button to show. Twitter only uses javascript.
*Your page is appearing via iframe, javascript or something from the system is causing Facebook to believe you may be hiding the button to fake a click.
If this is happening with both the iFrame and Scripted method a url will be helpful as it may be more complex.
A: Try adding <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"> to the HTML-tag.
Would be easier if you provided a link though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is compex? I found a bunch of java files online and there is one function that appears all over the place but i cannot find the definition of on google: compex. google keeps on sending me to complex, no matter how i use symbols to make compex an important search term. it doesnt seem to be imported from anywhere. all i have managed to find out about it is that it takes 2 single integers as inputs.
i am not a java programmer. im just trying to figure out what in the world the code means
/*
* PermSortAlgorithm.java
* Patrick Morin takes no responsibility for anything. So there.
*
*/
/**
* A PermSort Demonstration algorithm. The PermSort algorithm is due
* to Patrick Morin <http:www.scs.carleton.ca/~morin>. The algorithm
* works by trying every permutation until it finds one that's
* sorted. That's right, there are n! permutations and it takes O(n)
* time to test each one, yielding an O(nn!) algorithm. No hate mail
* please.
*
* @author Patrick Morin
*/
class PermSortAlgorithm extends SortAlgorithm {
/**
* Check if the input is sorted. Do it in a weird way so it looks
* good for the sort demo.
*/
boolean issorted(int a[], int i) throws Exception {
for (int j = a.length-1; j > 0; j--) {
compex(j, j-1);
pause();
if(a[j] < a[j-1]) {
return false;
}
}
return true;
}
/**
* Privately sort the array using the PermSort algorithm.
*/
boolean sort(int a[], int i) throws Exception {
int j;
// Check if array is already sorted
if (issorted(a, i)) {
return true;
}
// Array wasn't sorted so start trying permutations until we
// get the right one.
for(j = i+1; j < a.length; j++) {
compex(i, j);
pause();
int T = a[i];
a[i] = a[j];
a[j] = T;
if(sort(a, i+1)) {
return true;
}
T = a[i];
a[i] = a[j];
a[j] = T;
}
return false;
}
/**
* Sort the input using the PermSort algorithm.
*/
void sort(int a[]) throws Exception {
sort(a, 0);
}
}
A: It's short for compare-and-exchange.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Barcode scanner SDK for Blackberry can anyone guide me to any of the efficient Barcode scanner SDK which can work in Blackberry SDK. while googling i have got to here about ZXing lib. But i failed to find the samples and to download the SDK.
Help me with some link to the SDK download and test code sample.
A: In past i faced the same problem,after googled i found ZXing bar code scanner api with sample.
The below link will really help you.
http://aliirawan-wen.blogspot.com/2011/05/barcode-scanner-for-blackberry-os-50.html
A: Check this may be useful for u ...
BlackBerry barcode scanning library?
http://supportforums.blackberry.com/t5/Java-Development/Barcode-reader-SDK-or-library/td-p/238641
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to Select from more columns but group by 1 column? SELECT studentnum
FROM Atten
WHERE (att = 'Yes') AND (unitCode = 'MMA1034')
GROUP BY studentnum
HAVING (COUNT(*) < 4)
How do i select more columns? eg, student_name as well?
A: If student information is in Student table, then query may look like this:
SELECT student_name, student_birth_day, studentnum
FROM Student S
RIGHT JOIN (
SELECT studentnum, count(*) as cnt
FROM Attendance
WHERE (attStatus = 'Yes')
AND (unitCode = 'MMA1034')
GROUP BY studentnum
HAVING (COUNT(*) < 4)
) A
ON A.studentnum = S.studentnum
A: From GROUP BY (Transact-SQL)
Each table or view column in any nonaggregate expression in the
list must be included in the GROUP BY list
So you have to include it in the group by if it is unaggregated in the select list.
So if you wish to have student_name in the select list, unaggregated, then you need something like
SELECT studentnum,
student_name
FROM Attendance
WHERE (attStatus = 'Yes')
AND (unitCode = 'SIT103')
AND (CONVERT(VARCHAR, attDate, 101) < '10/10/2011')
GROUP BY studentnum,
student_name
HAVING (COUNT(*) < 4)
A: if the student_name exist in the same table you need to pass it after your studentnum like
SELECT studentnum,student_name
if student_name exist in the different table you need to use the joins.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: asp.net dropdownlist onmousehover event fire dropdown display data I have asp:DropDownList control which i want to display data to user who don't want to click on it.
But user only want to make Mouse hover over asp:DropDownList Control.
Is there any possible way to make it without using datalist control or gridview ?
If so let me know it please.
A: <script>
function Open_ddl(ddl) {
document.getElementById(ddl).size = 5
}
function Close_ddl(ddl) {
document.getElementById(ddl).size = 1
}
</script>
...
<asp:DropDownList ID="ddlPostClaim" runat="server" onmouseover="Open_ddl('ddlPostClaim')" onmouseout="Close_ddl('ddlPostClaim')"></asp:DropDownList>
This does however create a new problem where the mouseover over the menu items will not highlight them, at least for me. Nonetheless, it's a start.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why isn't applicationShouldOpenUntitledFile being called? I added a applicationShouldOpenUntitledFile method to my application delegate, returning NO as Apple's documentation specifies. However, I'm still getting a new document on startup. What's wrong?
@implementation AppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSLog( @"This is being called" );
}
- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender
{
NSLog( @"This never is" );
return NO;
}
@end
A: -(void)applicationDidFinishLaunching:(NSNotification *)notification
{
// Schedule "Checking whether document exists." into next UI Loop.
// Because document is not restored yet.
// So we don't know what do we have to create new one.
// Opened document can be identified here. (double click document file)
NSInvocationOperation* op = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(openNewDocumentIfNeeded) object:nil];
[[NSOperationQueue mainQueue] addOperation: op];
}
-(void)openNewDocumentIfNeeded
{
NSUInteger documentCount = [[[NSDocumentController sharedDocumentController] documents]count];
// Open an untitled document what if there is no document. (restored, opened).
if(documentCount == 0){
[[NSDocumentController sharedDocumentController]openUntitledDocumentAndDisplay:YES error: nil];
}
}
A: I'm using Xcode 8.3.2 and compiling for Os X 10.11 using a storyboard for a document based app.
I noted that, if you set the window controller as initial controller, a window is created without any document and without calling applicationShouldOpenUntitledFile.
I solved removing the "is initial controller" checkbox in the storyboard.
A: You're running Lion. When you ran before adding the applicationShouldOpenUntitledFile handler, a new document was created. Now, with 10.7's "Restore windows when quitting and re-opening apps", your application is restoring that untitled window, and not creating a new one as you suppose.
Close that window and re-run your application, and applicationShouldOpenUntitledFile will be called and will suppress the creation of a new untitled file.
A: If you're not running Lion / 10.7 or later, this can still happen if you have some other window open (even a non-Document window) when applicationShouldOpenUntitledFileshould be called.
I have a Document-based app where the AppDelegate class opens a global logging window, both for debugging purposes and for user status messages. If I have the program display that window on startup while running on OS X 10.6, applicationShouldOpenUntitledFile never gets called, even with no document windows displayed. If I turn that window off, the call is made.
A: Since OSX Lion, the app's state restoration may interfere with your custom preferences for this exercise.
Citing an update to Aaron Hillegass and Adam Preble's book Cocoa Programming for MacOSX:
Note that Mac OS X Lion's state-restoration features may make it tricky to observe the new document preference. You can disable state restoration by editing the Run scheme in Xcode. Open the product menu and select Edit Scheme. Select the Run RaiseMan.app scheme, change to the Options pane, and check Disable state restoration.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Is there any jquery print preview that shows you the printed page without the website header & menu? My web application generates reports and I need now to add the print preview functionality to these reports in order to show the user what he will print of that report and to show him that the report will not contain the website header and menu in the printed page.
Should I use the combination of jquery and css to do this functionality?
A: Create style sheet with the media type as rpint
For example
<link rel="stylesheet" type="text/css" media="print" href="print.css">
Check this out : CSS Media Types Create Print-Friendly Pages
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Firefox Video tag failed i got a problem when use html5 video tag
I created a sample aspnet mvc project , on a page (named Index), i test video tag
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<video autoplay="true" controls="controls" type="video/mp4" id="vd" >
<source src="/Content/Video/oceans-mini.mp4"></source>
Your browser does not support the <code>video</code> element.
</video>
start debugging this project , it only work in Safari and Chrome, IE and firefox got dump with a gray rectangle and a "X" sign inside ...
after using firebug to check net request/response, i got this
[Response]
HTTP/1.1 206 Partial Content
Server: ASP.NET Development Server/10.0.0.0
Date: Tue, 27 Sep 2011 04:35:46 GMT
X-AspNet-Version: 4.0.30319
Content-Range: bytes 0-4484952/4484953
Etag: "1CC78E2DCD83280"
Cache-Control: public
Content-Type: application/octet-stream
Content-Length: 4484953
Connection: Close
why the connection is "close" , is there any config needs in my project
here my web config/webserver section , remain are default
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
<staticContent>
<mimeMap fileExtension=".mp4" mimeType="video/mp4" />
</staticContent>
</system.webServer>
appreciate any suggest
A: firefox doesn't understand proprietary formats like mp4. you should use separate video formats and put them in source elements like so
<video controls>
<source src="foo.ogg" type="video/ogg">
<source src="foo.mp4" type="video/mp4">
you can generate different formats online via media.io
A: Apple uses mp4 while firefox and ie use .ogg/.ogv. OGG was the standard but, Apple refused to use it that is why there are two now.
<video autoplay controls>
<source src="/Content/Video/oceans-mini.mp4" type="video/mp4">
<source src="/Content/Video/oceans-mini.ogv" type="video/ogg">
Your browser does not support the <code>video</code> element.
</video>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DropdownList with Multi select option? I have a DropDownList as following
<asp:DropDownList ID="ddlRoles" runat="server" AutoPostBack="True" Width="150px">
<asp:ListItem Value="9" Text=""></asp:ListItem>
<asp:ListItem Value="0">None</asp:ListItem>
<asp:ListItem Value="1">Ranu</asp:ListItem>
<asp:ListItem Value="2">Mohit</asp:ListItem>
<asp:ListItem Value="3">Kabeer</asp:ListItem>
<asp:ListItem Value="4">Jems</asp:ListItem>
<asp:ListItem Value="5">Jony</asp:ListItem>
<asp:ListItem Value="6">Vikky</asp:ListItem>
<asp:ListItem Value="7">Satish</asp:ListItem>
<asp:ListItem Value="8">Rony</asp:ListItem>
</asp:DropDownList>
I want to select Multiple name at once suppose I want to select Ranu Mohit or Ranu Kabeer Vikky, How its possible?
A: asp:DropDownList does not support multiple selects:
VerifyMultiSelect():
Always throws an HttpException exception because multiple selection is not supported for the DropDownList control.
You can use asp:ListBox with SelectionMode="Multiple" instead:
<asp:ListBox SelectionMode="Multiple" ID="lbRoles" runat="server" AutoPostBack="True" Width="150px">
<asp:ListItem Value="9" Text=""></asp:ListItem>
<asp:ListItem Value="0">None</asp:ListItem>
<asp:ListItem Value="1">Ranu</asp:ListItem>
<asp:ListItem Value="2">Mohit</asp:ListItem>
<asp:ListItem Value="3">Kabeer</asp:ListItem>
<asp:ListItem Value="4">Jems</asp:ListItem>
<asp:ListItem Value="5">Jony</asp:ListItem>
<asp:ListItem Value="6">Vikky</asp:ListItem>
<asp:ListItem Value="7">Satish</asp:ListItem>
<asp:ListItem Value="8">Rony</asp:ListItem>
</asp:ListBox>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: call other layout or xml file in frame of a tab in android Inside frame of my tab i am calling an activity having first.xml xml file. Inside this i have two different layout. I have one more xml file graph.xml. Right now i am passing my intent to another activity where i have setcontentview of graph.xml but what i want now is to display this graph inside my first.xml file.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:layout_width="fill_parent">
<LinearLayout android:layout_width="fill_parent" android:id="@+id/linearfullview" android:layout_height="400sp" android:background="@drawable/background_full_view" android:layout_alignParentTop="true"/>
<LinearLayout android:layout_width="wrap_content" android:layout_height="180sp"
android:layout_alignParentBottom="true" android:layout_marginTop="20sp">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:paddingTop="4dp"
android:gravity="bottom"
android:layout_marginTop="30dp">
<com.widget.WheelView
android:id="@+id/segment"
android:layout_height="wrap_content"
android:layout_width="100dp"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
I want to have graph.xml layout inside linearfullview linear layout. please suggest
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Calling variables with pointers in a typedef Hello i know a bit about pointers in C but the problem I am running into is how to access variables in an this typedef enum.
The structure is defined as:
typedef enum {
ZERO = (uint8_t) 0, ONE = (uint8_t) 1
} BIT;
typedef BIT lc3_word_t[16];
and the method that is calling it is:
word_not(lc3_word_t *R, lc3_word_t *A) {
/*int i;
for (i=0;i<16;i++){
printf("Current i is: '%d' and the value is: '%d' \n", i, *A[i]);
//lc3_word_t a_value = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1}; // 13
}
*/
}
The commented out section is what I have been trying along with some other variations that were introduced in this post: Understanding C: Pointers and Structs
If anyone could help me get this it would be greatly appreciated.
THanks
A: You want to use (*A)[i], not *A[i].
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Curious: what is this syntax that Facebook's polling services is using during the callback I was watching the Network Monitor on Chrome's developer tool seeing how Facebook updates content throughout their news feed.
All of the responses from AJAX begin with the following:
for (;;);{"__ar":1,"payload":[]}
What is the for(;;); piece doing?
Is this part of their custom JS framework? Or is this native and just something I am unfamiliar with?
It seems to be loading as a json object when I preview it.
A: It appears to be a lame attempt at content protection (DRM). The for() loop is basically infinite. The intention appears to be that anyone sourcing their AJAX request with javascript naively will end up with code that hangs because of the infinite loop.
The for() loop would also generate errors for standard JSON parsers like those found in jQuery or YUI or even from JSON.org. To consume the request you need to write your own parser or first remove the for() loop from the request.
Which is why I said this looks lame. Because it isn't difficult to remove the for() loop from the string with a bit of code.
A: It's not really content protection per se; as has been noted, it is trivial to work around it. The likely purpose is to "break" apps that simply take the string and feed it to a javascript eval() function. That approach was once quite common, and still can be found more often than you would think. I suspect there are quite a few programmers out there who think that is actually the proper way to parse a JSON string into javascript variables. Adding the for-loop to the beginning of the string loosely enforces a parse-instead-of-eval rule. Of course it's still trivial to work around it if the programmer is dead set on using eval. I would say it's meant more as a broken-code detector that will force old (and lazy) coding to be corrected.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: "Vista-only" heap corruption in a MFC application Ours is a MFC application, which links to a win32 DLL. When the application invokes this DLL function, the argument "buffer" becomes a "Bad Pointer", after entering the function stack. This results in an application crash.
static MyClass* Instance(string& buffer);
I changed the argument type to "char *", but it only pushes the crash to next statement in the function. How to detect this heap corruption?
Few hints
*
*This crash is reproducible, even if I invoke this DLL function from the very start of our application (CWinApp constructor). Could this memory corruption be caused by loading of resources, manifest etc?
*The crash is ocurring in Vista and Win7, but not in XP.
*Both these projects were recently migrated from Visual Studio 2002 to VS2008.
Code that invokes the function
CString data = "some string";
string str = data.GetBuffer();
data.ReleaseBuffer();
MyClass *obj = MyClass::Instance(str);
A: There were two mistakes:
*
*Couple of custom built C++ files were not compiled with MD switch. We had to add -MD to the custom build script to make the CRT consistant with other objects.
*There were LNK2005 conflicts between LIBCMT.LIB and MSVCRT.LIB, which were otherwise ignored due to the /FORCE switch. We resolved these conflicts by removing LIBCMT.LIB in Linker->Input
Thanks all for your help.
A: My guess is this is wrong usage of calling conventions or a CRT mismatch (i go with calling conventions).
Try building a stub DLL with the same function signature (which does nothing) and make it work with your MFC app.
Here's an example...
HTH
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to grab large xml response using ksoap I am using the ksoap library to consume .net webservice. One of the request returns a very larger xml response.The thing is ksoap shows only partial response.But the wireshark trace shows xml response as sequence of TCP segments which represent the bulk XML.
any idea to grab full xml response?
A: You can modify HttpTransportSE.java file for saving WS response directly in a xml file. Then you can parse it as you prefer. Last ksoap release (3.0.0) has got a method for saving response in a file if you don't want modify java class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Passing data from a table view to another when clicking a row in Objective-c Suppose I have a table view with 5 rows, each row have product name(UiLabel), product photo(UiImageView) and product price(UiLabel).
When clicking a row, it will be changed to a UiView that showing the product name(UiLabel), product photo(UiImageView) and product price(UiLabel), plus a product description(UiLabel).
I want to ask how to pass the data of product name, photos, price and description which is stored in ProductListTableView.m, from this table view to another view ProductDetailView?
ps: I guess I should write some code on method didSelectRowAtIndexPath, but no idea...
A: yes you have to write code in didSelectRowAtIndexPath-
and follow this to how to pass data from one class to another - Passing data between classes using Objective-C
you can pass a NSDictionary obj from one class to another.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does Java allow such strange code using inner class to pass compilation? Hi I tried below code while learning Java inner class. So surprising it passed compilation but could not work in run-time. My understanding is for inner class it must be instantiated in an instance of the top class.
But why JDK compiler allow such code to pass compilation? I am using JDK 6.
public class Hello
{
public Hello()
{
System.out.println("Simple Hello!");
}
public void test()
{
Test.test();
}
protected int i = 0;
static class B
{
public B()
{
System.out.println("B Hello!");
}
static class C
{
public C()
{
System.out.println("C Hello!");
}
}
}
}
class Test
{
static void test()
{
C c = new C();
}
}
A: Here’s what I get:
$ javac -version
javac 1.6.0_26
$ javac Hello.java
Hello.java:31: cannot find symbol
symbol : class C
location: class Test
C c = new C();
^
Hello.java:31: cannot find symbol
symbol : class C
location: class Test
C c = new C();
^
2 errors
Are you 100% sure you are able to compile that code?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
}
|
Q: Validate preferences. Android I have PreferenceActivity with 2 fields.
*
*A URL
*Time in seconds
I need to validate the first one for a valid URL and the second for an integer value. How do I do it with standard means?
A: You can use android:inputType attribute for these fields in the xml, this will display a keyboard to the user for entering the value in a specific format.
See more
http://developer.android.com/reference/android/text/InputType.html
But this do not guarantee that the URL will not be malformed. That you would need to check using regular expression in your submit handler.
A: Here's some code implementing OnPreferenceChangeListener in your fragment:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Your_Pref = (EditTextPreference) getPreferenceScreen().findPreference("Your_Pref");
Your_Pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Boolean rtnval = true;
if (Your_Test) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Invalid Input");
builder.setMessage("Something's gone wrong...");
builder.setPositiveButton(android.R.string.ok, null);
builder.show();
rtnval = false;
}
return rtnval;
}
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: DML statement in a SQL Views I am trying to create a view in that view I want to insert a record or update a record based on perticular condition so can we insert or update in SQL view. Can we have insert or update statement in view?
A: Short answer: Yes. But there are restrictions.
Eg: (taken from http://msdn.microsoft.com/en-us/library/ms180800(v=sql.90).aspx )
Any modifications, including UPDATE, INSERT, and DELETE statements, must reference columns from only one base table.
The columns that are being modified in the view must reference the underlying data in the table columns directly. They cannot be derived in any other way, such as through:
*
*An aggregate function (AVG, COUNT, SUM, MIN, MAX, GROUPING, STDEV, STDEVP, VAR and VARP). 2. A computation; the column cannot be computed from an expression using other columns. Columns formed using set operators (UNION, UNION ALL, CROSSJOIN, EXCEPT, and INTERSECT) amount to a computation and are also not updatable.
The columns that are being modified cannot be affected by GROUP BY, HAVING, or DISTINCT clauses.
TOP cannot be used anywhere in the select_statement of the view when WITH CHECK OPTION is also specified.
Sooo... if it is a relatively straight forward insert or update you're trying to achieve, then it is very possible - but the more complex the query (and the view), the more difficult it becomes.
I'd also offer some advice against doing this if you can - in my opinion it adds an unnecessary layer of complication and (as someone who has had to unravel others queries that use this process) it is a real pain to maintain.
A: No you cannot have an insert or update statement in a view. Refer to the documentation for CREATE VIEW
CREATE VIEW [ schema_name . ] view_name [ (column [ ,...n ] ) ]
[ WITH <view_attribute> [ ,...n ] ]
AS select_statement
[ WITH CHECK OPTION ] [ ; ]
It enforces that the definition must be a SELECT statement.
A: It would probably be better to instead use a stored procedure or function that returns a table.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: String in switch java switch(title)
{
case "Return":
returnBooks();
break;
}
strings in switch are not supported in -source 1.6, use -source 7 or higher to enable strings in switch
So, I have already installed JDK7, Why compiler show this message and giving an error while on compiling?
I am using NetBeans
A: In NetBeans, go to the properties of the project and change the java platform to java 7 in libraries
A: I have found a solution:
If you are using Netbeans 7.1 (even, 7.0), just you have to follow this:
Right Click on Project -> Properties -> Sources -> (On the bottom) Source/Binary Format
Just select JDK 7, and that's all, you can then use strings in switch!
A: I hate to say it, but: read the darn error message. It tells you exactly what the problem is.
You are compiling in Java 6 mode, not compiling in Java 7 mode. If you're using javac that comes with JDK 7, as the error message says, use the -source 7 flag:
> javac -source 7 {stuff here}
A: Two key points from the user query:
*
*Already installed JDK7;and
*Using Netbeans
So, netbeans came with two package:
*
*With JDK
Means when install the Netbeans 7 it automatically install JDK 7 and set JDK 7 as Default Library.
*
*Without JDK
On the installation of NetBeans 7, it found JDK in the system, and if found it automatically configure the path of library as well, but show you information about the path and version of JDK7.
All of users try to give the correct answer of this query, but no one is in position to answer in the correct way as the user required because user using the Netbeans as well.
With continue the edit version of Hemal Pandya, one thing more is required to configure, which is that
RightClick on Project > properties > and in the categories option select > source. see the
**Hemal Pandya** edit version to look at image, the source option is available above the
Libraries option.
And
then select **Source/Binary Format** form bottom and set it to JDK 7 (= 1.7). this is the exact solution
of user's post and I am 100% sure now String in swich will work
A: I do not use NetBeans but there seems to be a compliance switch that has defaulted to 1.6. You will have to find that switch and set it to 7, as others have pointed out.
EDIT: I found I found netbeans.org/kb/docs/java/project-setup.html#projects-jdk. You seem to have done the second step of registering jdk. But maybe it is not the default? Follow the instructions to To switch the target JDK of a standard project. Looking at images it seems to be in this dialog:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do you normalize an ontology the way you would normalize a relational database? I know how to normalize a relational database. There are methodologies for getting to a fifth normal form. I understand the reasons why you may want to back off to fourth normal or otherwise.
What is the equivalent method for an ontology which describes a graph?
A: I am not aware of any mechanism for ontologies that is directly comparable to database normalization. The closest match I can think of are ontology design patterns. However, they are much less strict. You can roughly compare them to software design patterns. You can check
http://ontologydesignpatterns.org/wiki/Main_Page
or have a look at some papers, e.g., about the M3O (http://dl.acm.org/citation.cfm?id=1772775), Event Model F or by Aldo Gangemi, among many others. Ontology design patterns also give you certain properties, but they mainly depend on the patterns you use, and which ones are appropriate depends on the modeling taks you try to achieve.
Both design patterns and database normalization try to achieve certain properties. I guess the difference is, that design patterns are less strict. The achieved properties are often depending on the patterns you use, the domain, the purpose etc. So, they are not really as generic as the normal forms.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What are the arguments against using size_t? I have a API like this,
class IoType {
......
StatusType writeBytes(......, size_t& bytesWritten);
StatusType writeObjects(......, size_t& objsWritten);
};
A senior member of the team who I respect seems to have a problem with the type size_t and suggest that I use C99 types. I know it sounds stupid but I always think c99 types like uint32_t and uint64_t look ugly. I do use them but only when it's really necessary, for instance when I need to serialize/deserialize a structure, I do want to be specific about the sizes of my data members.
What are the arguments against using size_t? I know it's not a real type but if I know for sure even a 32-bit integer is enough for me and a size type seems to be appropriate for number of bytes or number of objects, etc.
A: Use exact-size types like uint32_t whenever you're dealing with serialization of any sort (binary files, networking, etc.). Use size_t whenever you're dealing with the size of an object in memory—that's what it's intended for. All of the functions that deal with object sizes, like malloc, strlen, and the sizeof operator all size_t.
If you use size_t correctly, your program will be maximally portable, and it will not waste time and memory on platforms where it doesn't need to. On 32-bit platforms, a size_t will be 32 bits—if you instead used a uint64_t, you'd waste time and space. Conversely, on 64-bit platforms, a size_t will be 64 bits—if you instead used a uint32_t, your program could behave incorrectly (maybe even crash or open up a security vulnerability) if it ever had to deal with a piece of memory larger than 4 GB.
A: Uhm, it's not a good idea to replace size_t (a maximally portable thing) with a less portable C99 fixed size or minimum size unsigned type.
On the other hand, you can avoid a lot of technical problems (wasted time) by using the signed ptrdiff_t type instead. The standard library’s use of unsigned type is just for historical reasons. It made sense in its day, and even today on 16-bit architectures, but generally it is nothing but trouble & verbosity.
Making that change requires some support, though, in particular a general size function that returns array or container size as ptrdiff_t.
Now, regarding your function signature
StatusType writeBytes(......, size_t& bytesWritten);
This forces the calling code’s choice of type for the bytes written count.
And then, with unsigned type size_t forced, it is easy to introduce a bug, e.g. by checking if that is less or more than some computed quantity.
A grotesque example: std::string("ah").length() < -5 is guaranteed true.
So instead, make that …
Size writeBytes(......);
or, if you do not want to use exceptions,
Size writeBytes(......, StatusType& status );
It is OK to have an enumeration of possible statuses as unsigned type or as whatever, because the only operations on status values will be equality checking and possibly as keys.
A: I can't think of anything wrong in using size_t in contexts where you don't need to serialize values. Also using size_t correctly will increase the code's safety/portability across 32 and 64 bit patforms.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to capture ALL touch events in iOS? I want to make an application that it capture all touch events and display x,y value in toolbar。
*
*If it's possible to capture all events although event not happened in this app ?
*How to show this app in the Toolbar like the Battery icon (when app run in background) ?
A: 1) You can capture touch events when your own app is running is pretty easy. One way would be to a single root view controller, implement
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
If you really are interested in displaying their coordinates, you will also have to think about questions like what happens in cases of multitouch.
However,
This is not possible for other apps. 2) is not possible at all. You don't have access to the status bar and you will not be able to do anything like capturing touch events when the application is in the background anyway. You can only capture events when your application is in the foreground.
A: Neither of your goals can be accomplished on a non-jailbroken device (and probably not even on a rooted one), because it violates the spirit of the Application Sandbox.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: cookie that only exists while viewing a particular page? The title ways it all. I want to use a cookie to send some metadata over to the client that is specific to the current page he is viewing. I'd rather not put it in the HTML, mainly because the metadata is only calculated after all the HTML is already generated and the closing </html> tag is in place.
Previously I was simply sticking it in a hidden <input/> after the final </html>, and browsers seem to render it fine, but I want to do the same thing while having standards compliant HTML. Although I want the cookie to be sent back whenever the client makes an ajax call to the server, I want it to invalidate immediately upon leaving the page.
A: If the page is in an unique path (or can be URL-rewritten as such), then just set the cookie's path attribute to the page's full path. The browser will send the cookie only back whenever the page URL is covered by the cookie's path.
Alternatively, depending on the concrete functional requirement, you could also consider using the HTML5 data attributes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to ignore .svn folder when searching in Total Commander How can I ignore .svn folders when searching in Total Commander?
A: *
*With Total Commander 8.01: Configuration menu / Options / (Operation) / Ignore List
*With older versions: Configuration menu / Options / (Display) / Ignore List
Then add
.svn
to the textbox.
A: In my case I tried search text, but exclude searching in directories bin and obj. I didn't know that pattern before pipe is required too, but I found help here:
https://gist.github.com/DStereo/af5f54c2d2d0d7073383f22753396185
So I had to put pattern in Search for field.
*|bin\ obj\
A: In version 9.12 you should also use an asterix.
So add the following to Configuration menu / Options / (Operation) / Ignore List:
*.svn
A: To exclude some files or folders from your search, use the following syntax in "Search field:":
*
*Exclude from search *.bak and *.old files
my*.*|*.bak *.old
*Don't search in .svn folders
*.cs|.svn\
*Don't search in .git folder
*.cs|.git\
The meaning of | is: 'and not'. Everything after it is excluded from the search. This syntax can also be used in other places, for example inside the ignore list.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "69"
}
|
Q: Track score from SCORM 2004 I am creating a LMS portal and planning to use adobe presenter as the online training quiz builder. After publishing the quiz (scorm 2004), I am not sure how to track the user's score. I already google it but could not find any working example. After searching google, I came to this point that I need javascript to track the score. But no luck yet.
If anyone knows, could you please help me in regards to this.
Thanks
A: Implementing a SCORM conformant LMS is a non-trivial task. Get started by reading up on it here and then dive into the technical parts. You will then want to download the official spec documents from ADL and read those.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to make zindex of a ui element relative to the parent canvas and not the containing canvas? Basically, I'm trying to create a shadow effect on a simple Path element in a user control by putting a ZIndex on the shadow element (also a Path) of 1 and a zindex on the other UI element of 2. These 2 elements are in a user control where the root is a canvas and work as expected in the user control.
I also have a containing canvas that contains 2 instances of this control, where I want the shadow element of each to appear underneath the other's non-shadow element. Its not working and the shadow of one control are appearing on top of the others non-shadow element. If I change the parent canvas's ZIndex index for the user control it puts both elements in the user control on top of the other user controls elements. I assume this is because the ZIndex is only relative to the containing canvas and not all canvases.
What's the best way to go about fixing this without putting all of the UI elements on the same canvas.
A: I'm afraid you are going to have to find a way to assemble your paths into a single Canvas. When a Canvas is rendered it respects the Z-Index of its immediate children only. You can test this as follows:
<Canvas x:Name="LayoutRoot" Background="White">
<Rectangle Width="100" Height="100" Fill="Green"
Canvas.Left="20" Canvas.Top="20"
Stroke="Black"
Canvas.ZIndex="10"/>
<Canvas Canvas.ZIndex="5">
<Rectangle Width="100" Height="100" Fill="Blue"
Canvas.Left="30" Canvas.Top="30"
Stroke="Black"
Canvas.ZIndex="16"/>
</Canvas>
</Canvas>
In the above example, even though the blue rectangle has a ZIndex of 16, which is greater than the ZIndex of the Green rectangle, it is rendered beneath, because it is contained within a Canvas with a ZIndex of 5. Remove the containing canvas and the blue rectangel renders above the green.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: method names in Rails migrations I'm using Agile Web Development with Rails to learn about Rails. In an early chapter, the author created scaffolding and then started looking at the Migration. In his Migration, there is an "up" and and "down" method, whereas I only have a "change" method in my Migration. The author is using Rails 3.05 (or something like that) and I am using 3.1, however, I don't think that's the explanation, because using another book but same version of Rails I remember creating a migration that had the "up" and "down" methods...
So, two questions,
a) What's the reason why I have different method names in my migration?
b) is it going to affect functionality?
My Migration
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string : title
t.text :description
t.string :image_url
t.decimal :price, :precision => 8, :scale => 2
t.timestamps
end
end
end
Books Migration
class CreateProducts < ActiveRecord::Migration
def self.up
create_table :products do |t|
t.string :title
t.text :description
t.string :image_url
t.decimal :price, :precision => 8, :scale => 2
t.timestamps
end
end
def self.down
drop_table :products
end
end
A: Rails 3.1 did away with both the "up" and "down" part of migrations. Now they are called "reversible migrations" that use the change method. So your first code example is correct for Rails 3.1, second is correct for 3.0.x and earlier. Here are the change notes for 3.1 that skim over this update:
https://gist.github.com/958283
The important line: Migration files generated from model and constructive migration generators (for example, add_name_to_users) use the reversible migration's change method instead of the ordinary up and down methods.
The update makes sense if you think about it... you no longer have to define all the steps to "up" your database as well as type out the same steps in reverse to "down" your database. The change method is smart enough to go back and forth given the singe set of instructions.
To answer your second question, no it won't change how the migration works. It will still update your data store per your instructions, keep track of the migration, etc. It's just a more efficient way of describing those changes to your Model.
A: Same code really, just more dry (and slightly less customizeable).
Theres a good description here:
http://edgerails.info/articles/what-s-new-in-edge-rails/2011/05/06/reversible-migrations/index.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: WCF proxy run time initialization and performance implication I'm initializing my proxy manually through ChannelFactory class, as configurations to initialize this proxy is from some other Configuration service (not in same App.Config) and to avoid initializing cost (Service Call, Read Configuration Settings) I cached this proxy. I can't bare the cost to close this proxy after each operation because a frequent operations execution required. Timeout Configurations for this proxy is as follows.
receiveTimeout="00:10:00"
sendTimeout="00:10:00"
closeTimeout="00:10:00"
As per my understanding about Timeout properties at client side, status of my proxy will be Fault when timeout exceed. right?
I want to reinitialize my proxy so I've 2 option to do this.
1) I use ICommunicationObject.Faulted event Handler and when my proxy moved into faulted state in this even I reinitialize the proxy. But this implementation is not suitable because we didn't dispose the proxy properly (calling .Close() method) and it will not release the resources from service side and effect my performance.
2) I create a Thread and set it's elapsed time few seconds before proxy is going to Faulted state. Close this proxy properly by calling .Close{) method and reinitialize another object and cache it.
Please suggest me which option is good in context of performance and do let me know if some other solution exist to avoid this problem.
Thanks in advance.
A: if the proxy is in faulted state you can call Abort on it.
If you really want to keep the proxy around depends on what you need. If you are going to use Duplex-Communication or something like this is might be good advice. If you only call the service from time to time you can go and use the proxy only during calls.
I normaly go and write myself a small proxy that just publishes Connected and Fault events. And I implement IDisposable with code that first tries to close the proxy and when a CommunicationException is thrown goes on to Abort it.
In the code that handles the communication I hold a reference to such a proxy object and dispose it on Close/Fault and open it as soon as I have a operation pending.
This works rather well on the client side even when the network is not reliable.
In case of Duplex-Services I just add a timer that tries to reconnect automatically if the connection is lost.
Here is a small snippet in F# demonstrating the way I use this very simple proxy - it's really nothing more but wrapping the Channel and getting connection-events out - WcfHelper is just a bunch of helper-functions to build up Adresses and Bindings - this case is a stripped down version for a DuplexService so it inherits from DuplexClientBase but the normal non-duplex case is just the same.
/// Duplex-proxy
type private MyProxy(handler, servicename: string, server : string, port : int) =
inherit DuplexClientBase<IWcfConnector>(handler, WcfHelper.getBinding(), WcfHelper.createEndpointAddress(servicename, server, port))
let _connectionEvent = new Event<_>()
do
base.InnerDuplexChannel.Closed.Add(fun _ -> _connectionEvent.Trigger(ConnectionState.Disconnected))
base.InnerDuplexChannel.Opened.Add(fun _ -> _connectionEvent.Trigger(ConnectionState.Connected))
base.InnerDuplexChannel.Faulted.Add(fun _ -> _connectionEvent.Trigger(ConnectionState.Disconnected))
/// sample-Operation
member i.TestCall(message) = base.Channel.TestCall(message)
interface IDisposable with
member i.Dispose() =
try
i.Close()
with
| :? CommunicationException ->
i.Abort()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySQL: Data truncation: Incorrect datetime value: '2006-10-01 02:22:44' I'm getting the following exception updating a row using MySQL via JDBC:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '2006-10-01 02:22:44'
The column is defined as:
'created_on_service timestamp NULL DEFAULT NULL'
There are no indexes or foreign keys on that column.
Obviously it's not a problem with data type. I have values in that table from both before and after that datetime. I also have values with times both before and after 2:22 AM.
A: I fixed the same problem (com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '' for column 'perev_start_time' at row 1) by upgrading my MySQL connector JAR, and copying the mysql.jar to the Tomcat lib directory.
The version of MySQL Server is 5.6 and the MySQL connector is mysql-connector-java-5.1.30-bin.jar.
A: We upgraded MySQL server but didnt upgrade the mysql connector jar. We encountered this issue. Later I figured out it was due to the old jar. I upgraded it and this issue went away.
A: My problem was caused by DST, too. I've fixed it by changing column data type from timestamp to datetime. This answer describes the difference, in short:
*
*timestamp stores time as Unix epoch time, so converts it to/from UTC according to server's time zone. Once you change server time zone, you have different interpretation for INSERT/UPDATE and different SELECT results. Some time points are invalid due to DST;
*datetime stores time as is, regardless of server time zone. When passing UTC time, any time is valid (there are no DST "holes").
Note: you may still have to deal with "missing" time. This approach just shifts responsibility from DB level to application level.
See also: MySQL documentation for TIMESTAMP vs DATETIME
A: Solved it.
Turns out that the 1st of October 2006 in South Australia was the start of daylight savings. Clocks get set forward one hour at 2.00am, so there was no 2:22am on that date: it went straight from 2:00am to 3:01am.
I'll change the db timezone to UTC, which should solve this issue.
A: You did not show exact update SQL. But may be you forget the date part
The correct format is yyyy-mm-dd hh:mm:ss format
Date value should be in following format 2011-11-01 12:32:01
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: Importing resources from OSGi bundle With the import mechanism in OSGi, it is straightforward to import packages from another bundle. However, I have been unsuccessful in importing resources that exist in the "root" of the bundle.
Is it at all possible to import resources that aren't package scoped in to another bundle?
What I would like to achieve is this:
Bundle A has a file resource in the "root"
Bundle B imports bundle A:s packages and resources.
Through bundle B:s ClassLoader, I'd like to be able to load the resource in bundle A as if it existed in Bundle B.
A: Resources in the root of a bundle are in the "default" package, which cannot be imported or exported.
If you really must access the resources via classloader, you need to move them into a package and export that package. Otherwise you can use Bundle.getEntry() to read resources from any location of any bundle.
A: You can use OSGi Fragment bundles. For your case: bundle B is a host and bundle A is a fragment of the bundle B. But bundle B has access to all classes and resources (folders) of bundle A.
More details in OSGi Core Spec #3.13 Fragment bundles
A: Create a new thread and then create a new classloader that points to the files needed.
Look at this fragment:
ClassLoader c = new URLClassLoader(urls);
thread.setContextClassLoader(c);
The thread classloader will then be able load the files within the package where the URLs include the absolute location to the bundle.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: animating ImageButton in android? I am really new to animations in android (and pretty much anything else). Is there a way to animate an ImageButton? I just want to rotate the button for sometimes. Thats all. Any help ?
Thanks.
A: rotate.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromDegrees="0"
android:interpolator="@android:anim/linear_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:startOffset="0"
android:toDegrees="360" />
Java Code :
RotateAnimation rotateAnimation = (RotateAnimation) AnimationUtils.loadAnimation(context,R.anim.rotate);
view.startAnimation(rotateAnimation);
A: Try this code snippet.
rotate.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="0"
android:duration="1000" />
</set>
in java file
ImageButton imgbt = (ImageButton)findViewById(R.id.your_id);
Animation ranim = (Animation)AnimationUtils.loadAnimation(context, R.anim.rotate);
imgbt.setAnimation(ranim);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Ruby max width output I have an array of strings that I need to print joined by a space in a way that each line only shows a maximum of 80 characters (including the space) per line.
So for example if I have:
str_ary = ["I", "am", "an", "array", "of", "strings"]
max_width = 10
I should obtain:
I am an
array of
strings
A: Is this what you mean?
words = %w(foo bar baz quux moomin snufkin fred)
max_width = 11
lines = []
until words.empty?
width = -1 # The first word needs no space before it.
line, words = words.partition do |word|
(width += word.size + 1) <= max_width
end
lines << line
end
for line in lines
puts line.join(" ")
end
Output:
foo bar baz
quux moomin
snufkin
fred
A: words = %w(foo bar baz quux moomin snufkin fred)
assumming max_length is 15 ..
irb(main):147:0> words.inject([[]]) do |memo, word|
irb(main):148:1* (memo.last.join(' ').length + word.length < 15) ? memo.last << word : memo << [word]
irb(main):149:1> memo
irb(main):150:1> end
=> [["foo", "bar", "baz"], ["quux", "moomin"], ["snufkin", "fred"]]
A: This will do it accounting for the spaces:
words = %w(this is jon doe and this is ruby)
max_width = 11
lines = ['']
words.each do |word|
if (lines.last + word).size < max_width
lines[-1] += (lines.last.empty? ? word : " #{word}")
else
lines << word
end
end
p lines
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: google map application not open in blackberry storm 2 i have storm 2 and i downloaded good map application from this url click here
download successful but . in device option>application(third party) i can see Google map app but in download folder i cant see this application .
how can i open this application ? application is already installed when i tried to second time install .
Give me suggetion .
A: Find "Google maps" in "Applications" folder. It is not in "Downloads" folder, it was installed in "Applications" folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL CLR Trigger - get Target / Table name Track column changes - single SQL CLR Trigger for multiple Targets/Tables
SQL CLR Trigger:
Is there a way to get Target / Table name from CLR code?
Purpose:
I'm building a universal SQL CLR Trigger to track column changes in multiple Tables.
Info:
The same CLR trigger can be bound to multiple Tables.
As long as CLR Trigger is bound to a Table, it fires just fine on any Table no matter what Target/Table was specified in CLR Trigger Attribute. It means I can create 1 CLR Trigger and use it for all Tables that require change tracking.
The problem is in calling table name / trigger name identification within the Trigger.
I tried all DMV objects, so far nothing that solves the problem. Btw, @@PROCID is not accessible in CLR.
PS: I have a solution, but is can not be considered as nice and reliable.
A: The tip is to have the Trigger Target set to the right level. Although it's not CLR specific the details can be found in MSDN here but the following would probably work for you.
[Microsoft.SqlServer.Server.SqlTrigger (Name="TriggerName", Target="database", Event="FOR UPDATE")]
Then to figure out what table or field changed access the EventData which is in a SqlXml variable. I created a class similar to the following to access the properties in a structured way.
using System.Data.SqlTypes;
using System.Xml;
using System.Xml.Serialization;
namespace CLRSQLTrigger
{
public class SqlEventData
{
readonly XmlDocument document = new XmlDocument();
public SqlEventData(SqlXml sqlXml)
{
if (sqlXml != SqlXml.Null)
{
document.LoadXml(sqlXml.Value);
}
}
public string EventType
{
get { return document.GetElementsByTagName("EventType")[0].InnerText; }
}
}
}
The values received by a given action are alot easier to decode by dumping the SqlXml variable that is returned when your event is fired. Once you have those values you can use a syntax similar to the EventType Property above or use the GetElementsByTagName method in your code directly. There are literally 100+ events and each event has 4-12 fields, so that part is up to you. If you are serious there is an XSD of the different combinations but it might slow you down compared to the debug method. The XSD path is going to be something like
C:\Program Files\Microsoft SQL
Server\100\Tools\Binn\schemas\sqlserver\2006\11\events
A: public partial class Triggers
{
[SqlTrigger(Name = "TriggerName", Target = "TableName", Event = "FOR UPDATE")]
public static void TriggerName ()
{
SqlTriggerContext triggerContext = SqlContext.TriggerContext;
if (triggerContext.TriggerAction == TriggerAction.Update)
{
SqlConnection connection = new SqlConnection("Context Connection=true");
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SELECT * FROM INSERTED,DELETED";
connection.Open();
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
if (SqlContext.TriggerContext.IsUpdatedColumn(reader.GetOrdinal("State")))
{
reader.Read();
long MessageID = Convert.ToInt64(reader["MessageID"]);
int State = Convert.ToInt32(reader["State"]);
reader.Close();
if (State == 1)
FunctionName.SendMassage(MessageID);
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Jquery ajax .html doesn't work success: function(json) {
for (var i = 0; i < json.length; i++) {
var response = json[i];
$('#rv-container').html('<p>' + response.name + '</p>' + '<span>' + response.id + '</span>');
}
$('#history_tracking').hide();
}
In the success callback $(#rv-container).html() will not work, but .prepend does.
Why doesn't jQuery allow for .html in the success callback?
The problem is the html loaded via ajax keeps on piling up ontop of the data already loaded. So it doesn't replace the data currently in the #rv-container
HTML:
<div id="bottom-toolbar">
<div id="rv-facet">
<div id="rv-fix">
<li id="rv-title">
Recently Viewed <span class="total_viewed"></span>
<div id="rv-total" style="float:right; margin-right:25px;"></div>
</li>
</div>
<div id="rv-content">
<div id="rv-container">
<div id="history_tracking"></div>
</div>
</div>
</div>
</div>
Is there anyway to have prepend replace the contents of the div?
A: You are calling it in a loop, so obviously it makes a difference whether you are resetting the HTML content over and over (.html()) or prepending more and more to it (.prepend())?
A: Each iteration of your loop is defining the element's inner HTML.. So per step in the loop, this would basically be like var text = "this is a test", so that variable would never grow.
You need to append or prepend the data.
success: function(json) {
for (var i = 0; i < json.length; i++) {
var response = json[i];
$('#rv-container').append('<p>' + response.name + '</p>' + '<span>' + response.id + '</span>');
}
$('#history_tracking').hide();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to make an array flexible? public List<int> GetCounts(string connectionstring)
{
List<int> results = new List<int>();
string sqlStmt = "SELECT DISTINCT COUNT(Grouping) from Attendance";
using (SqlConnection conn = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true"))
using (SqlCommand cmd = new SqlCommand(conn,sqlStmt))
{
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
int count = rdr.GetInt32(0);
results.Add(count);
}
rdr.Close();
}
conn.Close();
}
return results;
}
Currently I have this code, I want the array to be flexible, meaning if i have more than two items in the database the array will be automatically updated. The above sql statement will retrieve the items that i want to put in the array above. If the sql statement result has more than 2 items i want the array to be updated automatically.
A: If you want to retrieve an arbitrary number of items from the database, I would suggest the List<T> construct over an array.
Try this:
public List<int> GetCounts(string connectionString)
{
List<int> results = new List<int>();
string sqlStmt = "SELECT DISTINCT COUNT(Grouping) from Attendance";
using(SqlConnection conn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(sqlStmt, conn))
{
conn.Open();
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
int count = rdr.GetInt32(0); // read item no. 0 from the reader, as INT
results.Add(count);
}
rdr.Close();
}
conn.Close();
}
return results;
}
and then you could call this method like this:
string connStr = @"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;";
List<int> counts = GetCounts(connStr);
and you get back a list of all your counts - as many as there are - no dirty array hacks or anything necessary!
The List<T> construct is very flexible, too - you can have a List<string> or a list of any .NET type, really - you can build your own types (e.g. a class consisting of ten properties) and then have a list of that class type. Generics are cool! :-)
A: Use FieldCount property of SqlDataReader to create an array. You can also use SqlDataReader.GetValues(object[]) method to populate an array of objects with column values in current row.
Hope it helps you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: open multiple tabs on a single window by a single click using JavaScript I need to open multiple tabs on a single window, new window instance for a single link will not be a problem but when it comes to 20+ (which is my case) then 20+ new windows are really a problem, so I need to find a solution, the code has to run on chrome only in my case I have 35 links stored in an array. I am reading array using a for loop and opening links in new tabs using window.open()
I can use only JavaScript for this. I am developing a customized chrome extension.
I found out that while using window.open() to open multiple links in different tabs of a same window in Google Chrome, it succeeds in opening only first 24 windows and left out the rest.
I need to find out a way to open all the links at once with a single click.
There are some Google Chrome Extensions available which work like this like
LinkClump
This Extension successfully open all selected links in different tabs of a same window. I am trying to modify its working to suit mine.
Meanwhile, if anyone can get any solution, he/she is most welcome.
A: I wasn't sure if you wanted the links to be open in a new window or not so I've included both possibilities;
Same Window
var linkArray = []; // your links
for (var i = 0; i < linkArray.length; i++) {
// will open each link in the current window
chrome.tabs.create({
url: linkArray[i]
});
}
chrome.tabs documentation
New Window
// will open a new window loaded with all your links
chrome.windows.create({
url: linkArray
});
chrome.windows documentation
Regardless of which approach you use you will need to declare the tabs permission in your extension's manifest.
A: You can use target="_blank" attribute of a link for opening the corresponding page in new tab.
A: Solotion:
Use setTimeout! With more and more time values
javascript:
var a=document.location.href;
for (var i=0;i<50;i++){
setTimeout('window.open(a)',i*200);
}
void(0);
This will clone the current tabs 50 times, even in Chrome! Unfortunately, in new Windows instead of new tabs. Silly Chrome :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Using CFBundleGetVersionNumber I want to get the version number from info.plist using:
NSString *version = (NSString *)CFBundleGetVersionNumber(CFBundleGetMainBundle());
That doesn't give me the string value from Bundle Version that I expect.
This does give me the string I expect:
NSString *version = (NSString *)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey);
I'd like to know how to get the first form to work since it looks like it's the preferred way to get the version from info.plist.
Here is how I'm using the result:
htmlAbout = [htmlAbout stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"[version]"] withString:version];
I'm working in Xcode 4.1
Thanks
A: a serious error in conversion exists in your program: CFBundleGetVersionNumber returns UInt32, which is not convertible via typecast to NSString (or any objc type).
A: CFStringRef ver = CFBundleGetValueForInfoDictionaryKey(
CFBundleGetMainBundle(),
kCFBundleVersionKey);
NSString *appVersion = (NSString *)ver;
If you are using ARC ,
CFStringRef ver = CFBundleGetValueForInfoDictionaryKey(
CFBundleGetMainBundle(),
kCFBundleVersionKey);
NSString *appVersion = (__bridge NSString *)ver;
A: See the Apple docs for CFBundleGetVersionNumber:
https://developer.apple.com/library/mac/#documentation/CoreFOundation/Reference/CFBundleRef/Reference/reference.html
It says your second form is actually the preferred way for X.Y versions:
Where other version number styles—namely X, or X.Y, or X.Y.Z—are used,
you can use CFBundleGetValueForInfoDictionaryKey with the key
kCFBundleVersionKey to extract the version number as a string from the
bundle’s information dictionary.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Canceling a task when the main thread has exited I have a main thread that starts a task but does not wait for its completion. I also have a cancel button on the UI, on the click of which I would like to cancel the task. I tried doing this at multiple places in the method in the task:
if (cancelToken.IsCancellationRequested)
{
return;
}
This however, does not seem to work in the desired way.
Earlier I thought of doing cancelToken.ThrowIfCancellationRequested() but as far as I understand, this raises an exception, and I have no place in the main thread to catch this. What would be the best way to cancel the task in this scenario?
A: Presumably your cancelToken originally came from a CancellationTokenSource which the main thread still has access to. You should just be able to call:
cancellationTokenSource.Cancel();
in your cancel button's click event handler.
ThrowIfCancellationRequested will throw an exception in the task thread, not in the main thread. You would only see an exception in the main thread if you called ThrowIfCancellationRequested and then requested the Result in the main thread.
Note that if you just return after cancellation has been requested, your task's state will end up as RanToCompletion rather than Canceled. Calling ThrowIfCancellationRequested is the preferred way of indicating cancellation, partly as it means if you've got a deep stack within your task's code, you don't need to worry about explicitly returning from each method.
I'm unsure whether cancellation represents a fault that needs to be observed, by the way - I suspect not, but you should probably check. (You should probably have a continuation to deal with errors anyway...)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Moving the focus from One EditText to Another (Horizontal Direction) - Android I have a Scrollview as a parent view, within that i have placed some mixture of linear layout
and there is no probs in the design, but while testing the app, i found that there is a problem in movement of cursor, my intention is to move the focus from one edit text to another that is located adjecent(Horizontally), but when i click the enter button at the bottom, it moves the focus to the next edit text that is vertically located (I knoe,this is default one).
Even i tried with implementing the EditorAction, still the same issue exists.
This is the code that i used to move the focus from one edit text to another.
// Adding the special listener, to be invoked when the action is performed on the editor
firstEditText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// TODO Auto-generated method stub
if(actionId == EditorInfo.IME_ACTION_UNSPECIFIED || actionId == EditorInfo.IME_ACTION_NEXT) {
// Move the focus to the next edittext(secondEditText)
secondEditText.requestFocus();
}
return false;
}
});
Please let me know, how to move the focus from one text box to another placed in a horizontal direction. The above code moves the focus to text box that is vertically located. I tried with searching google a lot, but no results.
I have also shared that screen for better clarity.
Hope i could get a better response here.
Thank you
A: public abstract void onFocusChange (View v, boolean hasFocus){
if(!hasFocus){
secondEditText.requestFocus();
}
}
but fails when scrolled up coz, even in that case the second EditText gets focus and not the above view..
a better solution could be,
GestureDetector.OnGestureListener lis = new GestureDetector.OnGestureListener(){
@Override
public boolean onDown(MotionEvent arg0) {
if(firstEditText.hasFocus){
secondEditText.requestFocus();
return true;
}
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: forcing a scrollbar for fixed element accomodation i am using the jquery simplemodal plugin,
now i've set it up so that it uses a dynamic height, based on the content within it.
however i've run into a bit of a snag here, it seems that if i make the browser window smaller, it does not accomodate for the height of the simplemodal element, therefore some things within the container are hidden off-screen.
i've tried adding:
body {
overflow: auto;
}
and this accomplishes nothing. in fact, the body will scroll when resized based on the content of the page, not the simplemodal element height.
is there a way for me to force scrollbars if a fixed element is overflowing?
A: overflow: scroll
This forces scrollbars to appear, even when not needed.
A: overflow:scroll;
if you only want it to show for an instance(s), put that in a class you can chain to your simplemodal element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SelectedValue lost when tabbing to a combobox (MVVM) I have a datagridtemplatecolumn with CellTemplate / CellEditingTemplate, works ok, after loading it shows the previously choosen selectedvalue bound from the model.
But the problem is that when I 'tab' through the columns the combobox loses it's selectedvalue and gives me an empty one?
I hope there's something wrong with my code:
<data:DataGridTemplateColumn x:Name="colPosId" Width="80">
<data:DataGridTemplateColumn.HeaderStyle>
<Style TargetType="dataprimitives:DataGridColumnHeader">
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Text="{Binding Resource.lblPosId, Source={StaticResource CustomLocStrings}}" Style="{StaticResource ColumnHeaderTextBoxStyleCentered}"/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</data:DataGridTemplateColumn.HeaderStyle>
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Model.posid}" Style="{StaticResource ColumnTextBoxStyleCentered}" />
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
<data:DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox
Height="23" HorizontalAlignment="Left"
x:Name="cmbPositions" VerticalAlignment="Top" Width="100" ItemsSource="{Binding PositionVM.Positions, Mode=TwoWay}" SelectedValue="{Binding Model.posid, Mode=TwoWay}"
DisplayMemberPath="Model.name" SelectedValuePath="Model.posid">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<cmd:EventToCommand Command="{Binding MainScore.SelectionPosChangedCommand, Mode=OneWay, Source={StaticResource Locator}}" CommandParameter="{Binding SelectedValue, ElementName=cmbPositions}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
</DataTemplate>
</data:DataGridTemplateColumn.CellEditingTemplate>
</data:DataGridTemplateColumn>
Kind regards,
Mike
A: try using SelectedItem instead of SelectedValue.
Why do you use a SelectionChangedTrigger? when you bind the SelectedItem with TwoWay you get the selection to your viewmodel.
you should also changed the ItemsSource Binding to Mode=OneWay or OneTime. TwoWay Binding makes no sense here.
A: Fixed it by removing the EventTrigger EventName="SelectionChanged part.
The trigger was for generating the itemsource for combobox B based on the selection of combobox A.
I replaced the functionallity with an eventhandler
_selectedScore.Model.PropertyChanged += SelectedScore_PropertyChanged;
public void SelectedScore_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName =="posid" )
{
this.UpdateFilteredRules(SelectedScore.Model.posid);
}
if (e.PropertyName == "playerid")
{
this.SelectedScore.Model.posid = this.SelectedScore.PlayerVM.GetPosId(SelectedScore.Model.playerid).Model.posid;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to place one image at the corner of another in relative layout in android? I have two images. image A is a rectangle one and image B is a circular one. I want image B to be at the lower right corner of image A - 1/4th of it inside image A and the other 3/4th of it outside.
I am not sure how to do this using relative layout for my android app. Any help ?
Thanks.
A: this code may help you.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/imagepart"
android:layout_width="72dp"
android:layout_height="72dp"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
/>
<ImageView android:id="@+id/imgOnlinePart" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentLeft="true"
android:layout_alignBottom="@+id/imagepart" android:src="@drawable/online"/>
</RelativeLayout>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JQuery toggle not collapsing properly in IE6 I've got 3 divs using JQuery's toggle function to collapse divs:
The divs collapse fine in Firefox, but in IE6 (target browser), this happens:
If I resize the IE window, the divs go back to looking normal, as they do in Firefox.
I've tried to get the code down to its simplest form:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>BIIS Portal</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta http-equiv="pragma" content="cache" />
<link rel="stylesheet" type="text/css" media="all" href="../assets/stylesheets/core-css.css" />
<script type="text/javascript" src="../assets/js/core-js.js"></script>
<!-- This script doesn't seem to work when put it in its own .js file... why? -->
<script type="text/javascript">
$(document).ready(function(){
//Hide (collapse) the toggle containers on load
$(".toggle-container").hide();
//Show all containers with class toggle-opened
//Remove the opened class
//Find the trigger for the now opened container and apply the active class
$(".toggle-opened").show().removeClass("toggle-opened").prev(".toggle-trigger").addClass("active");
//Switch the Open and Close state per click then slide up/down (depending on open/close state)
$(".toggle-trigger").click(function(){
$(this).toggleClass("active").next().toggle();
return false; //Prevent the browser jump to the link anchor
});
});
</script>
</head>
<body>
<div id="wrapper">
<div id="header">
</div>
<div id="body">
<div>
<div class="portlet">
<div class="portlet-header">
<div class="portlet-title">
<h2>BI - External data Control</h2>
</div>
</div>
<div class="portlet-body">
<div>
<h3 class="toggle-trigger">External Data Configuration</h3>
<div class="toggle-container toggle-opened">
blah
</div>
<h3 class="toggle-trigger">Current Notifications</h3>
<div class="toggle-container toggle-opened">
blah
</div>
<h3 class="toggle-trigger">General Information</h3>
<div class="toggle-container toggle-opened">
blah
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
core-css.css:
@import "base.css";
@import "framework.css";
@import "elastic.css";
@import "superfish.css";
@import "/application/css/jquery.autocomplete.css";
@import "/application/css/hspi-content-nav.css";
@import "/application/css/jquery-ui/jquery-ui-1.8.12.custom.css";
core-js.js is merely several JQuery libraries minified, namely:
*
*jQuery JavaScript Library v1.5.2
*jQuery Cycle Plugin (with Transition Definitions) Version: 2.86 (05-APR-2010)
*jQuery Cycle Plugin Transition Definitions Version: 2.72
*jQuery UI 1.8.12
*jQuery UI Widget 1.8.12
*jQuery UI Mouse 1.8.12
I'm not too sure what's happening, as I've mostly copied existing code. I need to get it working right in IE, so any advice is appreciated.
A: add conditional comments for ie6 with .toggle-container and/or .toggle-closed (not sure if you're using that class) display:none
A: A common problem is that things simply aren't redrawn as they should be. If resizing the window or zooming the page work, it's a redraw error and as far as I know there's abolutely nothing you can do about it in code, other than trying to find some other way of coding it that works.
A: @Mitch. I think your main problem it's your CSS styles. You dont provide CSS code, but next example is worked in my tests in IE6-8 and FF7 (except that IE6-7 do not support CSS content style) http://jsfiddle.net/2YyXC/
HTML:
<div id="wrapper">
<div id="header">
</div>
<div id="body">
<div>
<div class="portlet">
<div class="portlet-header">
<div class="portlet-title">
<h2>BI - External data Control</h2>
</div>
</div>
<div class="portlet-body">
<div>
<h3 class="toggle-trigger toggle-trigger-active">External Data Configuration</h3>
<div class="toggle-container toggle-container-opened">
blah
</div>
<h3 class="toggle-trigger toggle-trigger-active">Current Notifications</h3>
<div class="toggle-container toggle-container-opened">
blah
</div>
<h3 class="toggle-trigger toggle-trigger-active">General Information</h3>
<div class="toggle-container toggle-container-opened">
blah
</div>
</div>
</div>
</div>
</div>
</div>
</div>
SCRIPT:
$(document).ready(function() {
$(".toggle-trigger").click(function(){
$(this).toggleClass("toggle-trigger-active").next().toggleClass("toggle-container-opened");
return false; //Prevent the browser jump to the link anchor
});
});
CSS:
.portlet {
padding: 5px 5px 5px 5px;
border: 1px solid black;
}
.portlet-body {
padding: 5px 5px 5px 5px;
}
.portlet-title {
background-color: black;
color: white;
font-family: Verdana;
font-size: 13px;
padding: 6px 6px 6px 6px;
}
.toggle-trigger {
background-color: lightgrey;
color: black;
font-family: Verdana;
font-size: 13px;
padding: 6px 6px 6px 6px;
}
.toggle-trigger:before {
content: "► ";
}
.toggle-trigger-active:before {
content: "▼ ";
}
.toggle-container {
font-family: Verdana;
font-size: 13px;
padding: 6px 6px 6px 6px;
display: none;
}
.toggle-container-opened {
display: block;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Multiple attributes with one attribute using js variable Hello I am having problems with Jade and Node.JS
I have the following code in my template:
- var css = assets.get('css')
each path in css
link(rel="stylesheet" href=path)
It gives me the following error:
SyntaxError: Unexpected identifier
But If I do the following
- var css = assets.get('css')
each path in css
link(href=path)
It seems to work, what am I doing wrong? Any help is greatly appreciated! :)
A: You're missing a comma:
link(rel="stylesheet", href=path)
// here ---^
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I make CGI::Session store session data on the server side using Perl? Is there any way to get CGI::Session to store the session id in something besides a cookie or a query string?
A: Storing session id in the cookie or in the query string are the only 2 ways HTTP protocol allows to transfer session id on each and every request. If you store it somewhere else, then there is no way for the client and server to know they are working with the same session.
A: You can ask CGI::Session to persist session data in a database of your choice. For MySQL, you can do it like so:
use CGI::Session;
$session = new CGI::Session("driver:MySQL", undef, {Handle=>$dbh});
See CGI::Session::MySql for details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JSP onclick event before passing the variable it updates in link I have a link in a jsp that looks like this:
<a href="link?var1=foo&var2=bar"target="_blank">text</a>
I have a form submit submitFormAsync('Form'); that sets a variable ${design.textVar}
How can I set an onclick for this link to submit the form and then pass me the updated variable call it var3?
A: If you want to update your link's href then it must have an id in order for JavaScrpt to find it:
<a id="lnk" href="link?var1=foo&var2=bar" onclick="update();" target="_blank">text</a>
And then append your value to the href:
function update()
{
var link = document.getElementById("lnk");
link.href += "&var3=" + ${design.textVar};
return;
}
UPDATE:
If your var3 value is retrieved asyncronously, then you don't need to use JSP variables, but use pure JavaScript:
function update()
{
var link = document.getElementById("lnk");
var result = submitFormAsync('Form');
link.href += "&var3=" + result;
return;
}
A: function update()
{
var link = document.getElementById("lnk");
var var3 = submitFormAsync('Form');
var url = link.href + "&var3=" +var3;
document.Form.action = url;
document.Form.submit();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Importing an existing Eclipse project into MyEclipse workspace I am trying to import an existing project into my ECLIPSE wORKSPACE .
While importing the project into Eclipse using the
(Existing Projects into Workspace ) option from eclipse ,
i have got the following screen shot .
Now my question is What does the checkbox mean here
(Copy Projects into Workspace )
Please refer to the screen here
http://tinypic.com/view.php?pic=n4tcua&s=7
What is the impact if we check or uncheck the checkbox
Need your help on this .
Thanks .
A: I think he is more concerned about the check box, The check box tells you wether to create a copy of all the resources in the project you are importing to your workspace or not, and if you keep it unchecked it will just create a .classpatha and .project file ( basically a project ) with all the resources refering to original location.
A: The screen asked you to select the root directory and not just a single project. It then displays all the projects present in that directory. You can then allow to choose between the projects to import to the workspace.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Live tiles not picking up image from isolated storage Within my WP7 app, I am generating an image for a live tile and saving in Isolated storage.
It is then available for my periodic task to update the live tile with and everything is working fine in this regard for the periodic task.
The problem I have is at the point in my foreground WP7 app when I create the live tile image I also update the live tile (since I know something has changed so why wait for the periodic task). But when the live tile update occurs here, it seems that it cannot find the newly created file and so presents the live tile without the bitmap.
In terms of the relevant code
Creating the file
var source = new BitmapImage(new Uri("Images/Tiles/Class Timetable with T.png", UriKind.Relative));
source.CreateOptions = BitmapCreateOptions.None;
source.ImageOpened += (sender, e) => // This is important. The image can't be rendered before it's loaded.
{
// Create our image as a control, so it can be rendered to the WriteableBitmap.
var newImage = new Image();
newImage.Source = source;
newImage.Width = 173;
newImage.Height = 173;
// Define the filename for our tile. Take note that a tile image *must* be saved in /Shared/ShellContent
// or otherwise it won't display.
var tileImage = string.Format("/Shared/ShellContent/{0}.jpg", Event.UniqueId);
// Define the path to the isolatedstorage, so we can load our generated tile from there.
var isoStoreTileImage = string.Format("isostore:{0}", tileImage);
and the actual save itself
// Create a stream to store our file in.
var stream = store.CreateFile(tileImage);
// Invalidate the bitmap to make it actually render.
bitmap.Invalidate();
// Save it to our stream.
bitmap.SaveJpeg(stream, 173, 173, 0, 100);
// Close the stream, and by that saving the file to the ISF.
stream.Close();
and the code that actually retrieves the image and updates the live tile (and works in the periodic task but not from the app itself
string imageString = "isostore:/Shared/ShellContent/" + nextEvent.UniqueId + ".jpg";
ShellTile defaultTile2 = ShellTile.ActiveTiles.First();
defaultTile2.Update(new StandardTileData
{
Title = nextTime,
BackgroundImage = (new Uri(imageString, UriKind.Absolute)),
});
Just unsure as to if I am doing something fundamentally wrong here? I am considering storing the generated image in the database with its object. And, I do have a manageable number of files involved here. I am not generating hundreds of the things.
I do have a workaround which is to update the livetile from within the WP7 app without using the image file.
A: Hey that code looks familiar ;-) That aside, there's nothing in the code you posted that actually can determine the problem.
My guess is that you're calling NotifyComplete() to early in your periodic task. For this, I recommend you use the Task Parallel Library to workaround the problem.
I actually wrote a article about it this very morning: How To: Live Tile with Scheduled Agent
The essential part is to use Task.ContinueWith to ensure that NotifyComplete() is first called after you finished rendering the background image, and saved it to the isolated storage.
A: You shouldn't need the isostore: prefix on teh path when creating it within the main app. Try just creating a Relative URI to the file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: jQuery - Ajax call failing to reach success callback but still functioning My question:
My ajax request downloads a generated file as expected but never fires the success callback and fires the complete callback immediately. How do I get a function to be triggered by the completed download of the file?
Some details:
I have a form that submits to itself and calls a function that generates a file for download.
The ajax:
var prepdata = 'start=' + startdata + '&end=' + enddata;
$.ajax({
url: 'index.php',
data: prepdata,
success: function(){console.log('success.');},
complete: function(){console.log('complete')}
});
So you submit a form (in index.php), the form submits to the same page (index.php) and passes some $_GET paramaters. The presence of the $_GET params triggers a function that gets some data from the database, formats a file and outputs it with:
header("Content-type: application/vnd.ms-excel");
// more headers here... the correct ones, trust me
print $data;
exit;
Now, all of this works, resulting in a downloaded file. The problem is that I want to fire a javascript function (that removes a "...loading" symbol) after the page has been downloaded. What happens is that the "success" callback is never triggered while the "complete" call back is triggered immediately after submitting.
How do I trigger a function after the data has been downloaded?
Any ideas? One more thing, in Safari I see the following console error:
GET http://mysite.com/somedir/?start=1&end=2 Frame load interrupted
Which I assume has something to do with the headers being output and interrupting the flow of things, and which I assume is why the ajax is failing. Just don't know how to work around it.
EDIT: Nothing worked. :( I tried loading into an iframe but couldn't get the load event to trigger because of the frame load interrupted issue. In the end I just faked it with a timeout that runs after a set period that is slightly longer than the longest download I can reasonably expect.
A: Hmm, I believe I have fixed my similar situation (although mine doesn't use ajax, I am setting HTTP headers to download data as a result of a submit). Random punt: try changing your form from GET to POST. Still think it is a Safari bug, as it doesn't appear to affect FF or Chrome.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Blackberry Simulator problem I am using BB Java sdk 6.0.0.30 and I have installed BB 9780 Simulator Simpackage-6.0.0.285_9780 which I downloaded from BB site.
I installed this on net.rim.ejde.componentpack6.0.0_6.0.0.30\components\simulator, after runnig an application I am facing the following problems
1 Not able to clean the simulator (I tried Project > Blackberry > Clean Simulator )
2 Not able to view Edited app on running, the app which is installed first time remains on the simulator after making some changes in code the new version is not getting loaded, but when I tried debugging the app with modified code is installed.
Any help is welcome
Regards,
A Y.
A: Try to run clean.bat in C:\Eclipse\plugins\net.rim.ejde.componentpack6.0.0_6.0.0.30\components\simulator\clean.bat. also close simulator before running it.
A: When you want to clean the SIMULATOR you MUST close the simulator.
There is no need to clean SIMULATOR everytime. If you change your code then:
Rightclick on your project ------> refresh;
Rightclick on your project ------>BuildPoject;
Rightclick on your project ------> Debug As----->DebutCofiguration--->Debug;
If you have doubts come on StackOverFlow chat room name "Life for Blackberry" to clarify Your and our doubts.
A: Check in eclipse Project>Build Automatically is selected....
check your java version by typing java -version command in cmd it should be 1.6 ....
to set path for new jdk type : set path=C:\Program Files\Java\jdk1.6.0_16\bin im cmd
may be this information is useful for u.... best of luck
A: In Eclipse plugin,
GO TO YOUR INSTALLATION PATH\plugins\YOUR COMPONANT PACK WHAT ARE YOU USING\components\simulator\,
RUN clean.bat;
Other idea just download again the installaer and install in a separated directory and copy the simulators from there to your existing eclipse directory.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to know if an activity is called using startActivityForResult or simply called by using startActivity? or should i send some extra data in the Intent to know the call ?if there is no predefined method,like getIntent and do something with it ?
A: I think that you should expose several intents for the same activity in your manifest, then test the calling intent to adapt your behaviour.
Example for your activity intent filter in the manifest:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.EDIT" />
<action android:name="android.intent.action.PICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
and corresponding code in your activity onCreate:
if (getIntent().getAction().equals(Intent.ACTION_VIEW)) {
// do whatever you need to do here
} else if (getIntent().getAction().equals(Intent.ACTION_PICK)){
...
}
A: I know this question is answered already but I have a better solution..
When your activity was started just by startActivity() a getCallingActivity() method in target activity will return null. When it was called by startActivityForResult() it will return name of calling activity.
See getCallingActivity for more details.
So you can check in Activity before finishing for calling activity. If result is null Activity was called by startActivity() and if result is not null then Activity was called by startActivityForResult(). Thats it.
example :-
if (getCallingActivity() == null) {
//This Activity was called by startActivity
} else {
//This Activity was called by startActivityForResult
}
A: you can put a flag like "0" and "1" , putting it in intent, so if "0" then its startActivity or "1" for startActivityForResult... this is simple, isnt it?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Overriding a WPF window style in a Prism module I'm writing a module for a prism application that we do not control. The requirement is to show a web browser control in one of the regions. Unfortunately, each window derives from a CustomWindow class, that has AllowsTransparency=true. Having AllowTransparency=true prevents the WebBrowser control from displaying.
I can right click and hover over the control and know there is a web page loaded (google), so I'm nearly certain that the problem I'm facing has to do with transparency and win32 controls (of which the WebBrowser is a wrapped win32 control to my knowledge).
So, I've decided that my only course of action is to try and override the Window style, to turn AllowTransparency off.
This is the offending style (using Reflector to browse the baml):
<Style x:Key="{x:Type local:CustomWindow}" TargetType="{x:Type local:CustomWindow}">
<Setter Property="AllowsTransparency" Value="true" />
...
</Style>
And this is how I'm trying to remove the style:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="clr-namespace:Vendor.App.WPFCommon.Controls;assembly=Vendor.App.WPFCommon">
<Style TargetType="{x:Type Controls:CustomWindow}">
<Setter Property="AllowsTransparency" Value="false" />
</Style>
</ResourceDictionary>
private void LoadThemeOverrides()
{
var assemblyName = System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().ManifestModule.Name);
var overrides = new Uri(string.Format("{0};component/themes/overrides.xaml", assemblyName), UriKind.Relative);
var themeManager = _container.Resolve<IThemeManager>();
foreach (var theme in themeManager.ThemeCollection)
theme.Sources.Add(overrides);
var rd = new ResourceDictionary {Source = overrides};
Application.Current.Resources.MergedDictionaries.Add(rd);
themeManager.ChangeTheme(themeManager.CurrentTheme);
}
The ResourceDictionary is being loaded correctly, so it's not the URI that is the problem. I debugged the rd, and I can see my style in there.
The above piece of code is run between the login window validating user/password, and the main application window being displayed. They are two different windows, however, they both derive from CustomWindow.
Using WPF Inspector, I can see that the CustomWindows still have AllowTransparency set to true. Am I able to override this style at all? Or am I attempting to do this incorrectly?
A: With windows, setting implicit style will not work in every situation. You have to give a key to the style and find a way to set the style explicitly on the window that requires that.
Using ResourceKey might help, depending upon your architecture.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cannot find new threads: generic error When I try to debug my C++ application using gdb, I get the following error:
[Thread debugging using libthread_db enabled]
Cannot find new threads: generic error
If I try to quit gdb, I get A debugging session is active. Inferior 1 [process 17785] will be killed.
I am not using any thread library myself.
I tried the solutions suggested in gdb: Cannot find new threads: generic error but did not help.
My OS: Ubuntu 10.04
$ gcc -v
(Ubuntu 4.4.3-4ubuntu5)
$ uname -a
Linux rskDesktop 2.6.32-33-generic #72-Ubuntu SMP Fri Jul 29 21:07:13 UTC 2011 x86_64 GNU/Linux
Any suggestions?
A:
I am not using any thread library myself
Take a look at this answer: reverse-step multithread error which should apply in your situation: force GDB not to activate thread debugging if you don't want it to be aware of the threads.
(the EDIT applies as well, but maybe it's one of the libraries you use which requires the libpthread.so)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to remove auto suggest functionality on Textbox I have one text box and i want load 2 auto suggest basis on radio button option
Means if user select option button 1 then auto suggest should load Product employee table.if User select option button 2 then auto suggest should load Custom Product table.
I am using jquery auto suggest
How could i achieve this kind of functionality
Example for
when i select radio button SetAutoSuggest Method Will be called
function SetAutoSuggest(ProductType) {
if (ProductType == "PRODUCT") {
$("#PantryFooodItemName").autocomplete('<%= Url.Action("GetAutosuggestProductlistForMeal", "Autosuggest") %>',
{
minChars: 2,
width: 300,
multiple: false,
matchContains: true,
mustMatch:true,
formatItem: formatItem,
formatResult: formatResult
}
);
}
if (ProductType == "CUSTOMPRODUCT") {
$("#PantryFooodItemName").autocomplete('<%= Url.Action("GetCustomProduct", "Autosuggest") %>',
{
minChars: 2,
width: 300,
multiple: false,
matchContains: true,
mustMatch: true,
formatItem: formatItem,
formatResult: formatResult
}
);
}
}
A: Assign click events to the checkboxes and change your URL based on which one is checked.
Alternatively, you can use a callback function on the autocomplete source which would verify which checkbox is checked and pull the proper source url.
The biggest thing you'll run into using the callback function is it requires a very strict format:
source: function(request, response)
{}
Response should be in this format:
[{"id":25,"label":"mylabel","value":"myval"},{"id":26,"label":"mylabel26","value":"myval26"}]
Wouldn't it be better to use a radio button for what you're trying to do instead?
It sounds like a situation where you're trying to do an either/or and not a multi-option (checkboxes).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problems appending audio after AudioFileOpenURL I'm having a problem playing back audio data after appending extra recording to it. Here's the general sequence of events, which don't return any errors:
AudioQueueNewInput // Start audio queue
AudioFileCreateWithURL // Create audio file
AudioFileSetProperty // Set magic cookie
AudioQueueAllocateBuffer // Allocate buffers
AudioQueueEnqueueBuffer // Prime buffer
AudioQueueStart // Start the audio queue
// Record some audio in the audio queue callback...
AudioQueueWritePackets
AudioQueueEnqueueBuffer
AudioQueueStop // Stop the queue
AudioQueueFlush // Flush remaining buffers in the queue
AudioFileSetProperty // Set magic cookie again (needed for some formats?)
AudioQueueDispose // Dispose queue
AudioFileClose // Close the file
I can start and stop the queue to append recording and it works great. The audio appends perfectly and I can play back as I expect. The problem comes when I re-open the file, and try to append:
AudioQueueNewInput // Start audio queue
AudioFileOpenURL // Re-open audio file
AudioFileGetProperty // Get packet count and resume recording at last packet
AudioFileOptimize // "Optimize" the file for appending
AudioFileSetProperty // Set magic cookie
AudioQueueAllocateBuffer // Allocate buffers
AudioQueueEnqueueBuffer // Prime buffer
AudioQueueStart // Start the audio queue
// Record some audio in the audio queue callback...
AudioQueueWritePackets
AudioQueueEnqueueBuffer
AudioQueueStop // Stop the queue
AudioQueueFlush // Flush remaining buffers in the queue
I take care to resume recording from the last packet of audio, and indeed, data is being appended to the file because I can see the file size grow. However, when I play back the file, I do not hear the appended audio. It plays back the original audio, but stops before I expect to hear the additional audio.
I've tried different combinations moving around AudioFileOptimize and resetting the magic cookie to no avail.
The audio format I'm using is as follows:
static const AudioStreamBasicDescription kMyAudioFormat = {
.mFormatID = kAudioFormatAppleIMA4,
.mSampleRate = 44100.0,
.mChannelsPerFrame = 2,
.mBitsPerChannel = 0,
.mBytesPerPacket = 68,
.mBytesPerFrame = 0,
.mFramesPerPacket = 64,
.mFormatFlags = 0
};
What is going on here? Why won't the appended audio play back after I re-open the AudioFileID?
A: Needed to call AudioFileClose. For more info see: http://lists.apple.com/archives/Coreaudio-api/2011/Oct/msg00014.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using Cofoja with Wicket (or even with just Maven) I am trying my darnedest to get Google Cofoja to run in my Apache Wicket application which uses Maven2 as seems to be standard.
The project was initially generated using Leg Up with the Archetype "Wicket 1.4.12, Guice 2.0, WarpPersist 2.0 (snapshot), Hibernate 3.5.6" selected.
What I've tried most recently (and seems to be the closest to working) is building with maven (which i've managed to make build the contract classes), and then attempting to run the project using ant to get the contract checks to happen. The most current problem is I am not sure what to make my main class. I've tried making it the class that runs the jetty server, but I get a class not found exception.
J:\adminconsole>ant run
Buildfile: J:\adminconsole\build.xml
run:
[java] java.lang.NoClassDefFoundError: com/mycompany/myproject/adminconsole/Start
[java] Caused by: java.lang.ClassNotFoundException: com.mycompany.myproject.adminconsole.Start
[java] at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
[java] at java.security.AccessController.doPrivileged(Native Method)
[java] at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
[java] at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
[java] at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
[java] at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
[java] Could not find the main class: com.mycompany.myproject.adminconsole.Start. Program will exit.
[java] Exception in thread "main"
[java] Java Result: 1
BUILD SUCCESSFUL
Total time: 2 seconds
As well, even if I did get this solution working, this is far from the ideal solution of having the contract checks happen as part of the maven build.
Now, what I have currently:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.myproject</groupId>
<artifactId>adminconsole</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<properties>
<jdk.version>1.5</jdk.version>
<slf4j.version>1.5.11</slf4j.version>
<wicket.version>1.4.12</wicket.version>
<jetty.version>6.1.25</jetty.version>
<cofoja.version>1.0</cofoja.version>
<asm.version>3.3.1</asm.version>
</properties>
<name>Admin Console New</name>
<!--
<repositories>
<repository>
<id>jboss</id>
<name>JBoss Repository</name>
<url>https://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
</repositories>
-->
<build>
<finalName>fsrpadmin</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/java</directory>
<includes>
<include>**</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</testResource>
<testResource>
<directory>src/test/resources</directory>
<includes>
<include>**</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</testResource>
</testResources>
<plugins>
<plugin>
<inherited>true</inherited>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addClasspath>true</addClasspath>
<mainClass>com.mycompany.myproject.adminconsole.Start</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>${jetty.version}</version>
<configuration>
<scanIntervalSeconds>5</scanIntervalSeconds>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>2.5</version>
<configuration>
<targetJdk>${jdk.version}</targetJdk>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<configuration>
<xmlOutput>true</xmlOutput>
<effort>Max</effort>
<threshold>Low</threshold>
</configuration>
<version>2.3.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8</version>
</plugin>
<!-- Run annotation processors on src/main/java sources -->
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<executions>
<execution>
<id>process</id>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<outputDirectory>target\classes</outputDirectory>
<processors>
<processor>com.google.java.contract.core.apt.AnnotationProcessor</processor>
</processors>
</configuration>
</execution>
</executions>
</plugin>
<!-- Run annotation processors on src/test/java sources -->
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<executions>
<execution>
<id>process-test</id>
<goals>
<goal>process-test</goal>
</goals>
<phase>generate-test-sources</phase>
<configuration>
<outputDirectory>target\classes</outputDirectory>
<processors>
<processor>com.google.java.contract.core.apt.AnnotationProcessor</processor>
</processors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- WICKET DEPENDENCIES -->
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-guice</artifactId>
<version>${wicket.version}</version>
</dependency>
<!-- LOGGING DEPENDENCIES - LOG4J -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>1.8.0.10</version>
<scope>runtime</scope>
</dependency>
<!-- You will need to install this yourself from http://warp-persist.googlecode.com/svn/trunk/warp-persist/dist/ -->
<dependency>
<groupId>com.wideplay.warp</groupId>
<artifactId>warp-persist</artifactId>
<version>2.0-20090214</version>
</dependency>
<!-- Cofojo - Contracts for Java LOCALLY INSTALLED from http://code.google.com/p/cofoja/downloads/list -->
<dependency>
<groupId>com.google</groupId>
<artifactId>cofoja</artifactId>
<version>${cofoja.version}</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm-all</artifactId>
<version>${asm.version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.5.6-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.8.0.GA</version>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
<!-- Other -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="adminconsole-run" default="package" basedir=".">
<!-- ====================================================================== -->
<!-- Build environment properties -->
<!-- ====================================================================== -->
<property file="${user.home}/.m2/maven.properties"/>
<property file="maven-build.properties"/>
<!-- ====================================================================== -->
<!-- Run Contracts target -->
<!-- ====================================================================== -->
<target name="run">
<java jar="${maven.build.dir}/${maven.build.finalName}.war" fork="true">
<jvmarg value="-javaagent:lib/cofoja/cofoja-1.0-r138.jar"/>
</java>
</target>
</project>
maven-build.properties
maven.build.finalName=fsrpadmin
maven.build.dir=target
com/mycompany/myproject/adminconsole/Start.java
package com.marsh.fsrp.adminconsole;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.webapp.WebAppContext;
public class Start {
public static void main(String[] args) throws Exception {
Server server = new Server();
SocketConnector connector = new SocketConnector();
connector.setPort(8080);
server.setConnectors(new Connector[] { connector });
WebAppContext bb = new WebAppContext();
bb.setServer(server);
bb.setContextPath("/");
bb.setWar("src/main/webapp");
// START JMX SERVER
// MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
// MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
// server.getContainer().addEventListener(mBeanContainer);
// mBeanContainer.start();
server.addHandler(bb);
try {
System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
server.start();
while (System.in.available() == 0) {
Thread.sleep(5000);
}
server.stop();
server.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(100);
}
}
}
If you know how to fix my current ant problem, or even better, have an idea of how to scrap the ant-hack all together, that would be super exciting (:
Update 1
Removed -'s from code as that is bad (thanks @Martijn Dashorst). Sadly, this didn't fix the problem.
A: Don't use a- in your artifact and group IDs. They are invalid Java identifier characters. The script uses the groupId and artifactId to generate the package name in your project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Left join on multiple column performance? Assume that I have 2 tables :
table1 :(20.000 records)
id code1 code2 something status
table2: (7.500 records)
id code1 code2 name
All I want is list all records in table1 with the "name" in table2 by using this QUERY:
SELECT DISTINCT `tb1`.*, `tb2`.`name` FROM `table1` AS `tb1`
LEFT JOIN `table2` AS `tb2`
ON (tb1.code1 = tb2.code1 AND tb1.code2 = tb2.code2)
WHERE (tb1.status = 1)
But it took me too long to retreive the data (after 5 minutes I still cant see the result).
What is the best way to do this?
Thanks in advance..
A: Please try adding an index on table1 using columns(code1,code2,status). If you don't have too many columns in table1, you can add them to the index too. In MS SQL, we have "include columns" that we can add to an index. Maybe mysql has something similar.
Add an index on table2 using columns(code1,code2, name).
If you are concerned about index size then just keep (code1, code2, status) for index1 and (code1, code2) for index2.
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: iOS: Core location turn off after update? Obviously to save battery we need to use CoreLocation as quickly as possible and shut it off when not needed. I have a GPS app that tracks a users location, so I use almost all good location updates. Do I still need to be turing off core location at some sort of interval?
Looking in Apple's "LocateMe" app they seem to turn it off when they find a location, but this is confusing to me, when does it get turned back on? In my case it doesn't seem to make sense to turn it off for a split second then back on.
Thoughts?
From "LocateMe":
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
// store all of the measurements, just so we can see what kind of data we might receive
[locationMeasurements addObject:newLocation];
// test the age of the location measurement to determine if the measurement is cached
// in most cases you will not want to rely on cached measurements
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5.0) return;
// test that the horizontal accuracy does not indicate an invalid measurement
if (newLocation.horizontalAccuracy < 0) return;
// test the measurement to see if it is more accurate than the previous measurement
if (bestEffortAtLocation == nil || bestEffortAtLocation.horizontalAccuracy > newLocation.horizontalAccuracy) {
// store the location as the "best effort"
self.bestEffortAtLocation = newLocation;
// test the measurement to see if it meets the desired accuracy
//
// IMPORTANT!!! kCLLocationAccuracyBest should not be used for comparison with location coordinate or altitidue
// accuracy because it is a negative value. Instead, compare against some predetermined "real" measure of
// acceptable accuracy, or depend on the timeout to stop updating. This sample depends on the timeout.
//
if (newLocation.horizontalAccuracy <= locationManager.desiredAccuracy) {
// we have a measurement that meets our requirements, so we can stop updating the location
//
// IMPORTANT!!! Minimize power usage by stopping the location manager as soon as possible.
//
[self stopUpdatingLocation:NSLocalizedString(@"Acquired Location", @"Acquired Location")];
// we can also cancel our previous performSelector:withObject:afterDelay: - it's no longer necessary
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(stopUpdatingLocation:) object:nil];
}
}
// update the display with the new location data
[self.tableView reloadData];
}
A: It seems to me that your dual requirements of wanting location updates every meter or so vs. wanting to save battery and so wanting to use CoreLocation as quickly as possible and then shut it off "when not needed" are mutually incompatible. If you need location updates every meter or so, there is no time when the app will be in the foreground when you will not need location services on. Depending on the nature of your app, you may well want to turn location services off when you go into the background or the screen is locked...
The one other exception might be that you'd like to turn off location services if the user is standing still for a while. Apple provide the significant change location service but that isn't going to be suitable for your needs it would seem, if you want meter-by-meter updates... it just doesn't have that level of resolution.
So there may be no solution that meets both your desires?
A: it depends on how often you need location. If you need it all the time while your app is working its a better a idea to turn ON location updates in applicationWillBecomeActive and turn OFF the updates in applicationWillResignActive
A: You can configure the accuracy and distance filter
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
locationManager.distanceFilter = 10;
it depends on accuracy and update frequency you need
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C++ equivalent of .ToString() There must be an easy way to do this...
// C# code
for (int i = 0; i < 20; i++)
doSomething(i.ToString() + "_file.bmp");
I'm trying to do this in C++, but it turns out that the simplest things are the hardest to do in that language. Mostly because there's a catch: I'm restricted to a library that only takes char*'s as the parameter for the function this will eventually end up in, so I'm pretty much stuck playing with char arrays. This is what I have so far:
char* path[12];
for(int i = 0; i < 20; i++)
{
sprintf(path[0],"%i_Card.bmp",i);
cards[i] = new Card(i,path[0]);
}
The problem is, this approach ends me up with one big, long, useless string.
I must disclose that this is for a school assignment, but answering this question will not decide my grade, it will just make one aspect of the app a little easier.
A: The C++03 equivalent of ToString is
std::stringstream stream;
stream << i;
std::string i_as_string = stream.str();
Note that you can also accomplish that with no intermediate variables, by doing ( std::stringstream() << i ).str().
In C++11 there is both std::lexical_cast< std::string >( i ) which does the above for you (also available from Boost), and std::to_string( i ).
A: Try this
#include <stdio.h>
#include <stdlib.h>
itoa(i)
atoi
Or you can go this route:
#include <sstream>
int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();
A: I see several bugs in your code.
1) You declare "path" to be an array of 12 character pointers, but no memory allocated for the any of the array items. The sprintf statement is guaranteed to copy into garbage memeory. I'm surprised this doesn't crash your program right away.
2) And even if there was memory allocated for the path array, your sprintf statement always copies to path[0] - overwriting what was already there.
I suspect you are confusing char arrays, strings, and arrays of strings in C/C++. Perhaps the code below will help. I'm assuming that your "Card" class doesn't save a copy of the string passed as the second parameter to a member variable (at least not without copying it). Otherwise, it will be pointing to stack memory - which could be buggy if your Card instance outlives the function in which it was created in.
const size_t MAX_INTEGER_LENGTH = sizeof(int) * 4; // 4x the sizeof int will suffice no matter what the sizeof(int) is
char szPostfix[] = "_Card.bmp";
for(int i = 0; i < 20; i++)
{
char path[MAX_INTEGER_LENGTH + sizeof(szPostfix) + 1]; //+1 for null terminator
sprintf(path,"%d%s",i, szPostfix);
cards[i] = new Card(i,path);
}
A: You can use std::string and convert it to to the c-string using std::string::c_str(). However, it returns a c string of const char*. const_cast can be use to disqualify the const associated with it.
#include <iostream>
#include <string>
using namespace std;
void foo(char* str){
cout << str << endl;
}
int main(){
string str = "Hello World";
foo(const_cast<char*>(str.c_str()));
return 0;
}
Output: Hello World
Demo
A: There's no general way to convert an object to a string in C++. You have to define your conversion functions yourself. For basic types you can convert them to strings using stringstream.
#include <sstream>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
stringstream ss;
ss << 1;
cout << ss.str();
}
There's more info about stringstream here
A: From the code it looks like it is a file name and the Card class should take the path as a const char*. So I think the following would be the c++ way of doing it.
for(int i = 0; i < 20; i++)
{
std::stringstream out;
out << i << "_Card.bmp";
cards[i] = new Card(i,out.str().c_str());
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Embed two-dimensional arrays as part of higher-dimensional arrays in R My questions concerns how to cleanly deal with a bunch of data I have.
I'm running an experiment with 4 conditions. There will be 20 participants in each condition, and when each completes the experiment, I'm left with a text file that has 600 rows, and 7 columns. The 600 rows correspond to 600 trials that each person completes. The 7 columns refer to variables that are measured on each trial.
So my data for each person look something like this (except there are 600 rows):
394 b a 0 9773 1 1436
114 a b 0 3595 1 1246
432 b a 0 1272 1 1061
209 a a 1 3514 1 120
In order to run my analyses, it would be really helpful if I could get all these text files into the one object called "data" that would have the following dimensions:
*
*Experimental condition (1-4)
*Participant number (1-20)
*Trial number (1-600)
*Variable (1-7)
My files have names like "ii-wm-long_1316994934_7_1.txt", where the "ii-wm-long" part identifies their experimental condition, and the last number (1 here) identifies their participant number.
At the moment my code looks like this:
#Get the names of the text files in the results folder
files <- list.files()
#Conditions - which ones correspond to which numbers
condition.def <- c("ii-wm-long","ii-wm-short","wm-ii-long","wm-ii-short")
#1 = ii-wm-long
#2 = ii-wm-short
#3 = wm-ii-long
#4 = wm-ii-short
#This is where everything will be stored
data <- array(NA,dim=c(4,20,600,7),dimnames=c("condition","participantNumber","trialNumber","experimentalvariable"))
#Loop for each participant's file
for (n in 1:length(files)){
#What condition is the person in?
condition <- unlist(strsplit(files[n],"\\_"))[1]
condition <- grep(condition,condition.def)
#What is their participant number (of the people in that condition)?
ppt <- as.integer(unlist(strsplit(unlist(strsplit(files[n],"\\_")),"\\."))[4])
#Read the text file into the array
data[condition,ppt,,] <- read.table(files[n],sep="\t",header=F,nrows=600,col.names=c("stimulus","category","category.choice","category.correct","category.time","memory.present","memory.time"))
}
I receive an error:
Error in data[condition, ppt, , ] <- read.table(files[n], sep = "\t", :
incorrect number of subscripts
I've read up on cbind and abind, and can't seem to figure out how they would allow me to read the data in one-by-one.
What is the correct way to take a 2D array, and turn it into the last 2 dimensions of a 4D array?
A: read.table returns a data.frame, so at the very least you would need to wrap it in as.matrix:
data[condition,ppt,,] <-
as.matrix(read.table(files[n], sep="\t", header=FALSE, nrows=600,
col.names=c("stimulus", "category", "category.choice",
"category.correct", "category.time",
"memory.present", "memory.time")))
But, this is pretty fragile since you are going directly from I/O into an array slice, and you should put in some sanity checks so you know the input is as expected, the file exists, and so on.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Can I access azure applications from any device? I have read that to use applications present on cloud, the only requirement is a web browser and an Internet connection.
Does this mean that I can access applications on azure cloud from my low end phone that has a low speed Internet connection and an Opera Mini browser?
Are there any minimum hardware or software requirements to be able to access these applications?
Thank you very much.
A: Azure can be used to write web applications and services that can be accessed from any device with an internet connection.
On its most basic level Azure can be used like a normal web hosting service to provide web content for mobile devices.
The minimum hardware/software requirements for the device will be dependent on the complexity of the content provided by the web service/site that is hosted on Azure (this is no different to a web service/site hosted on a traditional platform)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Obtaining Coordinates from "Share this place" in Google Maps When viewing the details of any location in Google Maps, there's an option for "Share this place". I have successfully added myself to the list of receivers by adding this intent-filter to my application in the manifest:
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
The extras passed along with this bundle are Intent.EXTRA_SUBJECT and Intent.EXTRA_TEXT. I retrieved these extras in my activity using:
Bundle extras = getIntent().getExtras();
Intent.EXTRA_SUBJECT contains a string with the title of the location.
Intent.EXTRA_TEXT contains a string with a detailed address of the location and a mobile maps URL.
Is it at all possible to retrieve the GPS co-ordinates (latitude and longitude) of the location from the "Share this place" action?
A: You can use geocoder to obtain the location from the address:
How can I find the latitude and longitude from address?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Getting GPS data of a remote mobile I'm developing a mobile app, somekind of a social networking thing. There I'm planning to intergrate a Location searching facilty to users. Can anyone tell me is it possible to track the gps data of a remote mobile programatically(in j2ME specialy)? I'm preffer to doing this data transfer through GSM or HSDPA. I found import javax.microedition.location.*; to get location based data. What I want toknow is, is it possible to get those data of another remote mobile?
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to delete a session value from table when we close a browser I am a beginner in PHP. I got a problem related to session, I created a one table with username, password fields and one temp_session table with sessionID.
When I login with given username a session is generated and session will store in temp_session table and when i logout by pressing logout button session value is deleted from tem_session table.
Now, I have question that what would I do when I close browser, in this case session get expired but session value is still in temp_session table I want to remove that value after 2 minute from temp_session after browser close. what logic I will use for this.
A: Here is a suggestion instead of invalidating the sessionId after two minutes why dont you reset the value when the user logs back into your application. I am not a PHP expert but I am guessing you should be able to use session_start handler for the same.
If you still wanna go ahead and do this then you need to setup a timestamp in the users table that will be updated everytime the server receives a request and then you probably would want to have a schedule running that updates your table based on the timestamp.. Do you see the unnecessary overhead you are introducing.
A: you can't clear database value on event of closing browser but you need to implement logical solution.
you need to add time stamp in session table as last activity time, set last activity = current time if user's last activity time and current time difference is not more then 2 minute else remove record from database.
Let's discuss cases.
when you login you will add session in DB.
if user is idle for more than 2 min than we will delete session from DB.
if user id not idle more then 2 min than last activity will set as current time.
A: In java we can handle it through HTTPSessionListner and adding an entry in web.xml file . This will be called when the session is not active and session.invalidate() method we can call post after operations we want to do.
So, You can try implementing same in PHP or findout something related to that :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: assert fails when it should not, in Smalltalk Unit testcase I'm stumped. Here is my testcase.
theTestArray := #(1.2 3 5.1 7).
self assert: theTestArray squareOfAllElements = #(1.44 9 26.01 49).
The assert should not fail. On calculating the square of each element is correct. So I did "step into test", shows that the result of the method squareOfAllElements and #(1.44 9 26.01 49) are both the same but assert evaluates to false. why? What am I doing wrong here? Any help is appreciated.
A: You are dealing with floating point numbers here. Floating point numbers are inexact by definition and you should never compare them using #=.
For details check Section 1.1 of the draft chapter on floating point numbers of Pharo by Example: http://stephane.ducasse.free.fr/Web/Draft/Float.pdf
A: However, the comparison equality message, #=, is sent to the collection presumably returned by #squareOfAllElements.
You can rewrite your test statement as:
theTestArray := #(1.2 3 5.1 7).
theSquaredArray := theTestArray collect: [:each | each squared].
theTestArray with: theSquaredArray do: [:a :b | self assert: (a equals: b) ].
That will test the same as the previous one, but will run one #assert: per element.
Other option would be to implement a variation of #hasEqualElements: in terms of Float>>#equal: instead of #=.
A: As said in other answers, Float are inexact. Also remember that Visualworks Float default to single precision (about 7 decimal places), if you posfix your float number with letter d, like 5.1d you'll get double precision (about 15 decimal places), less inexact, but still inexact.
One additional source of confusion is that two different Float can print with the same approximate decimal representation in Visualworks.
5.1 squared printString
-> '26.01'
but
5.1 squared = 26.01
-> false
Note that recent Squeak or Pharo prints just enough decimals to distinguish different Float (and reinterpret them unchanged)
5.1 squared
->26.009999999999998
Alternatively, you can use the so called FixedPoint (in VisualWorks, or ScaledDecimals in other flavours) to perform exact operations:
theTestArray := #(1.2s 3 5.1s 7).
self assert: theTestArray squareOfAllElements = #(1.44s 9 26.01s 49).
Also beware of this other trap: a FixedPoint (ScaledDecimals) prints only as many decimals after the fraction point as it was told to, but internally it can hold more (infinitely many).
5.1s1 squared printString
-> '26.0s1'
but
5.1s1 squared = 26.01s2
-> true
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to hint types when compiling with llvm-gcc? In some C code, I'm defining a simple static array as a function argument, say:
void foo(float color[3]);
When I compile it with llvm-gcc, it produces the following LLVM assembly language output:
define void @foo(float* %n1) nounwind ssp {
Is there any way I can hint to the compiler that I'd like it to generate code using an LLVM array [3 x float] or vector <3 x float> on the stack, instead of a pointer?
A: void foo(float color[3]); is defined by the C standard to be equivalent to void foo(float *color);. Maybe you want void foo(float (*color)[3]), or struct vec { float elems[3]; }; void foo(struct vec color);?
A: Generally speaking, you cannot. It's C standard / platform ABI which defines the layout of your types, etc.
If you want such fine control over IR emission you'd need to do this by hands (or modify clang, etc.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to replace exec () through system command in php? My Coding is so far:
How to replace exec() through system command in php?
if($str!="success")
{
$cmd = "rm -rf /portal/data/config/certificate/tmp/";
$error_text="Command : ".$cmd;
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
$output = exec($cmd,$array1,$error_code);
$error_text="Error code : ".$error_code;
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
seterror('0:|: :|: Could not apply certificate.');
$error_text="Could not apply certificate";
AddLog("sslconfig.php",$error_text,ERR_INFO);
header("Location: ssl.php");
exit;
}
if($certName==$cert_auth)
{
//copy the applied certificate to fireballbundle.crt
//$output = copysslfb("/portal/data/config/certificate/".$newfile.".crt");
$error_text="Selfsigned Certicate";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
$output="success";
}
else
{
$error_text="Not Selfsigned Certicate";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
$output="success";
}
if($output!="success")
{
$cmd = "rm -rf /portal/data/config/certificate/tmp/";
$error_text="Command : ".$cmd;
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
$output = exec($cmd,$array1,$error_code);
$error_text="Error code : ".$error_code;
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
$error_text="Could not add certificate to fireballbundle.crt : ".$output;
AddLog("sslconfig.php",$error_text,ERR_ERROR);
seterror('0:|: :|: Error in applying certificate.');
header("Location: ssl.php");
exit;
}
Now I want to replace exec command with system command ?
I am using three times exec() here as shown as above code now i want to replace with system () command in php
exec("hostname",$retval);
$output = exec($cmd,$array1,$error_code);
exec($cmd,$array1,$error_code);
A: To remove a single file, you should use unlink and to remove a directory you should use rmdir. In the comments on those pages, you will find many different ways to emulate rm -rf through these functions.
You should avoid using system or exec as much as is possible. Always look on php.net and google to see if you can find a way to do whatever you're trying to do with a built-in function or library. You have no need to use these facilities here.
What hostname returns you should probably use $_SERVER['SERVER_NAME'] for instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why do some floating point numbers appear with a trailing 0 Does anyone know why the numbers 0.001 to 0.009 are rendered to a String with a trailing 0 but other numbers do not. e.g. numbers 0.01 to 0.09 do not.
System.out.println(Locale.getDefault());
for (int i = 0; i <= 20; i++)
System.out.println(i / 1e3);
prints
en_GB
0.0
0.0010
0.0020
0.0030
0.0040
0.0050
0.0060
0.0070
0.0080
0.0090
0.01
0.011
0.012
0.013
0.014
0.015
0.016
0.017
0.018
0.019
0.02
EDIT The code for DecimalFormat doesn't appear to be locale dependant. If I run
for (Locale l : Locale.getAvailableLocales()) {
Locale.setDefault(l);
System.out.println(l + " " + 1 / 1e3);
}
on Java 6 update 26 on Ubuntu 11.04 I get
ja_JP 0.0010
es_PE 0.0010
en 0.0010
... many locales with the same result ...
sv_SE 0.0010
da_DK 0.0010
es_HN 0.0010
on Java 7 on same system I get
ms_MY 0.001
ar_QA 0.001
is_IS 0.001
... many locales with the same result ...
el_CY 0.001
hu 0.001
fr_FR 0.001
A: For those interested, here is a diff between the FloatingDecimal class responsible for creating the string representation of the double. As you can see from the diff, the patch fixes the special case encountered when the exponent is -3 in the dtoa() method.
A: This was identified as a bug in Java 1.3 - Java 6: http://bugs.java.com/view_bug.do?bug_id=4428022
EDIT: As to why this happens, here's the fix referred to in the bug report that was ported from OpenJDK 6: http://hg.openjdk.java.net/jdk6/jdk6/jdk/rev/8159687b6316
Turns out it's an off-by-one error. (The fix changes <= to <).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: Grid Panel Scrollbars in Extjs 4 not working var gusersPanel = Ext.create('Ext.grid.Panel', {
flex:1,
columns: [{
header: 'User Login',
dataIndex: 'user_login',
width:150
},{
header: 'User Name',
dataIndex: 'user_nicename',
width:150
},{
header:'Privledge',
dataIndex:'admin',
width:150
}],
autoScroll: true,
layout:'fit',
selModel: gusersSel,
store: gusersStore
})
Hi I am using above code for the grid Panel in Extjs4.0.2a When I populate data dynamically in the store the scrollbars are not working .
I have also tried using doLayout() for grid Panel but dosent work too .
The grid Panel is in a Window .
Anything that can solve this problem ?
Actually it works for some time but dosen't work all the time .
A: I did gusersPanel.determineScrollbars() when i am adding and removing data from store and it is working fine .
A: The problem with this is the scroll listener is attached to the div element on the afterrender event, but then if the scrollbar is not needed after a layout operation the div element is removed from the dom. Then, when it's needed again it's added back, but only if enough time has passed the garbage collection makes extjs recreate the div node and this time it's added to the dom without attaching the scroll listener again. The following code solves the problem:
Ext.override(Ext.grid.Scroller, {
onAdded: function() {
this.callParent(arguments);
var me = this;
if (me.scrollEl) {
me.mun(me.scrollEl, 'scroll', me.onElScroll, me);
me.mon(me.scrollEl, 'scroll', me.onElScroll, me);
}
}
});
A: I've had the same problem. They use custom scrollbar and it's pretty buggy (especialy in chrome). If you are not going to use infinite scroll the possible solution could be to remove custom scrollbar and use native one. To do that just add the following to the grid's config:
var gusersPanel = Ext.create('Ext.grid.Panel', {
scroll : false,
viewConfig : {
style : { overflow: 'auto', overflowX: 'hidden' }
},
// ...
});
A: You written code to layout: 'fit'. It did not work autoScroll.
Change the code to some height and remove layout: 'fit' code.
Like this.
var gusersPanel = Ext.create('Ext.grid.Panel', {
flex:1,
columns: [{
...........
}],
autoScroll: true,
//layout:'fit',
height: 130,
selModel: gusersSel,
store: gusersStore
It is help you. Cheers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Display popup for users I want to implement a popup as shown on Google maps, to rate restaurants (after search). The user hovers over the overall rating, and then a popup is shown on which user can rate. I am using jquery. The popup should disappear once focus is lost from the popup. So, basically I want to know how to display such a popup ?
A: jquery tooltip is a good one
Its as simple as:
$("[title]").tooltip();
// or
// $(".trigger").tooltip({ position: "bottom left", opacity: 0.7});
Even customize the html inside the tooltip (from their example page here):
<!-- trigger element. a regular workable link -->
<a id="download_now">Download now</a>
<!-- tooltip element -->
<div class="tooltip">
<img src="http://static.flowplayer.org/img/title/eye.png" alt="Flying screens"
style="float:left;margin:0 15px 20px 0" />
<table style="margin:0">
<tr>
<td class="label">File</td>
<td>flowplayer-3.2.7.zip</td>
</tr>
<tr>
<td class="label">Date</td>
<td>2011-03-03</td>
</tr>
<tr>
<td class="label">Size</td>
<td>112 kB</td>
</tr>
<tr>
<td class="label">OS</td>
<td>all</td>
</tr>
</table>
<a href="/3.2/">What's new in 3.2</a>
</div>
Then:
$("#download_now").tooltip({ effect: 'slide'});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Bug Merge Using Svn How to merge bug occurred in one branch to another ..
Example : There is bug id :1010 (this is fixed using some 2 files) Under branch-5 i want to merge same files(2 files) to branch-3
Can anybody please help out?
A: Well, the process is something like this. Say you are merging some commits made in branch-5 into branch-3. So in branch-3 if you could select Merge from a range of revisions. Then in the URL of the branch where the revisions are present you would select the revisions where you committed the two files, and then merge. There is also a Test-merge option available in TortoiseSVN. The process should be similar in RabbitVCS Svn on Ubuntu. Sorry, never used a command line for SVN, though I think with this knowledge you could look it up on the SVN docs to find the command line equivalent. Hope this helps !
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: django: use QuerySet.values() to return Python types? I've got a custom Field which converts the value to/from a Python type:
class MyField(models.Field):
# …
def to_python(self, value):
# …
return MyType(value)
Is there any way to trick QuerySet.values(…) into running the field-specific conversions on the values it returns?
For example, I'd like something like this:
>>> MyModel.objects.all().values("my_field")
[{"my_field": MyType(…)}]
Instead of the current behaviour:
>>> MyModel.objects.all().values("my_field")
[{"my_field": "raw_database_value"}]
Obviously I can manually convert the result… But that's kind of lame =\
A: No, this isn't possible. You can see the related ticket at https://code.djangoproject.com/ticket/9619
There you will see there is discussion whether values() should actually run any field-specific conversions.
As the ticket is marked "Design Decision Needed", you'd need to bring this up by posting to the django-developers mailing list, or raising it with someone on IRC (Freenode #django-dev)
In the meantime, you will have to manually convert the raw database value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to disable PhoneGap APIs/functionality? Is there a recommended way to remove access to unneeded PhoneGap APIs?
For example our app does not need to access the contact database.
With normal web pages, an XSS vulnerability is sandboxed to only affect one site (the browser prevents any contagion to other sites). With a PhoneGap application, by default, an XSS vulnerability can access the contacts list or any other part of the PhoneGap API.
I want to avoid the Skype situation where an XSS vunerability in Skype allowed an attacker to copy the address books of their users: http://www.macnn.com/articles/11/09/20/users.address.books.could.be.copied/
A: In your app, under PhoneGap.plist/Plugins, remove any rows for plugins that are not needed - this will remove access from JavaScript.
A: PhoneGap is Open Source. You could make your own copies of the PhoneGap.js files with those functions disabled (put return false; as the first line of the function or something).
On Android you can do it with the permissions in the AndroidManifest.xml file, but as far as I know, there is not such feature for iOS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JBoss deployment results in java.lang.UnsupportedClassVersionError: Bad version number in .class file When I am trying to hit my application in local machine I am getting a Http 404 error. When I see the console I am getting the below stack trace. Also the ear file is getting deployed in deployment folder but I am still not able to understand the problem.
Could not create deployment: file:/C:/Tools/jboss-4.2.2.GA/server/core-internal-dev/tmp/deploy/tmp9021jms-logging.jar-contents/jboss-service.xml
org.jboss.deployment.DeploymentException: Unexpected error during load of: device.common.log4j.jmx.JMSAppenderInitializer,
msg=Bad version number in .class file; - nested throwable: (java.lang.ClassNotFoundException: Unexpected error during load of: device.common.log4j.jmx.JMSAppenderInitializer, msg=Bad version number in .class file)
at org.jboss.system.ServiceConfigurator.install(ServiceConfigurator.java:196)
at org.jboss.system.ServiceController.install(ServiceController.java:226)
at sun.reflect.GeneratedMethodAccessor21.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
at $Proxy4.install(Unknown Source)
at org.jboss.deployment.SARDeployer.create(SARDeployer.java:249)
at org.jboss.deployment.MainDeployer.create(MainDeployer.java:969)
at org.jboss.deployment.MainDeployer.create(MainDeployer.java:959)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:818)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:782)
at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
at $Proxy9.deploy(Unknown Source)
at org.jboss.deployment.scanner.URLDeploymentScanner.deploy(URLDeploymentScanner.java:421)
at org.jboss.deployment.scanner.URLDeploymentScanner.scan(URLDeploymentScanner.java:634)
at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.doScan(AbstractDeploymentScanner.java:263)
at org.jboss.deployment.scanner.AbstractDeploymentScanner.startService(AbstractDeploymentScanner.java:336)
at org.jboss.system.ServiceMBeanSupport.jbossInternalStart(ServiceMBeanSupport.java:289)
at org.jboss.system.ServiceMBeanSupport.jbossInternalLifecycle(ServiceMBeanSupport.java:245)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.system.ServiceController$ServiceProxy.invoke(ServiceController.java:978)
at $Proxy0.start(Unknown Source)
at org.jboss.system.ServiceController.start(ServiceController.java:417)
at sun.reflect.GeneratedMethodAccessor10.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
at $Proxy4.start(Unknown Source)
at org.jboss.deployment.SARDeployer.start(SARDeployer.java:302)
at org.jboss.deployment.MainDeployer.start(MainDeployer.java:1025)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:819)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:782)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:766)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
at $Proxy5.deploy(Unknown Source)
at org.jboss.system.server.ServerImpl.doStart(ServerImpl.java:482)
at org.jboss.system.server.ServerImpl.start(ServerImpl.java:362)
at org.jboss.Main.boot(Main.java:200)
at org.jboss.Main$1.run(Main.java:508)
at java.lang.Thread.run(Thread.java:595)
Caused by: java.lang.ClassNotFoundException: Unexpected error during load of: device.common.log4j.jmx.JMSAppenderInitializer,
msg=Bad version number in .class file
at org.jboss.mx.loading.RepositoryClassLoader.loadClassImpl(RepositoryClassLoader.java:560)
at org.jboss.mx.loading.RepositoryClassLoader.loadClass(RepositoryClassLoader.java:415)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at org.jboss.mx.server.MBeanServerImpl.instantiate(MBeanServerImpl.java:1204)
at org.jboss.mx.server.MBeanServerImpl.instantiate(MBeanServerImpl.java:286)
at org.jboss.system.ServiceCreator.install(ServiceCreator.java:193)
at org.jboss.system.ServiceConfigurator.internalInstall(ServiceConfigurator.java:451)
at org.jboss.system.ServiceConfigurator.install(ServiceConfigurator.java:171)
... 81 more
Caused by: java.lang.UnsupportedClassVersionError: Bad version number in .class file
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at org.jboss.mx.loading.RepositoryClassLoader.findClassLocally(RepositoryClassLoader.java:682)
at org.jboss.mx.loading.RepositoryClassLoader.findClass(RepositoryClassLoader.java:662)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at org.jboss.mx.loading.RepositoryClassLoader.loadClassLocally(RepositoryClassLoader.java:200)
at org.jboss.mx.loading.ClassLoadingTask$ThreadTask.run(ClassLoadingTask.java:131)
at org.jboss.mx.loading.LoadMgr3.nextTask(LoadMgr3.java:399)
at org.jboss.mx.loading.RepositoryClassLoader.loadClassImpl(RepositoryClassLoader.java:527)
... 88 more
21:49:07,247 ERROR [[/nenroll]] Exception starting filter EnrollInterceptingFilter
java.lang.ClassNotFoundException: device.odm.nenrollment.webservlet.EnrollInterceptingFilter
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:249)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:397)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:108)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3722)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4367)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:790)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:770)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:553)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:296)
at org.jboss.mx.server.RawDynamicInvoker.invoke(RawDynamicInvoker.java:164)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.apache.catalina.core.StandardContext.init(StandardContext.java:5312)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:296)
at org.jboss.mx.server.RawDynamicInvoker.invoke(RawDynamicInvoker.java:164)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.web.tomcat.service.TomcatDeployer.performDeployInternal(TomcatDeployer.java:301)
at org.jboss.web.tomcat.service.TomcatDeployer.performDeploy(TomcatDeployer.java:104)
at org.jboss.web.AbstractWebDeployer.start(AbstractWebDeployer.java:375)
at org.jboss.web.WebModule.startModule(WebModule.java:83)
at org.jboss.web.WebModule.startService(WebModule.java:61)
at org.jboss.system.ServiceMBeanSupport.jbossInternalStart(ServiceMBeanSupport.java:289)
at org.jboss.system.ServiceMBeanSupport.jbossInternalLifecycle(ServiceMBeanSupport.java:245)
at sun.reflect.GeneratedMethodAccessor18.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.system.ServiceController$ServiceProxy.invoke(ServiceController.java:978)
at $Proxy0.start(Unknown Source)
at org.jboss.system.ServiceController.start(ServiceController.java:417)
at sun.reflect.GeneratedMethodAccessor10.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
at $Proxy44.start(Unknown Source)
at org.jboss.web.AbstractWebContainer.start(AbstractWebContainer.java:466)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142)
at org.jboss.mx.interceptor.DynamicInterceptor.invoke(DynamicInterceptor.java:97)
at org.jboss.system.InterceptorServiceMBeanSupport.invokeNext(InterceptorServiceMBeanSupport.java:238)
at org.jboss.wsf.container.jboss42.DeployerInterceptor.start(DeployerInterceptor.java:87)
at org.jboss.deployment.SubDeployerInterceptorSupport$XMBeanInterceptor.start(SubDeployerInterceptorSupport.java:188)
at org.jboss.deployment.SubDeployerInterceptor.invoke(SubDeployerInterceptor.java:95)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
at $Proxy45.start(Unknown Source)
at org.jboss.deployment.MainDeployer.start(MainDeployer.java:1025)
at org.jboss.deployment.MainDeployer.start(MainDeployer.java:1015)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:819)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:782)
at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
at $Proxy9.deploy(Unknown Source)
at org.jboss.deployment.scanner.URLDeploymentScanner.deploy(URLDeploymentScanner.java:421)
at org.jboss.deployment.scanner.URLDeploymentScanner.scan(URLDeploymentScanner.java:634)
at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.doScan(AbstractDeploymentScanner.java:263)
at org.jboss.deployment.scanner.AbstractDeploymentScanner.startService(AbstractDeploymentScanner.java:336)
at org.jboss.system.ServiceMBeanSupport.jbossInternalStart(ServiceMBeanSupport.java:289)
at org.jboss.system.ServiceMBeanSupport.jbossInternalLifecycle(ServiceMBeanSupport.java:245)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.system.ServiceController$ServiceProxy.invoke(ServiceController.java:978)
at $Proxy0.start(Unknown Source)
at org.jboss.system.ServiceController.start(ServiceController.java:417)
at sun.reflect.GeneratedMethodAccessor10.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
at $Proxy4.start(Unknown Source)
at org.jboss.deployment.SARDeployer.start(SARDeployer.java:302)
at org.jboss.deployment.MainDeployer.start(MainDeployer.java:1025)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:819)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:782)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:766)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
at $Proxy5.deploy(Unknown Source)
at org.jboss.system.server.ServerImpl.doStart(ServerImpl.java:482)
at org.jboss.system.server.ServerImpl.start(ServerImpl.java:362)
at org.jboss.Main.boot(Main.java:200)
at org.jboss.Main$1.run(Main.java:508)
at java.lang.Thread.run(Thread.java:595)
A: Here's the main root cause:
Caused by: java.lang.UnsupportedClassVersionError: Bad version number in .class file
This can occur when you've a class (or a JAR file) which is compiled/built with a newer version of Java (e.g. Java 1.6) than the one which you're using in your JBoss environment (e.g. Java 1.5).
Here's the follow-up cause:
ClassNotFoundException: Unexpected error during load of: device.common.log4j.jmx.JMSAppenderInitializer
The mentioned class (or the JAR file containing that class) is the main suspect here. I have however never heard of this class and Google also doesn't give any clues other than your own question, so I can't give any hints as to where to look/search. Isn't it your company's own class? Perhaps it's in /WEB-INF/lib of the WAR or /lib of the EAR.
In any way, that class needs to be recompiled with a JDK version which matches the target environment's Java version, or you need to upgrade the target environment to use a newer Java version matching the class' version.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Web Service is not Responding I have a problem that I am calling a webservice which is running on Google Chrome RESTClient AddON Software and gives 200 response but when I called the same in my Android App It is not responding.
I don't know what is the problem for Android. Please suggest me for the right result.
Thanks
Error Stack
09-27 10:41:14.582: INFO/System.out(373): <HTML><TITLE>404 Not Found</TITLE><BODY><H1>404 Not Found</H1><P>Unable to connect to host</BODY></HTML>
09-27 10:41:14.582: WARN/System.err(373): org.json.JSONException: Value <HTML><TITLE>404 of type java.lang.String cannot be converted to JSONObject
09-27 10:41:14.582: WARN/System.err(373): at org.json.JSON.typeMismatch(JSON.java:107)
09-27 10:41:14.582: WARN/System.err(373): at org.json.JSONObject.<init>(JSONObject.java:158)
09-27 10:41:14.582: WARN/System.err(373): at org.json.JSONObject.<init>(JSONObject.java:171)
09-27 10:41:14.582: WARN/System.err(373): at com.equinix.android.parsing.Parse_Json.parse_ShowOrders(Parse_Json.java:323)
09-27 10:41:14.582: WARN/System.err(373): at com.equinix.android.showmyorders.ShowMyOrders$2.run(ShowMyOrders.java:112)
Code:
try{
HttpPost post = new HttpPost("http://qa.mobile.equinix.com/eqixmobile/siteservice/order/getsitevisitsByCustOrgId");
StringEntity se = new StringEntity("{\"userKey\":\"68782\",\"custOrgId\":\"37\",\"credentials\":{\"password\":\"welcome1\",\"username\":\"mobileuser1\"},\"ibxCode\":\"SV1\",\"orderStatusList\":[\"SAVED\",\"SUBMITTED\"],\"pagination\":{\"pageNo\":1,\"pageSize\":6}}");
obj = new Service_Call(post, se, "mobileuser1", "welcome1",false);
String json_string = obj.call_Service();
new Parse_Json(json_string).parse_ShowOrders();
}catch(Exception e)
{
e.printStackTrace();
}
Call Service Method:
package com.equinix.android.servicecall;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import com.equinix.android.common.MenuScreen;
import com.equinix.android.parsing.Parse_Json;
import com.equinix.android.parsing.Parse_Json;
import com.equinix.android.sitevisit.Site_Visit_Details;
public class Service_Call {
HttpPost post;
StringEntity eq_Credentials;
String usr_Name,pass;
boolean flag;
public static int status_code=0;
public Service_Call(HttpPost post,StringEntity eq_Credentials, String usr_Name, String pass,boolean flag)
{
this.post = post;
this.eq_Credentials = eq_Credentials;
this.usr_Name = usr_Name;
this.pass = pass;
this.flag = flag;
}
public String call_Service()
{
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 20000); //Timeout Limit
HttpResponse response;
try{
// HttpPost post = new HttpPost("http://122.180.114.68/eqixmobile/siteservice/um/ibx");
if(flag)
{
eq_Credentials.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(eq_Credentials);
response = client.execute(post);
System.out.println("The request body:"+post);
}
else
{
post.setHeader("Content-type", "application/json");
post.setHeader("accept", "application/json");
eq_Credentials.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(eq_Credentials);
response = client.execute(post);
System.out.println("The request body:"+post.toString());
status_code = response.getStatusLine().getStatusCode();
System.out.println("The Response Code:"+response.getStatusLine().getStatusCode());
}
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
String str="";
String line = null;
while ((line = reader.readLine()) != null) {
str +=line;
}
System.out.println(str);
return str;
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
A: Please Remove the following line from your code.
*eq_Credentials.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));*
Hope this help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Compute covariance matrix using Excel In Excel, I have 10 columns of data from column A to column J, and each column has 1000 rows from row 1 to row 1000. I wonder how to compute the 10 x 10 covariance matrix of the 10 columns of data in Excel?
My partial solution is based on dollar signs and copying formulas:
First I input in a cell a formula =covar($A1:$A1000,A1:A1000).
Then I copy and paste the formula to the cells on the right of the first cell, which gives me =covar($A1:$A1000,B1:B1000) ... =covar($A1:$A1000,J1:J1000).
Now I don't know how I can get =covar(B1:B1000,A1:A1000) ... =covar(J1:J1000,A1:A1000), because if I copy and paste the formula to the cells below the first cell, I will get =covar($A2:$A1001,A2:A1001), ..., =covar($A1000:$A2001,A1000:A2001) instead.
Thanks!
A: To make the formula "copy-proof" you can make use of the =OFFSET() function in combination with row and column indices. Example:
*
*in L1...U1 enter numbers 1, 2, 3, ... 10
*in K2...K11 enter numbers 1, 2, 3, ... 10
*now copy-proof references to one of the 10 columns A...J. This can be obtained by:
*
*=OFFSET($A$1:$A$1000,0,L$1-1) to follow the horizontal index
*=OFFSET($A$1:$A$1000,0,$K2-1) to follow the vertical index
*and finally you combine the 2 above into
=COVAR(OFFSET($A$1:$A$1000,0,L$1-1),OFFSET($A$1:$A$1000,0,$K2-1))
*this formula that you enter in L2, copy into L2..U11 to obtain your 10x10 matrix
Hope that helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Match url folders with a tag href to make an active state I made an active state for my menu on a certain urls. I have urls like this:
*
*/products/other-clothing/sporting/adults-anzac-australia-polo
*/products/other-clothing/sporting/adults-nz-tee
*/products/bags/backpacks
My code gets the folder from after the / so other-clothing, sporting, etc.
It is working fine, I just assume there is a more efficient way to write the code.
Here is my code:
jQuery(".product-nav li a").each(function() {
// URL url
var cat = location.pathname.split("/")[2];
var subcat = location.pathname.split("/")[3];
var c = "/products/" + cat + "/" + subcat;
// A tag url
var acat = this.href.split("/")[4];
var asubcat = this.href.split("/")[5];
var e = "/products/" + acat + "/" + asubcat;
if(e == c) {
jQuery(this).parent().addClass("active");
jQuery(this).parent().parent().parent().addClass("active");
}
});
If anyone can provide a cleaner way of writing the code that'd be great. I probably dont need "/products/" +.
A: Notice the output of the following expressions:
$('<a href="/questions/7564539/match-url-folders-with-a-tag-href-to-make-a-active-state"></a>')[0].href;
/*
* http://stackoverflow.com/questions/7564539/match-url-folders-with-a-tag-href-to-make-a-active-state
*/
$('<a href="/questions/7564539/match-url-folders-with-a-tag-href-to-make-a-active-state"></a>').eq(0).attr('href');
/*
* /questions/7564539/match-url-folders-with-a-tag-href-to-make-a-active-state
*/
So, if your <a> tags contain URLs that start with / then you can compare the .attr('href') with location.pathname. For testing, try running this in console from this page:
$('a').each(function () {
if ($(this).attr('href') == location.pathname) {
$(this).css({
'font-size': '40px',
'background-color': 'lime'
});
}
});
A: Here's a brief whack at it:
jQuery(".product-nav li a").each(function() {
// URL url
var c = location.pathname.split('/').slice(2, 4)
// A tag url
, e = this.href.split('/').slice(4, 6)
;
if(e[0] == c[0] && e[1] == c[1]) {
jQuery(this).parentsUntil(
'div:not(.subnav)', // go up the tree until the 1st div that isn't .subnav
'.product-nav li, .subnav' // and only match these parents
).addClass('active');
}
});
.parent().parent().parent()... has a pretty bad code smell to it but can't be improved without a look at your markup. You should probably be using .closest() instead.
A: Interesting question. Here is my attempt to clean it up:
jQuery(function ($) {
function Category(outer, inner) {
this.outer = outer
this.inner = inner
}
Category.fromURL = function (url) {
var parts = url.replace(/^(https?:\/\/.*?)?\//, "").split("/")
return new Category(parts[1], parts[2])
}
Category.prototype.equals = function (other) {
return this.outer === other.outer
&& this.inner === other.inner
}
var category = Subcategory.fromURL(location.href)
$(".product-nav a").each(function () {
if (Category.fromURL(this.href).equals(category)) {
$(this).closest("li.inner").addClass("active")
$(this).closest("li.outer").addClass("active")
}
})
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Checking for Referential Integrity Violation before deletion in ASP .NET MVC I have an object Tag that is linked to a whole bunch of other objects. I am attempting to handle the Delete for this object. I simply don't want to delete the tag if it is associated to any other objects.
At the moment I am solving it like this:
if(tag.Stands.Count == 0 && tag.Skids.Count == 0
&& tag.Panels.Count == 0 && tag.Devices.Count == 0
&& tag.Cables.Count == 0 && tag.JunctionBoxes.Count == 0)
{
_db.Tags.DeleteObject(tag);
_db.SaveChanges();
}
If I don't check for all these things, I obviously get a reference constraint error, e.g.
System.Data.SqlClient.SqlException: The DELETE statement conflicted
with the REFERENCE constraint "FKStandTag237968".
I know a way to get around this is with cascading deletes but it is actual business logic that tags shouldn't be deleted if they are associated to any other object.
Is there a way using the Entity Framework that I can check that I won't break any constraints on the DB before attempting to save a delete? Something along the lines of _db.IsValidToDelete(object)?
A: Having such a method (_db.IsValidToDelete(object)) will not guarantee you that it is safe to delete. Your application is a multi-user application. So one user may associate a tag when another user tries to delete it.
So better alternative would be to allow user to delete the tag and catch the exception to examine whether it is a referential integrity violation.
A: Btw. each call like tag.Stands.Count will load all related Stands from the database to your application so if you have a lot of relations and each contain a lot of entities this validation will be damn expensive and slow.
You can either use @Eranga's advice and catch exception or create stored procedure for tag deletion.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to select records faster from a big database? I have a mysql table of postcodes with 200000 Records in it. I want to select just one field post_code from it and fetch the postcodes for auto suggestion in a textbox. I will do this using jquery but I want to know which method I should use to create code in php and select records faster?
A: Without specifics it's hard to give an answer more specific than "Write a faster query".
I'm going to make a huge assumption here and assume you're working on a web application that's populating an autocomplete form.
You don't need all the post-codes! Not even close.
Defer populating the autocomplete until the user starts typing into the postcode field. When that happens, do an AJAX load to get the postcodes from the database.
Why is doing it this way better than just fetching all the post codes?
Because you now know what letter the user's post code starts with.
Knowing the first letter of the post code means you can eliminate any post code in your dataset that doesn't start with the same letter. You'll go from having to fetch 20000 postcodes to having to fetch less than 2000, improving performance by over an order of magnitude. If you wait until the user has entered two letters, you can get the amount of data to be fetched down even further.
Also, I'm assuming you're using an index on your postcode column, right?
A: I would think you simply want to create a MySql index on "post_code"?
Q: How many postal codes are you planning on fetching at a time (and passing back to the browser)? One? Five? 200,000?
A: You can use Sphinx-Php Api to deal with big database
But you will need to indexer file for your search for the first time to use this way.
Or can go for Zend Lucene Search
A: you probably want to filter the records that matches the current input of the user and your query should be as follows:
select postal_code from table_name where postal_code like '<userinput>%' LIMIT 50 eg: '60%'
and send back this result set to your jquery callback function. remember to set a limit on the postal codes retrieved as you dont want to send back too much data which not only hampers the performance but doesnt help the user in a direct way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Exploring nutch over hadoop What possibly can i do with Hadoop and Nutch used as a search engine ? I know that nutch is used to build a web crawler . But i'm not finding the perfect picture . Can i use mapreduce with nutch and do some mapreduce job ? Any ideas are welcome . Few links will be greatly appreciated . Thanks.
A: If you want to only do Map/Reduce jobs you don't need Nutch but Hadoop only. Hadoop brings you a cluster file system and a scheduler for map/reduce jobs on the filesystem.
As Nutch builds on top of Hadoop you can create your own map/reduce jobs on Nutch data as long as you understand the data structure and what the crawler is doing.
However if you only wanted to run some map/reduce jobs, just install hadoop and off you go.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What happens if printf is not handled I'm current supporting some legacy software written aeon ago, compiled in gcc 2.95.3. The program is ran in an SBC, occasionally I had to telnet into it to fix things. I notice that when the SBC is running on its own, it display some unexpected behavior e.g. missed executions.
When I do telnet in, slay the process and execute it manually, it stays fine that way. I'm suspecting that this has to do with performing printf without a proper terminal/console for it to print on.
If printf are not handled, what would be the effect of it?
A: Could it be that the system is trying to print to a hardware serial port (which are really slow) and when you telnet in its replaced by a TCP port instead?
A: It depends on the stdio library you use, most will attempt to write to console anyway, so...
You should redirecting your STDOUT and STDERR to NULL or to a file, this should be quiet easy.
gcc 2.95 was very stable so we can pretty much rule out any problems there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: creating a black transparent modal view controller I wanted to create a modal view controller with a black background, but I want to make the alpha as 0.9, so I can still see the view behind it partially. How do I do this? I know I can use UIView and then just add that as a subview, however if I have a UINavigationController or UITabBarController, this won't cover the entire screen. Looking for some suggestions on this, as far as I know the solutions I've seen so far never dealt with a colored background.. most only wants a transparent background.
A: This will help you...
You just have to set background color as per your requirement.
A: Did you try
[viewController1 presentModalViewController:viewController2 animated:YES];
I haven't tried it myself but the documentation says it always presents it full screen. Then just set its view to have a backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.9];. (white = 0.0 is black). Add whatever subviews you want. Or set the background color to be full black and the alpha of the whole view to be 0.9. It depends if you want the subviews also to be a bit translucent.
A: I got this idea from https://gist.github.com/1279713
Prepare:
In the modal view xib (or scene using storyboard), I setup the full-screen background UIImageView (hook it with the .h file and give it a property "backgroundImageView") with 0.3 alpha. And I set the view (UIView) background color as plain black.
Idea:
Then in "viewDidLoad" of the modal view controller I capture the screenshot from the original status and set that image to the background UIImageView. Set the initial Y point to -480 and let it slide to Y point 0 using 0.4-second duration with EaseInOut animation option. When we dismiss the view controller, just do the reverse thing.
Code for the Modal View Controller Class
.h file:
@property (weak, nonatomic) IBOutlet UIImageView *backgroundImageView;
- (void) backgroundInitialize;
- (void) backgroundAnimateIn;
- (void) backgroundAnimateOut;
.m file:
- (void) backgroundInitialize{
UIGraphicsBeginImageContextWithOptions(((UIViewController *)delegate).view.window.frame.size, YES, 0.0);
[((UIViewController *)delegate).view.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
backgroundImageView.image=screenshot;
}
- (void) backgroundAnimateIn{
CGRect backgroundImageViewRect = backgroundImageView.frame;
CGRect backgroundImageViewRectTemp = backgroundImageViewRect;
backgroundImageViewRectTemp.origin.y=-480;
backgroundImageView.frame=backgroundImageViewRectTemp;
[UIView animateWithDuration:0.4 delay:0.0 options:UIViewAnimationCurveEaseInOut animations:^{
backgroundImageView.frame=backgroundImageViewRect;
} completion:^(BOOL finished) {
}];
}
- (void) backgroundAnimateOut{
CGRect backgroundImageViewRect = backgroundImageView.frame;
backgroundImageViewRect.origin.y-=480;
[UIView animateWithDuration:0.4 delay:0.0 options:UIViewAnimationCurveEaseInOut animations:^{
backgroundImageView.frame=backgroundImageViewRect;
} completion:^(BOOL finished) {
}];
}
In viewDidLoad, simply call:
[self backgroundInitialize];
[self backgroundAnimateIn];
In anywhere we dismiss the modal view controller, we call:
[self backgroundAnimateOut];
Please note that this will ALWAYS animate the background image. So if this modal view controller transition style (or the segue transition style) is not set to "Cover Vertical", you may not need to call the animation methods.
A: First add an UIImageView in you .h file
UIImageView *overLayImage;
now add below code in .m file on viewDidLoad()
overLayImage=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"overlay1px.png"]] ;
overLayImage.frame = self.view.frame;
overLayImage.frame = CGRectMake(0, 0, 1024, 748);
Where "overlay1px.png" is a transparent image of your color choice with height and width of 1px X 1px.
Now in your IBAction from where you want add your view with transparent backgroud add the below code
[self.view addSubview:overLayImage];
[vwTermsCondition setFrame:CGRectMake(262, 300, 500, 120)];
[vwTermsCondition.layer setCornerRadius:5.0f];
[vwTermsCondition.layer setShadowColor:[UIColor blackColor]];
[vwTermsCondition.layer setMasksToBounds:YES];
[self.view addSubview:vwTermsCondition];
In the above code vwTermsCondtion is the name of your view. This is for iPad appplication you can adjust height/width for iPhone.
Enjoy :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Facebook Like Button with prepopulated Comment I've got a page with a table of items that the user can select. I'd like to add a facebook LIKE button.
When the user clicks the like button, it will popup the comment box, which I'd like to be helpfully prepopulated comment based on the items the user has clicked. They can change it if they wish, or they can just leave it as is. It would say something like "I like Item-1 and Item-4", if those table rows were selected.
Is it even possible to pre-populate the comment field?
If so, is it possible to change it via javascript each time the user changes their selection?
A: It is not possible to pre-populate the comment field of the Like Button, as it must be user generated. However, you can create unique URLs for each table row that will generate unique content in the like button story to represent the item the user liked. For Example:
<fb:like href="http://www.example.com/example.php?row=row1"></fb:like>
<fb:like href="http://www.example.com/example.php?row=row2"></fb:like>
The OG meta data associated with each unique URL should represent the item information for that row. Example:
<meta property="og:title" content="Row 2 Item"/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="http://www.example.com/example.php?row=row2"/>
<meta property="og:image" content="http://www.example.com/example_row2.jpg"/>
<meta property="og:site_name" content="example"/>
<meta property="og:description" content="Information about item at row 2"/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: QML - Move to top #TOP I am using a Flickable which is embedded in a Rectangle.
There is a button in the bottom of the rectangle.
My requirement is when I press the button my Flickable will move to top.
Its almost like #TOP in HTML.
Is anybody have an idea how to achieve this?
A: You should be able to set Flickable's contentY property to 0.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Showing a dialog in a thread I have a pygtk add which has a gtk.Button() which when pressed has to do a job of lets say 5 seconds. So, the thought of implementing the time-intensive function in the signal handler as a thread.
First of all, I have added gtk.gdk.threads_init() in the beginning.
My signal handler is def send_sms() and in that I have another function def send_sms_mycantos() which I call as a thread.
threading.Thread(target = self.send_sms_mycantos, args=(phone_no, message_text, username, password)).start()
I also have a function which displays dialogs.
def dialog_notification(self, message, dialog_type):
dlg = gtk.MessageDialog(self.window, gtk.DIALOG_DESTROY_WITH_PARENT, dialog_type, gtk.BUTTONS_CLOSE, message)
dlg.run()
dlg.destroy()
Now, if I call the above function in my thread
self.dialog_notification("Message sent successfully", gtk.MESSAGE_INFO)
I get this error.
SMSSender.py: Fatal IO error 11 (Resource temporarily unavailable) on X server :0.0.
Is this the right way to implement threading. What am I doing wrong. The error is like the thread doesn't know that Xserver is running.
A: The simplest way would be to run self.dialog_notification() in the main gtk thread. Just add gobject.idle_add(self.dialog_notification, args...) in your thread.
A: The error appears because you are updating the GUI from a thread.
You should use Gdk.threads_enter() and Gdk.threads_leave() (you must import Gdk) every time that you access to the GUI.
def dialog_notification(self, message, dialog_type):
dlg = gtk.MessageDialog(self.window, gtk.DIALOG_DESTROY_WITH_PARENT, dialog_type, gtk.BUTTONS_CLOSE, message)
Gdk.threads_enter()
dlg.run()
Gdk.threads_leave()
Gdk.threads_enter()
dlg.destroy()
Gdk.threads_leave()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Aligning a Child Div in a parent div
Possible Duplicate:
Make outer div be automaticly the same height as its floating content
I feel like I'm missing something very simple here...
We have a simple setup: a parent div that contains a child div.
I want to:
*
*make the parent resize its height based on the child
*align the child to the right edge of the parent instead of the default left.
Using float:right will cause the parent to no longer resize correctly and the child to 'jump out' of the parent.
I've tried using align: right and text-align: right but so far no dice.
HTML:
<div id="parent"> <p>parent</p>
<div class="child"> <p>child</p> </div>
<div class="child right"> <p>child2</p> </div>
</div>
CSS:
div{ padding: 15px; margin: 5px; }
p{ padding: 0; margin: 0; }
#parent{
background-color: orange;
width: 500px;
}
.child{
background-color: grey;
height: 200px;
width: 100px;
}
.right{ float: right; } // note: as the commenters suggested I should also be using a float:left on the other child.
Result:
What I want:
Any suggestions on what I could change either with #parent or .right to make child2 align to the right properly?
EDIT
The best fix I found for this is just using display:table on the parent. Though I haven't tested this in IE it fixes the issue in the browsers I care for and avoids using the un-intuitive overflow:hidden method discussed in the comments.
Even better: set margin-left of the child to auto.
A: Try floating the contents and adding overflow: hidden to the parent. It's counter-intuitive but worked for me with a similar issue.
EDIT: Also float the first child to the left.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Automated input generator for black-box testing I am a newbie for software testing. I want to know, is there any open source tool for automated test case generator black-box testing.
I found this tool KLEE: unassisted and automatic generation of high-coverage tests for complex systems programs, but to use this tool I need to do some code instrumentation. Is there any way I can generate automated testcases without code instrumentation as I don't have access to the source code.
A: KLEE does work with programs without modification. You can have it generate symbolic command line inputs as well as symbolic input files. Here are some example commands that can be used for this purpose:
-sym-arg - Replace by a symbolic argument with length N
-sym-args - Replace by at least MIN arguments and at most
MAX arguments, each with maximum length N
-sym-files - Make stdin and up to NUM symbolic files, each
with maximum size N.
-sym-stdout - Make stdout symbolic.
Examples can be found in the tutorials on KLEE's website.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Linked Combobox (filter store) you need when choosing to download a combobox CountryComboBox combobox CityComboBox list of products filtered by field *city_id*. My code works, but not the first time))
Opt for the first combobox value - I go in the second - the filter does not apply. Click again on the first, again in the second - and that's only if it is applied. What am I doing wrong? And then make a filter for the output grid, as well as for the combobox?
ExtJs 3.
My Code:
tbar: [
{
xtype : 'CountryComboBox', // expansion Ext.form.ComboBox
listeners : {
'select' : {
fn : function(combo, value) {
var combobox_city = Ext.getCmp('ProductsProductTypeComboBoxForProduct');
combobox_city.enable();
combobox_city.clearValue();
combobox_city.store.filter('city_id', combo.getValue(), true);
}
}
}
},
{
xtype : 'CityComboBox', // expansion Ext.form.ComboBox
disabled : true,
listeners : {
'select' : {
fn : function(combo, value) {
this.store.filter('people_id', combo.getValue(), true);
}
}
}
},
...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: GWT RPC: DTO vs. DAO? I've started learning GWT about a week ago and here's the question I can't answer for sure.
Here's the server-side:
// business object - has logic
interface Article {
String getTitle(); // lazy
void setTitle();
String getText(); // lazy
void setText();
Set<Comment> getComments(); // lazy
}
// also has logic
interface Comment { ... }
I need to somehow create a GWT widget to visualize Article. Passing Article won't work, since it's not serializable and moreover, it has some BL. So, there are 2 ways:
The first one is to use DTOs like:
class ArticleDTO implements Serializable {
public int articleId;
public String title;
public String text;
}
class CommentDTO implements Serializable {
public int commentId;
public int articleId;
public String commentText;
}
The I'll have to implement a repository logic in my GWT RPC service:
class MyRPCRepository ... {
ArticleDTO getArticle(int id);
void saveArticle(ArticleDTO article);
void deleteArticle(ArticleDTO article);
...similar things for comments here...
}
The second way is to use DAOs:
class ArticleDAO implements Serializable {
private transitional MyRPC rpc;
private int articleId; // only this one is serializable
public ArticleDAO(MyRPC rpc, int articleId) { ... }
public String getTitle() {
// i know it would require more code in real
return rpc.getArticleTitle(articleId);
}
...
}
I like the first one, because it's really stupid. I like the second one because it's quite intellectual. Which one should I choose to make the code easier to understand and maintain?
A: In projects I've worked on, people seem to differ a lot in their opinions about the best approach to take with problems like this. There are pros and cons for both. The DTO approach is now supported by GWT in an API called RequestFactory, and is advertised as an alternative to "standard" GWT RPC usage (your DAO approach). You gain performance and integration with GWT's data binding framework, and the cost of maintaining the DTOs. I think it's a good trade-off, but for small projects it might be overkill.
A: Typically DAOs are objects that determine data access methods of your system, while DTOs define data that is used by DAOs. So your first method is quite good but it is actually DAO/DTO method with MyRPCRepository being actually DAO (Data Access Object).
Second method is totally weird to my taste. It is some kind of service that allows you to access some pieces of your data and yet it retains some state (usually you want DAOs to be stateless).
So I vote for the first method, but repository should probably be called ArticleDAO and similar DAOs would be there for other data objects.
A: The question to ask is "how do you intend to use any of the solutions?" Assuming you have a kind of table UI on the client side, where you always show articelId, title and text (knowing that you are describing a kind of "Online Forum" I can assume you don't show the text, but lets pretend I did not know that). Now, with a DTO you simply can transfer a bunsh (one page?) of objects to the client. That means the transfer is done in one chunk and there is only one request from the client to fullfill.
With your DAO approach (which I would not call DAO but "Service" in this case) you might still send a bunsh of objects in one request/response to the client, but a cascade of small requests to display title and text will come back from the client.
So the question to ask is: how does the user interact with your system? In your concrete example I always would transfer "id" and "title" and only use a second request/DAO approch for the text.
OTOH again, if only a few users are using the system (dozens or a few hundret) I would use the approach that is most easiest to develop or maintain.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to apply parallelism-programming in graph problems? Problem Description:
there is n tasks, and in these tasks, one might be dependent on the others, which means if A is dependent on B, then B must be finished before A gets finished.
1.find a way to finish these tasks as quickly as possible?
2.if take parallelism into account, how to design the program to finish these tasks?
Question:
Apparently, the answer to the first question is, topological-sort these tasks, then finish them in that order.
But how to do the job if parallelism taken into consideration?
My answer was,first topological-sort these tasks, then pick those tasks which are independent and finish them first, then pick and finish those independent ones in the rest...
Am I right?
A: Topological sort algorithms may give you various different result orders, so you cannot just take the first few elements and assume them to be the independent ones.
Instead of topological sorting I'd suggest to sort your tasks by the number of incoming dependency edges. So, for example if your graph has A --> B, A --> C, B --> C, D-->C you would sort it as A[0], D[0], B[1], C[3] where [i] is the number of incoming edges.
With topological sorting, you could also have gotting A,B,D,C. In that case, it wouldn't be easy to find out that you can execute A and D in parallel.
Note that after a task was completely processed you then have to update the remaining tasks, in particular, the ones that were dependent on the finished task. However, if the number of dependencies going into a task is limited to a relatively small number (say a few hundreds), you can easily rely on something like radix/bucket-sort and keep the sort structure updated in constant time.
With this approach, you can also easily start new tasks, once a single parallel task has finished. Simply update the dependency counts, and start all tasks that now have 0 incoming dependencies.
Note that this approach assumes you have enough processing power to process all tasks that have no dependencies at the same time. If you have limited resources and care for an optimal solution in terms of processing time, then you'd have to invest more effort, as the problem becomes NP-hard (as arne already mentioned).
So to answer your original question: Yes, you are basically right, however, you lacked to explain how to determine those independent tasks efficiently (see my example above).
A: I would try sorting them in a directed forest structure with task execution time as edge weigths. Order the arborescences from heaviest to lightest and start with the heaviest. Using this approach you can, at the same time, check for circular dependencies.
Using parallelism, you get the bin problem, which is NP-hard. Try looking up approximative solutions for that problem.
A: Have a look at the Critical Path Method, taken from the are of project management. It basically do what you need: given tasks with dependecies and durations, it produces how much time it will take, and when to activate each task.
(*)Note that this technique is assuming infinite number of resources for optimal solution. For limited resources there are heuristics for greedy algorithms such as: GPRW [current+following tasks time] or MSLK [minimum total slack time].
(*)Also note, it requires knowing [or at least estimating] how long will each task take.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How can I fix this mobile stylesheet bug for iPhones and ipods? This is how my mobile stylesheet looks on a live iphone device: http://awesomescreenshot.com/0b1l8g51a , the website url can be seen in the adressbar, it looks fine on ipod/iphone from the second generation. Thanks
A: @user257357; it's not only problem of your ipad & ipod version it also have a problem in your PC version. Just test when you decrease your window size.
solution
css:
iphone & ipad
body{
min-width:480px;
}
css:
PC
body{
min-width:966px;
}
check this for more iPad background for div blocks not spanning entire width of screen
A: I think that this
width:100%;
will do the job better.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to remove attributes from HTML using javascript? I have an HTML with say a textfield (input element).
<input name="capacity" type="text" value="blah blah blah">
This simply displays a text field on my page with a default value "blah blah blah".
What I want to do is remove value attribute, as I don't want to see this default value.
I am doing this using javascript.
value = element.getAttribute("value");
if((element.readOnly != undefined || element.readOnly == false) || (element.disabled != undefined || element.disabled == false)){
//element.removeAttribute(value);
element.removeAttribute("value");
But it is not working. I even tried
element.setAttribute("value","");
but no luck.
Any pointers where I may be missing.
EDIT :
I got an issue related to this question, anyone interested may check this
*********************************************
Thanks a lot.
A:
...I don't want to see this default value.
Just set the value property directly to an empty string.
document.getElementsByName('capacity')[0].value = '';
jsFiddle.
A: Give your text field and id like <input name="capacity" type="text" id="text" value="blah blah blah"> document.getElementById['text'].value = "";
A: This is your html tag. You will need to add a ID to it
<input id="capacity" name="capacity" type="text" value="blah blah blah">
This is just to fire the javascript function
<input type="submit" value="Click" onclick="javascript:return reset();" />
The following function will reset the value of the selected element
<script type="text/javascript" language="javascript">
function reset() {
document.getElementById("capacity").value = "";
return false; // In order to avoid postback
}
</script>
If you are not using form and you want to use it with just the name you can try the following
this.capacity.value = '';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Arabic words problem in LWUIT on some models I've created a gui using LWUIT which uses Arabic words (and so it is right to left)
It works fine on some models (Sony Ericsson T700 or Elm for example). But on some other models (e.g. Sony Ericsson w800) words are not displayed correctly: letters are separated and displayed one by one from left to right.
I have absolutely no clues about the reason.
I found this thread:
LWUIT : issue in showing arabic words ?
This post is answered by Shai Almog who is one of LWUIT developers.
So I added below line to my code:
list.getStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_MEDIUM));
But it doesn't solve the problem.
1- Shai has answered that system fonts should be used. Is my code correct in order to set system font?
2- any other clues?
I have tested my application with both LWUIT 1.5 and 1.4 and both are the same regarding this problem.
Can anybody help me out of this?
Thank you in advance
A: AFAIK some Sony Ericsson mobiles having problem while showing Arabic font. It will be discussed in this forum.
A: OK, I searched for the problem and now I got something to say:
It seems there's a problem when we use LWUIT on old SonyEricsson models to show Arabic texts. The problem doesn't show up on newer SE models and you won't have this problem when you use standard jme or j2me polish. (As you see in my original post, w800 has the problem but T700 doesn't. so somewhere between 2005 and 2008 the problem is solved).
System fonts have this problem and you can't use bitmap fonts since LWUIT doesn't support bitmap fonts for Arabic words. (see this: LWUIT : issue in showing arabic words ? )
How to solve it :
A friend on the net guided me to this solution:
To fix the first problem you should reshape the string yourself, I
tried to search for some similar code, this might help you
http://code.google.com/p/glyph-util/source/browse/trunk/src/com/ahmadiv/dari/DariGlyphUtils.java
You should map each character to the correct glyph according to its
location in the word, and the characters surrounding the characters.
This might help you: http://unicode.org/charts/PDF/UFE70.pdf
Then, mirror the words to finally fix the problem.
Finally, add the fix to drawString() method of LWUIT.
Just, final note..this don't worth the headache. The handsets that
have this problem are very old handsets. I think you could skip
supporting them. We already stop supporting them.
I accepted his final advice, so I didn't solved the problem at last, I simply left it :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there any GWT fork around? I know that GWT is open-source and freely available. However just a curious question, is there any GWT fork around? I know one that can be considered which is Vaadin.
Cheers.
A: You did already answer your question, but there are others. The first that comes to mind is Pyjamas, which is actually a Python to Javascript compiler.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.