text stringlengths 8 267k | meta dict |
|---|---|
Q: Website Redirection Suppose that the user is currently located http://www.example.com/folder1/folder2/. I would like to be able redirect them to the home page at http://www.example.com/. The catch is, I don't know I'm two folders deep and I don't know what the domain name is. To do this, what should the href be in a link? For example, href='../../' would seem to work if I know a priori I'm two folders deep, but in general I won't know that. I want a link that will always direct me right to the home page, regardless of how 'deep' I am and regardless of the domain name of the site. How do I do this?
Thanks in advance!
A: "/" will direct to the root of your website:
<a href="/">Home</a> <!-- http://site.com/ -->
<a href="/lol/abc.html">ABC</a> <!-- http://site.com/lol/abc.html -->
etc.
A: Try using a root-relative link, which starts at the root of the site and builds outward. In this case, you want to go directly all the way to the root, so your path would just be /:
<a href="/">Home</a>
A: you can use href="/" to go to the root of a site.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Creating a simple pdf I'm trying to create a PDF on the iPhone for practice. I'm not sure why it doesn't work. I get the error:
2011-09-21 21:35:00.412 CreatePDF[869:b303] -[CreatePDFViewController createPDFDocumentAtURL:]
CreatePDF[869] <Error>: CGDataConsumerCreateWithFilename: failed to open `/Users/jon/Library/Application Support/iPhone Simulator/4.3.2/Applications/4486CF27-B309-4C7C-82A5-B425B9E2C04D/Documents' for writing: Is a directory.
deflateEnd: error -3: (null).
CreatePDF[869] <Error>: CGPDFContextCreate: failed to create PDF context delegate.
2011-09-21 21:35:00.419 CreatePDF[869:b303] Couldn't create PDF context
<Error>: CGContextBeginPage: invalid context 0x0
Here is the code I have:
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSURL *documentsURL = [NSURL fileURLWithPath:documentsDirectory];
[self createPDFDocumentAtURL:(CFURLRef)documentsURL];
NSLog(@"%s", __FUNCTION__);
}
- (void)createPDFDocumentAtURL:(CFURLRef)url {
NSLog(@"%s", __FUNCTION__);
float red[] = {1., 0., 0., 1. };
CGRect mediaBox = CGRectMake(0, 0, 850, 1100);
CGContextRef pdfContext = CGPDFContextCreateWithURL(url, &mediaBox, NULL);
if (!pdfContext) {
NSLog(@"Couldn't create PDF context");
}
CGContextBeginPage(pdfContext, &mediaBox);
CGContextSaveGState(pdfContext);
CGContextClipToRect(pdfContext, mediaBox);
CGContextSetFillColorSpace(pdfContext, CGColorSpaceCreateDeviceRGB());
CGContextSetFillColor(pdfContext, red);
CGContextFillRect(pdfContext, mediaBox);
CGContextRestoreGState(pdfContext);
CGContextEndPage(pdfContext);
CGContextRelease(pdfContext);
}
A: You have to add the new file's name to your URL. Your documentsURL contains this right now:
/Users/jon/Library/Application Support/iPhone Simulator/4.3.2/Applications/4486CF27-B309-4C7C-82A5-B425B9E2C04D/Documents/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java - where to store extra resources files My code require one PNG file. Where should I put it ?
I saw some people put them along with .java, then use getClassLoader().getResourceAsStream.
Personally, I feel it is not clean to mix resource files with source code.
Is this a OK approach ?
A: That is a very common and accepted practice. It has the advantage that the PNG file will be bundled inside of the JAR file along with the code. So you do not have to worry about file system issues and installation processes. If your code is there, so will the resource.
You can have multiple source folders for the same project, one for Java, one for resources. If you are using Maven, it is recommended to have that kind of structure. However, mixing the PNG (and properties, and XML) files into the source tree is not a problem, either (especially since the separation would complicate the build process if you do not use Maven).
The only things you should keep apart from the source (and the compiled result) is user-editable data, such as configuration files. This may apply here if you want the user to be able to replace the image. If it is fixed (or a default is provided), bundle it up with your program to reduce the number of movable (= breakable) parts.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: pass 2 variables from 1 function to another in jquery OK, I'm getting the results of a PHP form from JSON to do a login validation. I want to check to see if their account is activated, which I do just fine. If it's not I show a jQuery error but I want the ability to let them resend the activation email. I can pass the username password to the function displaying the error with JSON, but how do I then pass that data to a new function to process the new email? Here is what I have so far:
// LOGIN Validation
$(function(){
$("#jq_login").submit(function(e){
e.preventDefault();
$.post("widgets/login_process.php", $("#jq_login").serialize(),
function(data){
if(data.all_check == 'invalid'){
$('div.message_error').hide();
$('div.message_success').hide();
$('div.message_error').fadeIn();
$('div.message_error').html(
"<div>UserId and/or password incorrect. Try again.</div>"
);
} elseif(data.user_check == 'invalid'){
$('div.message_error').hide();
$('div.message_success').hide();
$('div.message_error').fadeIn();
$('div.message_error').html(
"<div>UserId and/or password incorrect. Try again.</div>"
);
} elseif (data.activated_check == 'invalid'){
$('div.message_error').hide();
$('div.message_success').hide();
$('div.message_error').fadeIn();
$('div.message_error').html(
"<div>Your account has not been activated. Please check your " +
"email and follow the link to activate your account. Or click " +
"<a href='#' id='resend'>here</a> to re-send the link.</div>"
);
} else {
$('div.message_error').hide();
$('div.message_success').fadeIn();
$('div.message_success').html(
"<div'>You are now logged in. Thank you </div>"
);
window.location.replace("producer.php");
return false;
}
}, "json");
});
});
$(function(){
$("#resend").live('click', function(event){
event.preventDefault();
alert(data.username);
var data = 'username=' + data.username + 'password=' + data.password;
$.ajax
});
});
I'm new so I don't understand all the ins and outs of passing data back and forth.
thank you.
craig
A: Could the server simply append the confirmation link with the returned json?
$('div.message_error').html(
"<div>Your account has not been activated. Please check your " +
"email and follow the link to activate your account. Or click " +
"<a href='" + data.activation_url + "' id='resend'>here</a> to re-send the link.</div>"
);
A: With Ajax there's not really "passing data back and forth," but rather just passing callbacks. That's what you're doing when you put function() { ... } as a function parameter--you're creating a callback.
I think the best course of action is to refactor this into several stand-alone functions. A good best practice is to make each function do one thing only, rather than defining functions within functions within functions.
Once refactored, it becomes more clear how we can "reuse" the username and password for the resend-activation link.
(function() { // to keep these functions out of the global scope(†)
// this will be called when the login form is submitted
function handleLogin(evt) {
evt.preventDefault();
// same as your code except that instead of creating a function here
// we instead pass `handleLoginResponse`, which is a function we'll
// define later
$.post( 'widgets/login_process.php',
$(this).serialize(), // <-- In events, `this` refers to the element that
handleLoginResponse, // fired the event--in this case the form, so we
'json' // don't need its id, we can just give `this`
); // to jQuery.
}
// This is the function we gave to $.post() above, and it'll be called when
// the response is received.
function handleLoginResponse(data) {
// Here we decide what message to show based on the response, just like
// in your code, but we call a function (showError or showSuccess) to
// avoid repeating ourselves.
if(data.all_check == 'invalid') {
showError("UserId and/or password incorrect. Try again.");
} else if(data.user_check == 'invalid') {
showError("UserId and/or password incorrect. Try again.");
} else if(data.activated_check == 'invalid') {
showError("Your account has not been activated. Please check your " +
"email and follow the link to activate your account. Or " +
"click <a href='#' id='resend'>here</a> to re-send the link."
);
} else {
showSuccess("You are now logged in. Thank you.");
redirectToLoggedInPage();
}
}
// the function that shows error messages
function showError(message) {
$('.message_success').hide();
$('.message_error').hide(). // jQuery chaining keeps things tidy
html('<div>' + message + '</div>').
fadeIn();
}
// the function that shows success messages
function showSuccess(message) {
$('div.message_error').hide();
$('div.message_success').fadeIn().
.html('<div>' + message '</div>');
}
// this method is called when the "resend" link is clicked
function handleResendClicked(evt) {
evt.preventDefault();
// send another Ajax request to the script that handles resending, using
// the form values as parameters
$.get( './resend_activation.php',
$('#jq_login').serialize(),
handleResendResponse // again we've defined this function elsewhere
);
}
// called when the Ajax request above gets a response
function handleResendResponse(data) {
// of course you can do whatever you want with `data` here
alert('resend request responded with: ' + data);
}
// called from handleLoginResponse when the login is successful
function redirectToLoggedInPage() {
window.location = './producer.php';
}
// finally, our document.ready call
$(function() {
// pass the names of the functions defined above to the jQuery
// event handlers
$("#jq_login").submit(handleLogin);
$("#resend").live('click', handleResendClicked);
});
}());
Of course, you won't always code like this--sometimes it really is best to just define an anonymous function() { ... } on the spot--but when things are getting nested three-levels deep this is a good way to untangle things and tends to make the way forward more clear.
(†) Anonymous closures for limiting scope
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make an action by clicking on ScrollView in Tableview Customcell I have a tableview and i'm using CustomCell for that tableview. I have imageview, label, and ScrollView in that customcell. But my problem is, after clicking image or label that particular cell is selected and then navigating to the detailView. But on clicking scrollview, cell is not selected. How to solve my problem.? Please help me out, Thanks in advance.
My custom cell like below:
A: Solution 1
When clicking on the scroll view, cell is not selected because the scroll view receives the touches, not the cell. If you want the cell to receive touches you need to explicitly set,
scrollView.userInteractionEnabled = NO;
which will make the scrollView irresponsive to touches, and I hope that is not what you want.
Solution 2
I think you are not doing anything with the scrollView when you tap on it. If so, add a UITapGestureRecognizer to the scrollView and in the tap action do the operation that you do in didSelectRowAtIndexPath: method.
- (void)handleSingleTap:(UITapGestureRecognizer *)tap {
UIScrollView *scrollView = (UIScrollView *)tap.view;
UITableViewCell *cell = (UITableViewCell *)scrollView.superview.superview;
NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
[self tableView:tbl_view didSelectRowAtIndexPath:indexPath];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Is there a way in android to get the area (a collection of points) of my finger Is there a way in android to get the area (a collection of points) of my finger when i touch the screen. Usually, the return is one point location. I need to get the several points which can represent the area of my touching. Any one knows? Thnaks
A: Just use View class's onTouchEvent() or implements OnTouchListener in your activity and get the X and Y co-ordinates like,
This is View class's OnTouchEvent()..
@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
float x = ev.getX();
float y = ev.getY();
break;
}
case MotionEvent.ACTION_MOVE: {
float mLastTouchX = x;
float mLastTouchY = y;
break;
}
case MotionEvent.ACTION_UP: {
break;
}
case MotionEvent.ACTION_CANCEL: {
break;
}
case MotionEvent.ACTION_POINTER_UP: {
break;
}
}
return true;
}
EDIT:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView textView = (TextView)findViewById(R.id.textView);
// this is the view on which you will listen for touch events
final View touchView = findViewById(R.id.touchView);
touchView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
textView.setText("Touch coordinates : " +
String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
return true;
}
});
}
For more details Android - View.
A: Does it have to be the real shape of the finger? Otherwise you could calculate a circle around the center of the touch.
A: I believe this is not possible in the touch's coordinate along with it's area. It's natively unsupported by Android API.
Ref:
http://developer.android.com/guide/topics/ui/ui-events.html
http://developer.android.com/reference/android/gesture/package-summary.html
A: Unfortunately not. I ran in to this a while ago - you could try normalising the data over several 'frames'. May be worth trying to figure out why you need an exact point, or set of points, and find another way of doing it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to arrange a daily time log entry form in Microsoft Access 2007 with Weekdays & Dates in the column headings The objective is to create a weekly form, in Microsoft Access 2007, that allows employees to select their name from a list, the date of the first day of the week, and then create all daily time longs for the week in single form. The form needs to have a week view like the form (an Excel mockup) shown here:
Once entered, the data is to be written to the Project Time Log table shown here:
When the employee selects the "Week Starting" value, the column headings in the able below need to update. Is this possible? What also has me stumped is how to enter project hours for the week in a single row that will result in creating up to 6 records in my database. Finally, how does one set up validation on the "Week Starting" field so that the employee can only select Mondays?
I guess this is where I admit that I am just getting started with MS Access. However, with some experience in database design and Excel I am finding everything but advanced form building to be fairly straightforward.
So, can someone point me in the right direction? Do I need to use a Pivot Table to make this work? What is a Modal Dialogue? Could it be useful here? Any suggestions would be greatly appreciated.
A: The easiest way may be to create a table used solely for dataentry that can reside in the front-end for each employee.
DETable
EmployeeID
WeekStarting
ProjectID
Workcode
Mon
Tue
<...>
Sat
You can clear down the table and then append the relevant projectIDs and EmployeeID with a command button or suitable event.
The labels showing Mon, Tue etc can be updated to show the relevant date after WeekStarting is selected.
A suitable set of queries, or a UNION query will allow you to append the data to the main table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: When should I stop training neural network for classification using Cross Validation Method I am now implementing neural network for classification. I use backpropagation algorithm to train. I use Cross validation method. But I am not clear when should I stop training the neural network.
Next one is how to check overfitting and underfitting.
I have a data set which has 1,000 pattern. I use 10 fold cross validation method. So 1 Fold has 100 pattern. I train with 900 pattern and test with 100 pattern.
Although I change no of hidden nodes and no of epoch, testing accuracy is not change very much. But I feed training data to trained network, accuracy of training is vary according to no of hidden nodes and no of epoch. Is My idea enough for checking overfitting and underfitting? Can I determine overfitting and underfitting only with accuracy?
I want to also ask some question continue with this. I post my result, that test with various hidden nodes and various no of epoch. As I told, I use cross validation, I use only one network(which get maximum on test accuracy) from 10 trained networks.
No of hidden nodes=50 ,Learning Rate=0.1 , no of epoch=100
Network 0 on Test=75.0 , onTrain= 97.11111111111111
Network 1 on Test=72.0 , onTrain= 98.22222222222223
Network 2 on Test=69.0 , onTrain= 97.88888888888889
> Network 3 on Test=78.0 , onTrain= 97.44444444444444
Network 4 on Test=77.0 , onTrain= 97.77777777777777
Network 5 on Test=77.0 , onTrain= 97.11111111111111
Network 6 on Test=69.0 , onTrain= 97.55555555555556
Network 7 on Test=74.0 , onTrain= 98.22222222222223
Network 8 on Test=76.0 , onTrain= 97.77777777777777
Network 9 on Test=74.0 , onTrain= 97.55555555555556
No of hidden nodes=50 ,Learning Rate=0.1 , no of epoch=70
Network 0 on Test=71.0 , onTrain= 93.22222222222221
Network 1 on Test=70.0 , onTrain= 93.33333333333333
Network 2 on Test=76.0 , onTrain= 89.88888888888889
Network 3 on Test=80.0 , onTrain= 93.55555555555556
Network 4 on Test=77.0 , onTrain= 93.77777777777779
> Network 5 on Test=81.0 , onTrain= 92.33333333333333
Network 6 on Test=77.0 , onTrain= 93.0
Network 7 on Test=73.0 , onTrain= 92.33333333333333
Network 8 on Test=75.0 , onTrain= 94.77777777777779
Network 9 on Test=70.0 , onTrain= 93.11111111111111
No of hidden nodes=50 ,Learning Rate=0.1 , no of epoch=50
Network 0 on Test=73.0 , onTrain= 87.8888888888889
Network 1 on Test=74.0 , onTrain= 89.22222222222223
Network 2 on Test=73.0 , onTrain= 87.1111111111111
Network 3 on Test=66.0 , onTrain= 90.44444444444444
Network 4 on Test=82.0 , onTrain= 88.77777777777777
Network 5 on Test=80.0 , onTrain= 88.44444444444444
Network 6 on Test=67.0 , onTrain= 88.33333333333333
Network 7 on Test=75.0 , onTrain= 87.8888888888889
Network 8 on Test=78.0 , onTrain= 87.44444444444444
Network 9 on Test=73.0 , onTrain= 85.0
The First Network( no of epoch=100) best network get accuracy on Test is 78.0 but on train is 97.4444. Is it mean overfitting? If this is overfitting, is the Third Network( no of epoch=50) best network get accuracy on test is 82.0 and on train is 88.777 acceptable? If not acceptable, should I decrease no of epoch?
A: See this answer for more details: whats is the difference between train, validation and test set, in neural networks?
OR if you like pseudo code, this is approximately what it would look like:
for each epoch
for each training data instance
propagate error through the network
adjust the weights
calculate the accuracy over training data
for each validation data instance
calculate the accuracy over the validation data
if the threshold validation accuracy is met
exit training
else
continue training
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: mySQL order by certain values & then DESC? Say I have a mySQL table which has a field named "name"
This field contains one name per row.
There are 10 rows:
Apple
Pear
Banana
Orange
Grapefruit
Pineapple
Peach
Apricot
Grape
Melon
How would I form a query so I select from the table, I want the details to show like this:
Peach
Apple
Apricot
... and then everything else is listed by descending order.
So basically I want to show a few specified results at the TOP of the list, and then the rest of the results in descending order.
Thank you.
A: You could do something like this:
select *
from fruit
order by
case name
when 'Peach' then 1
when 'Apple' then 2
when 'Apricot' then 3
else 4
end,
name
That should work in any SQL database.
A: You can sort with conditionals using the IF() function. The documentation for IF() states:
IF(expr1,expr2,expr3)
If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL) then IF() returns
expr2; otherwise it returns expr3. IF() returns a numeric or string
value, depending on the context in which it is used.
So you can use it to sort specific elements at the top like this:
SELECT *
FROM fruit
ORDER BY
IF(name = 'Peach', 0, 1),
IF(name = 'Apple', 0, 1),
IF(name = 'Apricot', 0, 1),
name DESC
This is a series of orders, with the first taking highest precedence. So if name='Peach', the value will be 0, for all others the value will be 1. Since in default ASC order, 0 comes before 1, this ensures "Peach" will be at the top of the list. The second sort in the series specifies how to break ties for the first sort. In this case, all elements exccept 'Peach' tie in the first sort with the value '1'. And in this case, 'Apple' gets pushed to the top of the tie list, which in reality is the second spot in the total list. Etc... down to the end the last 'name DESC'.
As the other answer points out, CASE() is an alternative to a series of IF()s:
CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...]
[ELSE result] END
The first version returns the result where value=compare_value. The
second version returns the result for the first condition that is
true. If there was no matching result value, the result after ELSE is
returned, or NULL if there is no ELSE part.
A: Since you are using php, you could read your answers into an array, pop the elements you want at the top store them in a temporary array. Sort the original array alphabetically, then prepend the temporary array.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: XMPP / Jingle Voice Library for Android I'm looking for a Jingle library (or app code) that exists on android and supports Voice for Gtalk or any xmpp in general.
I don't really want to write JNI for libjingle. I would prefer something in java /android.
A: Check this repo it should help.
webrtc-jingle-client
A: There is no java port for it. Its better to use the libjingle c .so and use JNI on android.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Connect Credit card reader I want to develop application like this :
http://itunes.apple.com/us/app/paypodd/id341546114?mt=8
I am going to develop one application for credit card reader but i have no idea for connect external device to iPhone. right now i am using ExternalAccessory Class for find connected device but i am not getting any event after connect any Accessory to my iPhone
if anyone has developed this kind of application please provide me the flow
i am really confused..
Thanks .!
A: Do you plan on producing your own credit card reader for the iPhone/iPod? If so, you will probably need to go through Apple's "Made For iPod" (MFi) program. See: http://developer.apple.com/programs/mfi/
If not, your options for connecting the reader to the iOS device are limited. You cannot connect generic USB or Bluetooth devices -- one of the few devices I'm aware of which gets around this is the Square reader, which is a custom hardware device which communicates over the audio jack. Setting this up likely involved a lot of custom audio engineering on Square's part; it is not an easy task, nor is it something that can be done with off-the-shelf parts.
If you have other plans for what type of reader to use, please add details to your question!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to take a picture using command line on webOS on HP touchpad? on webos, I have openssh running and would like to take a picture using the command line script.
I suspect this is going to include some luna-send command, or alternatively a gst-launch
But I am not having any luck with the docs.
webos doesn't have any of the expected capture tools, but I can access the /dev/video0 device.
Edit: i noticed that the touchpad has the ffmpeg utility installed, but it doesn't recognise the video4linux2 format
So far, I am trying Gopherkhan's suggestions with the following code;
luna-send -n 1 palm://com.palm.mediad.MediaCapture/startImageCapture \
'{"path":"/media/internal/foo1.png","options":[{"quality" \
:100,"flash":2,'reviewDuration':0,'exifData':{}}]}'
but its just hanging there doing nothing, after a while is says this;
{"serviceName":"com.palm.mediad.MediaCapture","returnValue":false,"errorCode":-1 \
,"errorText":"com.palm.mediad.MediaCapture is not running."} \
(process:8534): LunaService-CRITICAL **: AppId msg type: 17
A: So to do this with luna-sends is a bit tricky, and technically not supported.
You're probably going to want to hit the MediaCapture library, which can be found on the device here:
/usr/palm/frameworks/enyo/0.10/framework/lib/mediacapture
To include it in your enyo app drop the following in your depends.js:
"$enyo-lib/mediacapture/"
There are three main steps involved.
*
*Initializing the component
*Capturing the image
*Unloading the device.
Here's a sample:
Declare the component in your scene
{
kind: "enyo.MediaCapture", name:"mediaCaptureObj",
onLoaded:"_setUpLoadedState", onInitialized:"_setUpInitializedState",
onImageCaptureStart:"_onImageCaptureStart", onImageCaptureComplete:"_onImageCaptureComplete",
onAutoFocusComplete:"_onAutoFocusComplete", onError:"_handleError",
onElapsedTime:"_onElapsedTime", onVuData:"_onVuDataChange", onDuration:"_onDuration"
}
Call the initialize method:
this.$.mediaCaptureObj.initialize(this.$.ViewPort);
In your onInitialized callback
Use the property bag to locate the number of devices that are available. Typically, the descriptions are "Camera/Camcorder", "Front Microphone", and "User facing camera"
var keyString;
for(var i = 0; i < this.pb.deviceKeys.length; i++)
{
if(this.pb.deviceKeys[i].description.indexOf("Camera/Camcorder") >= 0)
{
keyString = this.pb.deviceKeys[i].deviceUri;
break;
}
}
if(keyString)
{
var formatObj = {
imageCaptureFormat: this.pb[keyString].supportedImageFormats[0]
};
this.$.mediaCaptureObj.load(keyString, formatObj);
}
Take a photo.
var obj = {"exifData":"{\"make\": \"Palm\", \"model\": \"Pre3\", \"datetime\": \"2011:05:19 10:39:18\", \"orientation\": 1, \"geotag\": {}}","quality":90,"flash":"FLASH_ON"};
this.$.mediaCaptureObj.startImageCapture("", obj);
Unload the device:
this.$.mediaCaptureObj.unload();
To do this with the old JS frameworks, see:
https://developer.palm.com/content/api/reference/javascript-libraries/media-capture.html
Now, you can do something similar with luna-send, but again, I don't think it's technically supported. You might have trouble with starting-up/keeping-alive the media capture service, etc. BUT, if you want to try, you could do something along the lines of:
1. get the media server instance --- this returns a port instance number
luna-send -a your.app.id -i palm://com.palm.mediad/service/captureV3 '{"args":["subscribe":true]}'
This will return a location of the capture service with a port number, a la:
{"returnValue":true, "location":"palm://com.palm.mediad.MediaCaptureV3_7839/"}
Since this is a subscription, don't kill the request. Just open a new terminal.
2. Open a new terminal. Use the "location" returned in step 1 as your new service uri:
luna-send -a your.app.id -i palm://com.palm.mediad.MediaCaptureV3_7839/load '{"args":["video:1", {"videoCaptureFormat":{"bitrate":2000000,"samplerate":44100,"width":640,"height":480,"mimetype":"video/mp4","codecs":"h264,mp4a.40"},"imageCaptureFormat":{"bitrate":0,"samplerate":1700888,"width":640,"height":480,"mimetype":"image/jpeg","codecs":"jpeg"},"deviceUri":"video:1"}]}'
You should see:
{"returnValue":true}
if the call completed correctly. You can safely ctrl+c out of this call.
3. Take your picture. (you can ctrl+c out of the last call, and just supply the args here)
luna-send -a your.app.id -i palm://com.palm.mediad.MediaCaptureV3_7839/startImageCapture '{"args":["", {"exifData":"{\"orientation\": 1, \"make\": \"HP\", \"model\": \"TouchPad\", \"datetime\": \"2011:09:22 15:34:36\", \"geotag\": {}}","quality":90,"flash":"FLASH_DISABLED","orientation":"faceup"}]}'
Again, you should see:
{"returnValue":true}
if the call completed correctly.
You should hear a shutter click, and the image will show up in the Photos app, in your Photo Roll.
A: An alternative, which might some benefit of using cross platform tools, is to the use the gst-launch pipeline. So far I have managed to start the web cam using command line;
gst-launch camsrc .src ! video/x-raw-yuv,width=320,height=240,framerate=30/1
! palmvideoencoder ! avimux name=mux ! filesink location=test1.avi alsasrc !
palmaudioencoder
but not take a single image;
gst-launch -v camsrc .src_still take-picture=1 flash-ctrl=2 ! fakesink dump=true
but I can't get it to recognise the .src_still tab. I will update this answer with this alternative method as I proceed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: nginx /admin /login wordpress I want to setup simpler urls in nginx to login into wordpress i.e. /admin /login in nginx
I have tried multiple ways of tackling this with no luck. any ideas?
A: The preferred method is to use NO IF-STMTS:
# Login Short Cut
location ~* /login/ {
rewrite ^/login/(.*)? /wp-admin/$1;
}
A: # Login Short Cut
if ($uri ~* "/login") {
rewrite ^/login(/.*)? /wp-admin$1;
}
A: I'm assuming the above rewrite should allow a user to access the wordpress login screen by visiting mysite.com/login
I've included the above rewrite in the appropriate nginx config file
I'm using Wp-Skeleton which means the directory structure looks like this:
/wp/wp-admin.php
/wp/wp-login.php
When I access mysite.com/login it redirects to mysite.com/wp/wp-login.php
Is my assumption wrong and is there a way to rewrite to the more user friendly /login and /admin urls?
Only solution I can think of is to 301 redirect wp-login.php to /login
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: cant make it resizable to make it more easy
i will put this code have same proplem
<style> p { color:red; margin:5px; cursor:pointer; } </style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$("p.good").click(function () {
$(".res").css("background-color","yellow");
$( ".res" ).resizable();
});
</script>
<table width="100%" border="1" cellspacing="1" cellpadding="1>
<td><div id="1a" class="res">jehad </div></td>
<td> <p class="good">make</p></td>
<td><div class="res">jeyad </div></td>
A: Resizeable is part of the JQuery UI, which is not included in jquery-latest.js.
A: it's work now :)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Resizable - Maximum / minimum size</title>
<link rel="stylesheet" href="http://jqueryui.com/themes/base/jquery.ui.all.css">
<script src="js/jquery.min.js"></script>
<script src="js/jquery-ui-1.8.13.custom.min.js"></script>
<style>
#resizable { width: 440px; height: 150px; padding: 5px; border-right:5px #3C0 solid; }
</style>
<style type="text/css">
.tableres
{
border-collapse:collapse;
}
.tableres, td, th
{
border:1px solid black;
}
.ul1 {
}
</style>
<script>
$('.ul1').live('click', function() {
// Bound handler called.
$(function() {
$( ".ui-widget-content" ).resizable({
maxWidth: 780,
minWidth: 100
});
});
});
</script>
</head>
<body>
<div class="demo">
<table class="tableres" width="880px" cellspacing="0" cellpadding="0">
<tr>
<td width="10%" align="center" valign="top"><div id="resizable" class="ui-widget-content ul1"></div></td>
<td width="90%" align="center" valign="top"><div class="ul1" >make me resize</div></td>
</tr>
</table>
</div><!-- End demo -->
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Working out total from sub total and amount I have a table with purchased orders data.
Each row contails the amount of certain item purchased, cost per item and the order number group. Each different item purchased is a new row with same order number.
I basically want to return the total cost for that order. I have tried the following but am getting nowhere:
SELECT order_number, SUM( sub_total ) AS `total`
FROM
SELECT order_number, SUM( SUM( amount ) * SUM( cost_per_item ) ) AS `sub_total`
FROM `ecom_orders`
WHERE member_id = '4'
GROUP BY order_number
ORDER BY purchase_date DESC
A: Pretty much any SQL-92 compliant RDBMS will take this:
SELECT
order_number
,SUM(amount * cost_per_item) AS total
,purchase_date
FROM
ecom_orders
WHERE member_id = '4'
GROUP BY order_number,purchase_date
ORDER BY purchase_date DESC
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: can't access content of iframe injected via google chrome content script using jquery so I'm creating this chrome extension by injecting a content script into the body:
this is my javascript:
test.js:
$(document).ready(function(){
Url = chrome.extension.getURL('etc.html');
link = '<iframe src="' + Url + '" id="frame" scrolling="no" frameborder="0px"></iframe>';
$('body').prepend(link);
alert($('.test').html());
});
this is the content of etc.html which is supposed to go to the iframe
etc.html:
<div class="test">An html</div>
and this is my manifest.json
manifest.json:
{
"content_scripts": [ {
"all_frames": true,
"js": [ "js/jquery.js", "js/test.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"run_at": "document_end"
} ],
"description": "Testing",
"name": "test",
"permissions": [ "tabs", "http://*/*", "https://*/*", "notifications", "management", "unlimitedStorage", "bookmarks", "contextMenus", "cookies", "geolocation", "history", "idle" ],
"version": "2.0.0.53"
}
the iframe was successfully inserted to the body, the iframe content appears, and I saw it through the chrome inspector...
but then when the js ran the alert($('.test').html()); line, it returned null instead of returning the html....how exactly do I access the contents inside the iframe when developing such extensions
I also tried $('#frame').contents().find('.test').html(); to no avail
A: I'm pretty sure you can't do that.
Right now I can't find anything online to support this but I remember having this issue. I think the reason for it being so is that other scripts and extensions wouldn't mess with your etc.html.
What you can do is have javascript inside etc.html access and modify its DOM. If you then need it to communicate with the content script that injected the iframe you can do so by passing messages through your background page: http://code.google.com/chrome/extensions/messaging.html
For example you can do this with simple one-time requests:
etc.html
chrome.extension.sendRequest(msg)
backround.html
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
chrome.tabs.sendRequest(sender.tab.id, request);
});
contentscript.js
chrome.extension.onRequest.addListener(function(req, sender, sendResponse) {
//do stuff
}
You could do similarly with postMessage and onMessage.
Let me know if you need more help. I use this technique extensively in my extension.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: nginx-gridfs connection failure I have nginx version 1.0.6 with nginx-gridfs module v0.8 installed. I have a testing account on mongohq as mongodb://:@staff.mongohq.com:20127/Test
I set the location attribute in my conf as
location /gridfs/ {
gridfs Test field=_id
type=objectid
user=<user>
pass=<password>;
mongo staff.mongohq.com:20127;
}
when i start nginx i got the following exception and no worker process can start.
Mongo Exception: Connection Failure.
can someone tell me what I did wrong?
Thanks
A: There is no wrong with the configuration. I face the same issue. The solution that I found, I change the hostname into IP and the problem gone :). Try:
> nslookup staff.mongohq.com
Server: 8.8.8.8
Address: 8.8.8.8#53
Non-authoritative answer:
staff.mongohq.com canonical name = ec2-50-17-135-240.compute-1.amazonaws.com.
Name: ec2-50-17-135-240.compute-1.amazonaws.com
Address: 50.17.135.240
Now, we have IP of staff.mongohq.com then change the line:
mongo staff.mongohq.com:20127;
to
mongo 50.17.135.240:20127;
Not sure where the problem is, is it on nginx-gridfs or mongo-c-driver but I am glad now it's working now :D
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Having problems in Playing mp3 files in android I am getting problems in playing audio(mp3) files this music files are like click sounds its residing at the raw folder, the problem is if there are many clicks at random intervals it throws an exception of nullPointer. It occurs anywhere when the click is done and anytime, is it related to the memory issue or MediaPlayer related problem, pls any suggestion will be appreceated.
Its simple media player object that i m calling, but its a games so on touch it plays the files, so in game i have many things to drag so i want a click sound at that time, sometime it works fine but when exceeds certain limit it throws null pointer exceptions. this is the code:
MediaPlayer mp= MediaPlayer.create(context,R.raw.soun1);
mp.start();
thats it:
A: just try this ::
MediaPlayer mp = new MediaPlayer();
mp= MediaPlayer.create(this,R.raw.soun1);
mp.start();
permission in manifest file:::
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
A: To play media player...we need two classes..
let us suppose mainactivity.java is our first file..
here we define two buttons - start_button & stop_button
mButton_start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent mIntent=new Intent(MainActivity.this,maservice.class);
startService(mIntent);
}
});
mButton_stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent mIntent=new Intent(MainActivity.this,maservice.class);
stopService(mIntent);
}
});
maservice.java is our another java file. Here we define media player and also there should be 3 methods: onCreate(), onStart(), onDestroy().
Here is the code:
MediaPlayer mPlayer;
@Override
public void onCreate()
{
super.onCreate();
mPlayer=MediaPlayer.create(this, R.raw.kyun);
mPlayer.setLooping(true);
}
@Override
public void onStart(Intent miIntent, int startid)
{
super.onStart(miIntent, startid);
mPlayer.start();
}
@Override
public void onDestroy()
{
super.onDestroy();
mPlayer.stop();
}
We also have to define these java files in manifest file
*
*mainactivity.java is defined under activity tag
*but maservice.java is defined under service tag
A: I got my answer, its SoundPool, especially created when the concern of game like application where the sound files are used continuously, so here we should use SoundPool except of MediaPlayer.
A: The issue is with the MP3 encoding. I tried with the same code, few work and few don't. So please try with a different one if it shows up the same error next time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Java check to see if a variable has been initialized I need to use something similar to php's isset function. I know php and java are EXTREMELY different but php is my only basis of previous knowledge on something similar to programming. Is there some kind of method that would return a boolean value for whether or not an instance variable had been initialized or not. For example...
if(box.isset()) {
box.removeFromCanvas();
}
So far I've had this problem where I am getting a run-time error when my program is trying to hide or remove an object that hasn't been constructed yet.
A: Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.
Now if you know that once assigned, the value will never reassigned a value of null, you can use:
if (box != null) {
box.removeFromCanvas();
}
(and that also avoids a possible NullPointerException) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:
if (box != null) {
box.removeFromCanvas();
// Forget about the box - we don't want to try to remove it again
box = null;
}
The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):
// Won't compile
String x;
System.out.println(x);
// Will compile, prints null
String y = null;
System.out.println(y);
A: Instance variables or fields, along with static variables, are assigned default values based on the variable type:
*
*int: 0
*char: \u0000 or 0
*double: 0.0
*boolean: false
*reference: null
Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "56"
} |
Q: SSL in Tomcat 7 I am attempting to follow the instructions for setting up SSL in Tomcat 7 for a local app. I don't really understand what I am doing here, so please excuse the n00biness of my approach. I create a key store, as so:
keytool -genkey -alias tomcat -keyalg RSA
Enter keystore password: changeit
Re-enter new password: changeit
What is your first and last name?
[Unknown]: Robert Bram
What is the name of your organizational unit?
[Unknown]: Developers
What is the name of your organization?
[Unknown]: MyBusiness
What is the name of your City or Locality?
[Unknown]: Melbourne
What is the name of your State or Province?
[Unknown]: Victoria
What is the two-letter country code for this unit?
[Unknown]: AU
Is CN=Robert Bram, OU=Developers, O=MyBusiness, L=Melbourne, ST=Victoria, C=AU correct?
[no]: yes
Enter key password for <tomcat>
(RETURN if same as keystore password):
I then added a Connector port to my server.xml:
<Connector port="8443" maxThreads="200"
scheme="https" secure="true" SSLEnabled="true"
keystoreFile="${user.home}/.keystore" keystorePass="changeit"
clientAuth="false" sslProtocol="TLS"/>
I exported the certificate:
keytool -export -alias tomcat -file tomcatcertfile.cer
Enter keystore password: changeit
Certificate stored in file <tomcatcertfile.cer>
I restarted Tomcat. I load my app https://localhost:8443/blah/myapp in IE. It shows a certificate error.
I click on "Certificate Error" in address bar > click on View Certificates > click on Install Certificate > Next > tick Place all certificates in the following store > click Browse > click Trusted Root Certification Authorities > Next > Finish > Yes > OK > OK.
Now when I go to the page I see "The security certificate presented by this website was issued for a different website's address".
So.. what exactly am I doing wrong?
Thanks for any advice!
Rob
:)
A: Instead of entering your name, enter the hostname of the server.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: sum linked list I need to sum a variable inside of my linked list. I've got the following function but I'm getting errors on the line noted. I also think that I may not have finished the if statement correctly to return the summed value to the function.
int print_nodeprice1 (node *headptr, int num) {
int sum = 0;
node *first;
first = *headptr; // getting errors that I can't assign this
while (first != NULL) {
first = first -> next_ptr;
if (num == first -> price1)
return sum;
else {
printf("\n");
}
}
}
A: first = headptr;
this will work..since both are of type (node *)
A: You have a couple issues:
*
*Assign first = headptr, instead of *headptr
*Do your num check at the top of the loop, before setting first =
first->next
*You aren't actually summing anything. Did you mean to increment your
sum variable?
A: first = *headptr; // getting errors that I can't assign this
Correct - you're trying to assign the value (dereference) to a pointer.
first = headptr;
Beyond that ... It's unclear what you mean about "sum a variable inside of my linked list". Your code returns 0 when it finds a price1 that equals the num you pass in.
A: int print_nodeprice1 (node *headptr, int num) {
node *first;
first = *headptr; // getting errors that I can't assign this
first is a pointer to node, headptr is also a pointer to node. Now you try to assign to first the result of derreferencing headptr.
A: You don't need the *. It should be just:
first = headptr;
first and headptr are of type node*. The * operator dereferences them so *headptr is of type node, not node*.
A: first is a pointer to node. headptr is a pointer to node. *headptr is a node. You cannot assign a node to a pointer to node.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Decrypt / Encrypt connection string in web.config in ASP.NET I have a connection string in web.config which custom-encrypted.
I would like to decrypt this during application start (the first page is Login page which is based on a Master page. The login credentials are verified using the encrypted connection string) and it must be encrypted before application closes - by whatever way - either normal close or application error.
I tried to implement using Global.asax but since any changes to web.config restarts application, it went into a loop and hence gave up this method.
Please note that I do not want the default configuration encryption provided by ASP.NET as I use a custom one.
While it is easy to decrypt the connection string during startup, is there really any way to encrypt again during application close?
Many thanks!
A: I am going to risk this as an answer because I can't really see the need for what you describe:
*
*If the connection string is already encrypted in the web.config *_you_don't_need_to_decrypt_it* when the application starts, you just decrypt it every time you instantiate a database connection. Believe me, the performance of decrypting the connection string is negligible even if you do it every time you open a connection. But assuming you are a performance freak and you only want to decrypt it once and put in Session (bad idea, but it appears that that's what you are doing), there's nothing to worry about as I will explain in point 3 below.
*Supposing that you decrypt it once (Application_Start, what have you), why do you say that you need to encrypt it again before application closes - by whatever way - either normal close or application error.? The connection string is not transferred over the wire, it's something that it's used on the server side in order to instantiate a connection to the database but it is not something that someone can see by using the application, unless of course, you store it in ViewState but that would be very silly.
*You mentioned that you store something in Session although is not 100% clear whether you are referring to the connection string or something else. Assuming it is the connection string (again, I can't think of a valid reason for this. I apologize if there's one.) it's not something that any user can see since Session is nothing but memory bytes on the server. The same applies for Cache.
So, that's that.
You decrypt the connection string, instantiate your connection, do your thing and close the connection. The connection string can stay encrypted in web.config for ever; untouched.
UPDATE
Since the OP is using the Membership provider, the solution is to implement your own Membership provider. You can download a sample project demonstrating how to do this from Microsoft at the following link: http://download.microsoft.com/download/a/b/3/ab3c284b-dc9a-473d-b7e3-33bacfcc8e98/ProviderToolkitSamples.msi
Look at the SQLConnectionHelper.cs class.
Here's another post doing pretty much exactly what you need.
UPDATE 2
Here's another way to do the same thing using Reflection. Call it a hack, but it seems to do the job:
Inside Application_PreRequestHandler in Global.asax call this method, where connectionString is your connection string already decrypted:
private void SetProviderConnectionString(string connectionString)
{
// Set private property of Membership, Role and Profile providers. Do not try this at home!!
var connectionStringField = Membership.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
if (connectionStringField != null)
connectionStringField.SetValue(Membership.Provider, connectionString);
var roleField = Roles.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
if (roleField != null)
roleField.SetValue(Roles.Provider, connectionString);
var profileField = ProfileManager.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
if (profileField != null)
profileField.SetValue(ProfileManager.Provider, connectionString);
}
Source.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: TTouchKeyboard: send keystroke to other program? How do I use TTouchKeyboard in Delphi, so it could send keystrokes to other program. For example, I want to type password in a browser using TTouchKeyboard component. I have no idea how make the browser stay focus while I'm clicking on my keyboard.
A: TTouchKeyboard sends the keys to the current control focused: so if you have a TEdit with the focus, the TEdit will receive the key...
You can create a form which contains the TTouchKeyboard and add this procedure:
protected
procedure CreateParams(var Params: TCreateParams); override;
...
procedure TForm1.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
with Params do
begin
ExStyle := ExStyle or WS_EX_NOACTIVATE;
WndParent := GetDesktopwindow;
end;
end;
Your form can't have the focus... so, the key is sent to the previous focused control. (I have just tested it and it works: the key has been sent to this webpage)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Why does a textbox lose its disabled attribute on postback but not its value attribute? This is my program
<script src="Scripts/jquery-1.6.4.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript" language="javascript">
function one() {
$(document).ready(function () {
$('#<%= textbox.ClientID %>').attr('disabled', 'disabled');
});
}
function two() {
$(document).ready(function () {
$('#<%= textbox.ClientID %>').attr('value', 'hello stackoverflow.com!');
});
}
</script>
<input type="button" value="one" onclick="one();" />
<input type="button" value="two" onclick="two();" />
<asp:TextBox ID="textbox" runat="server"></asp:TextBox>
<asp:Button ID="postbackButton" runat="server" Text="post back" />
*
*When I click on 'button one', the textbox switches to disabled. Then I click on 'postback button' and the textbox switches to enabled (It loses what I set!).
*When I click on 'button two', the textbox changes its value. Then I click on 'postback button' and the textbox doesn't lose its value.
How could I do to keep the disabled state of the button?
If I could do this on client-side it would be better..
Thanks a lot, Luciano.
A: ASP.Net keeps track of posted values for you via the ControlState. If you had set the DISABLED state in the code behind (via enabled=false) then it would have been retained via ViewState. If you had set it in the ASPX page, it would just be the value. Since you're doing it via JS, the server has no way to know that it's been set.
one way to handle this is that you could do such things as keep a list of disabled textboxes by name in a hidden field. Then on the post back, you could parse out the value from the hidden field, and set the enabled state of the textbox appropriately in the code behind, allowing ViewState to take care of things.
A: The reason is ViewState. Every changed property value of ASP.NET server control during the page execution will be saved by the ViewState. Read ViewState.
A: Simple reason is you must be doing this.
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Enabled = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Enabled = false;
}
Here you Enabled button in Load event and then disabled it when first button is clicked. Then you hit the second button which is to do the postback it will just go in Page_Load event and Enable the button.
If you simply remove TextBox1.Enabled = true; from Page_Load, PreInit, Init event you will not see this error.
Don't enable disable through JS.
A: If textbox with runat="server" attribute and if it is disable then you cannot change its value using javascript or jquery.It can only change at server side
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: help parsing xml string in perl I'm having trouble doing a match for this xml string in perl.
<?xml version="1.0" encoding="UTF-8"?><HttpRemoteException path="/proj/feed/abc" class="java.io.FileNotFoundException" message="/proj/feed/abc: No such file or directory."/>
I want to place a condition on FileNotFoundException like so:
code snippet:
my @lines = qx(@cmdargs);
foreach my $line (@lines) { print "$line"; }
if (my $line =~ m/(FileNotFoundException)/) {
print "We have an ERROR: $line\n";
}
Error:
Use of uninitialized value in pattern match (m//) at ./tst.pl
A: You never assign anything to the variable against which you match (since you create the variable right there inside the if condition), so it doesn't contain what you say it does.
Use use strict; use warnings;!!!
It would have given you a warning. Remove the my.
A: You should test $lineinside the foreach loop:
my @lines = qx(@cmdargs);
foreach my $line (@lines) {
print "$line";
if ($line =~ m/(FileNotFoundException)/) {
print "We have an ERROR: $line\n";
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to draw a Number to an Image Delphi 7 I have a requirement to draw a number to a image.That number will changes automatically.how can we create an image dynamically in Delphi 7 ?
.If any one knows please suggest me.
Yours Rakesh.
A: You can use the Canvas property of a TBitmap to draw a text in a image
check this procedure
procedure GenerateImageFromNumber(ANumber:Integer;Const FileName:string);
Var
Bmp : TBitmap;
begin
Bmp:=TBitmap.Create;
try
Bmp.PixelFormat:=pf24bit;
Bmp.Canvas.Font.Name :='Arial';// set the font to use
Bmp.Canvas.Font.Size :=20;//set the size of the font
Bmp.Canvas.Font.Color:=clWhite;//set the color of the text
Bmp.Width :=Bmp.Canvas.TextWidth(IntToStr(ANumber));//calculate the width of the image
Bmp.Height :=Bmp.Canvas.TextHeight(IntToStr(ANumber));//calculate the height of the image
Bmp.Canvas.Brush.Color := clBlue;//set the background
Bmp.Canvas.FillRect(Rect(0,0, Bmp.Width, Bmp.Height));//paint the background
Bmp.Canvas.TextOut(0, 0, IntToStr(ANumber));//draw the number
Bmp.SaveToFile(FileName);//save to a file
finally
Bmp.Free;
end;
end;
And use like this
procedure TForm1.Button1Click(Sender: TObject);
begin
GenerateImageFromNumber(10000,'Foo.bmp');
Image1.Picture.LoadFromFile('Foo.Bmp');//Image1 is a TImage component
end;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Increase the stack size of Application in Xcode 4 I want to increase the stack size of an ipad application to 16MB .I have done it in xcode build setting "-WI-stack_size 1000000 to the Other Linker Flags field ".
but getting build error of
i686-apple-darwin10-gcc-4.2.1: stack_size: No such file or directory
i686-apple-darwin10-gcc-4.2.1: 1000000: No such file or directory
How can i resolve that ?
A: Do not know if you got it solved or not, but the correct way to indicate such option to the linker (according to this site) is to add -Wl,-stack_size,1000000 to the Other Linker Flags field of the Build Styles pane. You are missing the commas.
In case you are using clang or gcc the cli would be:
g++ -Wl,-stack_size -Wl,1000000
Hope it helps.
A: If you think you need to increase the stack size you're almost certainly doing something very wrong in your code, like allocating way too large objects on the stack (ie a 16 MByte C array).
Instead, allocate the memory or use the proper Objective-C data structures (ie NSMutableArray).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to backup the installed application's .apk file? How to take backup the installed application's .apk file in device or emulator which we're using by programmatically. Thanks in Advance.
A: I am sure this kind of programming not possible (May be possible for rooted phone), because just consider if this is possible then paid application's Apk can easily available in market in free of charge, so if this is the case then what does it mean to develop paid android application?
Even though, it is possible then i am really interested to learn this programming snippets.
A: Eventually, the Android OS is a Linux OS.
If you have root access to your device, you can copy the protected files and do whatever you want with them.
The APK files are located in the /data folder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Java MySQL - Named Pipe connection throws warning on close I am connecting to MySQL in Java with Connector/J using Named Pipes. My connection and query are successful, but I am receiving a warning when I try to close the connection. I would like to know what I should do to fix whatever is causing the warning other than removing connection.close() (or removing the try-with-resources connection block and not adding a connection.close()).
Here is my code for the query:
public static List<List> QueryDB(int RowValue) {
List<Long> ValueList = new ArrayList();
try {
try (Connection Connection_T = MySQLConnectionResources.createConnection()) {
try (Statement Statement_T = Connection_T.createStatement()) {
String String_T = "SELECT AColumn FROM ATable WHERE BColumn = " + RowValue + ";";
try (ResultSet ResultSet_T = Statement_T.executeQuery(String_T)) {
while (ResultSet_T.next()) {
ValueList.add(ResultSet_T.getLong("AColumn"));
}
}
}
}
} catch(SQLException SQLException_P) {
System.err.println("ERROR: Failed to query the database.");
ValueList.clear();
}
List<List> Result_M = new ArrayList();
Result_M.add(ValueList);
return Result_M;
}
"MySQLConnectionResources" is just a custom class with method "createConnection()". There is nothing special to the class/method; it just creates and returns a connection.
After the method is completed (or technically, after the Java 7 try-with-resources connection block is completed) I receive the following error/warning:
Thu Sep 22 00:31:54 EDT 2011 WARN: Caught while disconnecting...
EXCEPTION STACK TRACE:
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: Socket is not connected
STACKTRACE:
java.net.SocketException: Socket is not connected
at java.net.Socket.shutdownInput(Socket.java:1456)
at com.mysql.jdbc.MysqlIO.quit(MysqlIO.java:1687)
at com.mysql.jdbc.ConnectionImpl.realClose(ConnectionImpl.java:4368)
at com.mysql.jdbc.ConnectionImpl.close(ConnectionImpl.java:1557)
at ... my class/method here (my class.java:#)
** END NESTED EXCEPTION **
If I remove the try-with-resources block (and don't add a connection.close()), the warning never appears. Also, if I switch to a TCP/IP connection the error never appears. BUT, neither of these solutions are satisfactory for my case. I want to ensure that the connection is properly closed and I will be using named pipe connections.
Any ideas?
-- (edit) --
Also: The error is being thrown by the Log within Connector/J. My error catching has nothing to do with how the error is being caught and printed. I've tried to research how to disable the WARN problems and have it print out just SEVERE problems (within Connector/J's Log), but I was unsuccessful. Furthermore, I would like to fix the WARN problem rather than ignore/conceal it.
-- (edit 2) --
I monitored the MySQL database and the connections aren't being closed. If I use a TCP/IP connection string rather than my named pipe connection string (and don't change anything else) the connection is closed just fine.
-- (edit 3) --
Ignoring my original code... just try the code below and it throws the warning. Seems like a bug to me.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public final class main {
public static void main(String[] args) {
Connection conn = null;
try {
conn =
DriverManager.getConnection("jdbc:mysql:///database?socketFactory=com.mysql.jdbc.NamedPipeSocketFactory&namedPipePath=\\\\.\\Pipe\\mysql.sock",
"root", "password");
conn.close();
} catch (SQLException ex) {
// handle any errors
}
}
}
A: As it appears to be a bug, I have submitted an official bug report to the MySQL bugs forum.
I will post back here whenever I receive an update.
UPDATE:
My bug report was analyzed by MySQL coders. They believe it is a JAVA bug.
Bug Report
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to get the user name and password from my app? I want to get the user name and password from my devise as shown in the attached image.Can somebody please give me any suggestions.
A: You should use Settings Bundle.
A: I assume that you have created setting bundle in your application.
then just write:
[[NSUserDefaults standardUserDefaults] stringForKey:@"username"]
[[NSUserDefaults standardUserDefaults] stringForKey:@"password"]
and you get the value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get the nodes containg an attribute with a certain value in XML in XPath i want to find nodes containg an attribute with a certain value in XML . I tried with a certain Xpath expression but it wont work..
String expression = ".*[@*[starts-with(., '"+search+"')]]";
Here the search is the variable which contains the value which i want to search. Can anyone tell me the right Xpath expression.
Thanks.
A: Your expression is correct, only the .* makes no sense.
String expression = "//*[@*[starts-with(., '"+search+"')]]";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Initial VoiceOver selection I'm adding VoiceOver support to my app. So far, so good, but I'd really like to be able to specify which element is the first one spoken after a UIAccessibilityScreenChangedNotification. I haven't seen a way to do this. Making something the summary element doesn't really seem to do it. Am I missing something?
A: This has always been perfectly possible to do.
Just write something along the lines of:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification,
self.myFirstElement);
}
@end
This works for both UIAccessibilityScreenChangedNotification and UIAccessibilityLayoutChangedNotification.
Now for Swift 5
override func viewDidAppear(_ animated: Bool) {
UIAccessibility.post(notification: UIAccessibility.Notification.screenChanged,
argument: myFirstElement)
}
A: I don't think there is an API value that specifies an order of reading, other than using Summary Element value on startup - it is by design.
So you would have to test the order and default for the UIKit elements or any custom controls, because it depends on your design. You can also mark items as non-accessible elements so they won't be 'read', accessible elements read by default, and containers for accessible elements to allow you to better control your intended interactions. I don't know if making the item selected will help.
I take it you are already using the Accessibility Inspector to test your application before testing on iOS.
If you are needing some background on the subject, Rune's Working With VoiceOver Support and Gemmell's Accessibility for Apps may be worth reading.
A: What about using UIAccessibilityAnnouncementNotification?
A: This technique worked for me.
VoiceOver will announce the value of the first element in the accessibleElements array. This can be sorted to suit your needs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: How do I clear the page content after a form is submitted? I currently have this code in my project:
require_once('mysql.inc.php');
session_start();
if (!isset($_SESSION['username']) && !isset($_SESSION['uid']))
{
login_sequence();
}
else
{
login_check($_SESSION['username'], $_SESSION['uid']);
}
function login_sequence()
{
echo '<p>' . $pretext . '</p><form method="post" action="" /><label for="password">Password: </label><input type="password" name="password" id="password" /><input type="submit" value="Log In" /><input type="hidden" name="submitted" /></form>';
if (isset($_POST['submitted']))
{
$pword = hash('sha256', $_POST['password']);
$query = "SELECT pword FROM users WHERE user = 'guest'";
$result = mysql_query($query);
$return = mysql_fetch_assoc($result);
if ($return['pword'] == $pword)
{
pageout();
}
else
{
echo 'You entered the wrong password, if you are not a member, please leave.';
}
}
}
function login_check($username, $uid)
{
}
function pageout()
{
echo('
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="" />
</head>
<body>
<div id="header">
<p>WOOT</P>
</div>
<div id="">
</div>
<div id="navigation">
</div>
<div id="footer">
</div>
</body>
</html>
');
}
?>
There is a single "Guest" password stored in a database, it accesses the database and checks the password entered by the user against the one stored in the database. I want to have it so after the form is submitted and the information is correct, on the same page the form disappears and the page appears. How do I do it? How do I get rid of the form to make room for the new page?
A: header(location ...) on success, or a page display conditional on log in settings
A: simply do
at the end of your form and at the php code do this
if(!isset($_POST['s'])){
?>
your form here
<?php
}
else //form handle
A: I would make structure look slightly different:
//First
if (!isset($_POST['submitted'])) {
//include your form only
} else {
//Check if user submitted correct password
//If password is correct
if ($return['pword'] == $pword) {
pageout();
//OR write pageout code on different page and call header("Location: Yourpage.php");
} else {
//Include form or inform user about password mismatch
}
}
edit. Also if you use header("Location:") function make sure you're not echoing or including anything that outputs data. This will cause Headers already sent error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Compile C++ source to a .dll I am trying to create a simple example with JNI. I am having trouble compiling the .cpp source file. I will give all the steps that I have done/tried below. I am trying to follow the tutorial found here: http://java.sun.com/docs/books/jni/html/start.html#27008
I have a Java program called HelloJNI.java
public class HelloJNI
{
private native void print();
public static void main(String[] args)
{
new HelloJNI().print();
}
static
{
System.loadLibrary("HelloJNI");
}
}
From here I compiled the java file and called
javah -jni HelloJNI to generate HelloJNI.h
From here I create the .cpp source file
#include <jni.h>
#include <iostream>
#include "HelloJNI.h"
using namespace std;
JNIEXPORT void JNICALL
Java_HelloJNI_print(JNIEnv *env, jobject obj)
{
cout << "Hello JNI!" << endl;
return;
}
Now that I have all of that I try to create the .dll from the source file, I am using this command to run gcc on cygwin (found this command here - http://www.inonit.com/cygwin/jni/helloWorld/c.html):
gcc -mno-cygwin -I$JAVA_HOME/include -I$JAVA_HOME/include/win32
-Wl,--add-stdcall-alias -shared -o HelloJNI.dll HelloJNI.c
When I do this I get an error:
HelloJNI.cpp:1:17: fatal error: jni.h: No such file or directory
compilation terminated.
This is where I am stuck, I don't really know whey the compiler can't find jni.h it is in the $JAVA_HOME/include directory.
Results from ls $JAVA_HOME/include:
classfile_constants.h jdwpTransport.h jvmti.h win32
jawt.h jni.h jvmticmlr.h
I know it is a lengthy post, but any help would be awesome.
Thanks
A: I use the following flags to compile:
JDK = "c:/Program Files/Java/jdk1.5.0_22/"
CFLAGS=-Wall -DGCC -DWINDOWS -I$(JDK)/include/win32 -I$(JDK)/include
However, I should mention that I was not able to run my JNI application if the dll was compiled with cygwin gcc. I compiled with the Visual Studio then and it worked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: MsTest, DataSourceAttribute - how to get it working with a runtime generated file? for some test I need to run a data driven test with a configuration that is generated (via reflection) in the ClassInitialize method (by using reflection). I tried out everything, but I just can not get the data source properly set up.
The test takes a list of classes in a csv file (one line per class) and then will test that the mappings to the database work out well (i.e. try to get one item from the database for every entity, which will throw an exception when the table structure does not match).
The testmethod is:
[DataSource(
"Microsoft.VisualStudio.TestTools.DataSource.CSV",
"|DataDirectory|\\EntityMappingsTests.Types.csv",
"EntityMappingsTests.Types#csv",
DataAccessMethod.Sequential)
]
[TestMethod()]
public void TestMappings () {
Obviously the file is EntityMappingsTests.Types.csv. It should be in the DataDirectory.
Now, in the Initialize method (marked with ClassInitialize) I put that together and then try to write it.
WHERE should I write it to? WHERE IS THE DataDirectory?
I tried:
File.WriteAllText(context.TestDeploymentDir + "\\EntityMappingsTests.Types.csv", types.ToString());
File.WriteAllText("EntityMappingsTests.Types.csv", types.ToString());
Both result in "the unit test adapter failed to connect to the data source or read the data". More exact:
Error details: The Microsoft Jet database engine could not find the
object 'EntityMappingsTests.Types.csv'. Make sure the object exists
and that you spell its name and the path name correctly.
So where should I put that file?
I also tried just writing it to the current directory and taking out the DataDirectory part - same result. Sadly, there is limited debugging support here.
A: Please use the ProcessMonitor tool from technet.microsoft.com/en-us/sysinternals/bb896645. Put a filter on MSTest.exe or the associate qtagent32.exe and find out what locations it is trying to load from and at what point in time in the test loading process. Then please provide an update on those details here .
A: After you add the CSV file to your VS project, you need to open the properties for it. Set the Property "Copy To Output Directory" to "Copy Always". The DataDirectory defaults to the location of the compiled executable, which runs from the output directory so it will find it there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: OpenCV: cvWarpAffine unhandled exception The code is:
CvMat *rotMapMat = cvCreateMat(2, 3, CV_32SC1);
cv2DRotationMatrix(center, angle, 1, rotMapMat);
cvWarpAffine(image, dst, rotMapMat);
First problem: The cv2DRotationMatrix is not correctly computing the matrix.
Then I've changed that function by my version cv2DRotationMatrixOwn
But there is another problem, the second: The cvWarpAffine always fails with unhandled exception error.
And I can't use debugger and call stack doesn't show the needed functions called before the place when an error occured.
Why does it happen?
Size of st image is made big enough.
EDIT1: Opencv version 2.2
A: rotMapMat has to be floating-point matrix. CV_32S type is not supported by cv2DRotationMatrix and cvWarpAffine. Change it to CV_32F to fix your problems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Hide the pointstyle displayed at bottom of chart I am using achartengine-0.7.0.jar in my project..
By default it displays pointstyle("Diamond","X","Point","Square",etc) at the bottom-left corner of chart (which shows which point style is used)
But I don't want to show this in my chart..
Is there any method For hiding this???
Thanks in advance.
A: Add renderer.setShowLegend(false) in your code. It will hide the points at the bottom.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: selecting drop-down value in xsl How to select the drop down value ? Am trying to display some data whenever I select some value in a drop-down in xsl. For example, If A is selected in the drop-down, details pertaining to A will be displayed in a table. Similarly, if B is selcted, only details relevant to B will be displayed. I need to write a line of code in xslt to select the drop down value in an if statement.
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head>
<title>VPGate Media Mixer</title>
<meta http-equiv="expires" content="0"/>
<meta http-equiv="pragma" content="no-cache"/>
<meta http-equiv="cache-control" content="no-cache, must-revalidate"/>
<meta http-equiv="refresh" content="15"></meta>
<script src="/Common/common.js\" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style001.css" />
<link rel="stylesheet" type="text/css" href="Grid.Default.css" />
</head>
<body class="WorkArea">
<div class="divSummaryHeader" id="SummaryHeader">
<h1>Media Mixer - VPGate</h1>
</div>
 
<div class="RadGrid RadGrid_Default" id="SummaryData" style="position:absolute;width:828px;height:510px;overflow:auto">
<table border="0" class="rgMasterTable rgClipCells" cellspacing="0" cellpadding="0" >
<tr>
<input type="button" class="formEditBtn" id="SubBtn" value="Refresh" onclick="window.location=window.location;"/>
</tr>
<tr>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;" colspan="2">Conference Summary</td>
</tr>
<tr>
<td>
<table border="0" class="rgMasterTable rgClipCells" cellspacing="0" cellpadding="0" >
<tr>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Conference Name</td>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Conference ID</td>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Composite Address</td>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Composite Port</td>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Composite Ssrc</td>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">No Of Participants</td>
</tr>
<xsl:if test="MediaMixer!= ''">
<xsl:for-each select="MediaMixer/Conference">
<!--<xsl:sort select="Name"/>-->
<xsl:if test="Name !=''">
<xsl:if test="(position() mod 2 = 0)">
<tr class="rgAltRow SummaryTableDataRow">
<td valign = "top">
<xsl:value-of select="Name"/>
</td>
<td valign = "top">
<xsl:value-of select="ConfId"/>
</td>
<td valign = "top">
<xsl:value-of select="CompositeAddress"/>
</td>
<td valign = "top">
<xsl:value-of select="CompositePort"/>
</td>
<td valign = "top">
<xsl:value-of select="CompositeSsrc"/>
</td>
<td valign = "top">
<xsl:value-of select="NoOfParticipants"/>
</td>
</tr>
</xsl:if>
<xsl:if test="(position() mod 2 = 1)">
<td>
<tr class="rgRow SummaryTableDataRow">
<td valign = "top">
<xsl:value-of select="Name"/>
</td>
<td valign = "top">
<xsl:value-of select="ConfId"/>
</td>
<td valign = "top">
<xsl:value-of select="CompositeAddress"/>
</td>
<td valign = "top">
<xsl:value-of select="CompositePort"/>
</td>
<td valign = "top">
<xsl:value-of select="CompositeSsrc"/>
</td>
<td valign = "top">
<xsl:value-of select="NoOfParticipants"/>
</td>
</tr>
</td>
</xsl:if>
</xsl:if>
</xsl:for-each>
</xsl:if>
<xsl:if test="MediaMixer = ''">
<td valign = "top">
<xsl:text>No Data </xsl:text>
</td>
</xsl:if>
</table>
</td>
</tr>
</table>
 
<div align="center">
<b> Please select a Conference Name :</b>
 
<select name="combo" id="combo">
<xsl:for-each select="MediaMixer/Conference">
<option>
<xsl:value-of select="Name"/>
</option>
</xsl:for-each>
</select>
</div>
<script type="text/C#" runat="server">
</script>
<table border="0" class="rgMasterTable rgClipCells" cellspacing="1" cellpadding="1">
<tr>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;" colspan="2">Conference Details</td>
</tr>
<tr>
<td>
<table border="0" class="rgMasterTable rgClipCells" cellspacing="0" cellpadding="0" >
<tr>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Conference Name</td>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Conference ID</td>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Participant ID 1</td>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Participant ID 2</td>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Participant Address</td>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Participant Listening Port</td>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">MM Listening Port</td>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">SSRC From Participant</td>
<td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">SSRC From MM</td>
</tr>
<xsl:if test="MediaMixer!= ''">
<xsl:for-each select="MediaMixer/Conference">
<xsl:if test="Name='combo.SelectedValue'">
<xsl:for-each select="Participant">
<xsl:if test="(position() mod 2 = 0)">
<tr class="rgAltRow SummaryTableDataRow">
<td valign = "top">
<xsl:value-of select="../Name"/>
</td>
<td valign = "top">
<xsl:value-of select="../ConfId"/>
</td>
<td valign = "top">
<xsl:value-of select="translate(ID1,
'abcdefghijklmnopqrstuvwxyz',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ')" />
</td>
<td valign = "top">
<xsl:value-of select="ID2"/>
</td>
<td valign = "top">
<xsl:value-of select="ParticipantAddress"/>
</td>
<td valign = "top">
<xsl:value-of select="ParticipantListeningPort"/>
</td>
<td valign = "top">
<xsl:value-of select="MMListeningPort"/>
</td>
<td valign = "top">
<xsl:value-of select="SSRCFromParticipant"/>
</td>
<td valign = "top">
<xsl:value-of select="SSRCFromMM"/>
</td>
</tr>
</xsl:if>
<xsl:if test="(position() mod 2 = 1)">
<td>
<tr class="rgRow SummaryTableDataRow">
<td valign = "top">
<xsl:value-of select="../Name"/>
</td>
<td valign = "top">
<xsl:value-of select="../ConfId"/>
</td>
<td valign = "top">
<xsl:value-of select="translate(ID1,
'abcdefghijklmnopqrstuvwxyz',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ')" />
</td>
<td valign = "top">
<xsl:value-of select="ID2"/>
</td>
<td valign = "top">
<xsl:value-of select="ParticipantAddress"/>
</td>
<td valign = "top">
<xsl:value-of select="ParticipantListeningPort"/>
</td>
<td valign = "top">
<xsl:value-of select="MMListeningPort"/>
</td>
<td valign = "top">
<xsl:value-of select="SSRCFromParticipant"/>
</td>
<td valign = "top">
<xsl:value-of select="SSRCFromMM"/>
</td>
</tr>
</td>
</xsl:if>
</xsl:for-each>
</xsl:if>
</xsl:for-each>
</xsl:if>
<xsl:if test="MediaMixer= ''">
<td valign = "top">
<xsl:text>No Data </xsl:text>
</td>
</xsl:if>
</table>
</td>
</tr>
</table>
 
<div style="display:none">
<iframe id="frameUpdate" name="frameUpdate" width="100%"></iframe>
</div>
</div>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
A: If you are building a HTML page out of XML data with client side XSLT in the Browser, be aware that XSLT can only define the transformation process. When the HTML is ready, XSLT has finished its job. What you can do is to insert javascript into the XSLT source, that reacts on drop-down changes and hides the inappropiate data. The XSLT can't communicate with the Javascript, because the Javascript will begin to work after the page is complete and XSLT is already finished. But it can fit the javascript into the HTML source. Just imagine how to work this out in plain HTML without XSLT and let XSLT build this HTML.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google map - Multiple marker I am trying to set multiple markers, getting address fetching from database and storing it to javascript array variable, then by running a loop trying to set markers in my map, but its not working.
This is my working URL : http://projects.pronixtech.net/kindcampaign/kind-country/
Please look to the source code, and please guys help me i have already given my full day on this.
A: FYI There is a JS error on your page i.e it could not find $(".videopan") i guess and you need not do the replace of px etc for parsing you could do
parseInt($(".videopan").css("left"))
i.e
parseInt("50px")=50
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to increase length of a String in mysql while mapping using JPA I'm having some trouble in JPA. I would be really thankful if someone could provide a solution. WIth JPA (I'm using MySQL DB), lets say, I have a class mapped as follows:
@Entity
class Employee{
int id;
String employeeName;
//getters and setters...
}
when mapping to the table, I see that String is mapped with varchar(255) in Mysql. However, lets say if I have an employee whose name is more than 255 chars, it shows data truncation error.
I know we could solve this by adding "length" attribute to the Employee column as:
@column(length=1000)
String employeeName;
Is this the only possible way? I thought, if we just map to String in java, the database would dynamically assign length.
A: varchar columns support lengths of dynamic size (no padding like with char) but you have to specify the max column size if you want something besides 255. Different dbs have different limits on char and varchar size (8k or 65k is common).
If you want to go beyond this limit you need to add a @Lob annotation to you string so that it'll map to a CLOB column type (assuming you are letting JPA generate tables). CLOB/BLOB columns can be much larger than varchar (again, exact limits depend on your DB). But LOBs have limitations such as not being primary keys or used in WHERE clauses.
A:
when mapping to the table, I see that String is mapped with varchar(255) in Mysql
This is because the default length of VARCHAR columns in DDL statements created by most JPA providers (including Hibernate and EclipseLink) is 255. Specifying the length attribute to the @Column annotation helps override the value, so that the new value is picked up by the schema generator of the JPA provider.
I thought, if we just map to String in java, the database would dynamically assign length.
This is an incorrect assumption. The JPA provider will create tables only once, and will not dynamically change the length of the underlying table during the lifetime of the application, and only if you configure the provider to create/update the table definitions in the first place. Moreover, the default mapping of String is the SQL VARCHAR type.
You seem to have configured the JPA provider to create tables as needed (after possibly dropping them), during the initialization process. If you're using Hibernate, this is done using the hibernate.hbm2ddl.auto property specified in persistence.xml with a value of update, create or create-drop. With EclipseLink, you would be specifying the property eclipselink.ddl-generation with a value of create-tables or drop-and-create-tables.
Both of the above properties are not recommended for use in a production environment. The ideal approach is to have DDL scripts to create the tables. Since, you are using VARCHAR, you ought to specify a suitable length in the column definition, to fit the maximum length of the user input. Additionally, since you are using VARCHAR over CHAR, the database engine will ensure that the storage space allocated will depend on the size of the records being stored.
If you do not need a String to the default VARCHAR mapping and instead use another valid mapping, then you must use columnDefinition attribute of the @Column annotation. An example usage for mapping Calendar to the TIMESTAMPTZ SQL datatype is shown in the JPA WikiBook; you'll need to modify this to suit your need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Multiple Membership Provider in web.config I've a WCF web the config file which requires multiple membership provider due to reason below:
1. One membership for WCF which uses application A.
e.g.
<add name="MySqlMembershipProvider1"
connectionStringName="ApplicationServices"
applicationName="ApplicationA"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
type="System.Web.Security.SqlMembershipProvider" />
*
*The other membership for creating and updating asp.net users.
<add name="MySqlMembershipProvider2"
connectionStringName="ApplicationServices"
applicationName="ApplicationB"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
type="System.Web.Security.SqlMembershipProvider"
/>
How do I specify the provider name on above scenario.
A: SqlMembershipProvider p1 = SqlMembershipProvider)
Membership.Providers["MySqlMembershipProvider1"];
....//
then using the membership providers's instance p1 for Application you can do whatever you need
SqlMembershipProvider p2 = (SqlMembershipProvider)
Membership.Providers["MySqlMembershipProvider2"];
....//
please see this link
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Batch editing without rebing Telerik MVC Grid We are currently using Telerik MVC Grid and we are using the batch editing. Everything works fine from updating, paging, sorting, filtering and grouping what I dont understand is that why when you update something the whole data is refreshed (grid is expecting data to work properly). Is there a property we can set in the telerik grid not to update the whole data (this is so useful if you dont have an add and delete record), it is in client already anyways.
A: I had solved this by returning a blank model back to the grid and removing the small red arrow by javascript. So instead of returning
return View(new GridModel<MyViewModel>);
I return as
return new LargeJsonResult
{
MaxJsonLength = int.MaxValue,
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet,
Data = new GridModel<MyViewModel>
{
Data = model.MyViewModel
}
};
And that Large JSON Result came from here
http://www.java2s.com/Open-Source/ASP.NET/AJAX/ajaxmapdataconnector/DataConDemoWebRole/Business/LargeJsonResult.cs.htm
Having said that on my method instead of the normal ActionResult
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult UpdateSomethingAjax(
[Bind(Prefix = "inserted")]IEnumerable<MyViewModel> insertedTransactions,
[Bind(Prefix = "updated")]IEnumerable<MyViewModel> updatedTransactions,
[Bind(Prefix = "deleted")]IEnumerable<MyViewModel> deletedTransactions)
I return it as
[AcceptVerbs(HttpVerbs.Post)]
public LargeJsonResult UpdateSomethingAjax(
[Bind(Prefix = "inserted")]IEnumerable<MyViewModel> insertedTransactions,
[Bind(Prefix = "updated")]IEnumerable<MyViewModel> updatedTransactions,
[Bind(Prefix = "deleted")]IEnumerable<MyViewModel> deletedTransactions)
without the GridAction
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP explode string by html tag Suppose string $a holds
<p>Phasellus blandit enim eget odio euismod eu dictum quam scelerisque.
</p><p>Sed ut diam nisi.</p><p>Ut vestibulum volutpat luctus.</p>
How can I explode this into this array
Array(
[0] = '<p>Phasellus blandit enim eget odio euismod eu dictum quam scelerisque.</p>';
[1] = '<p>Sed ut diam nisi. Ut vestibulum volutpat luctus.</p>';
[2] = '<p>Ut vestibulum volutpat luctus.</p>';
)
A: Using DOMDocument and DOMXPath (a bit overkill if only a simple solution is needed):
$dom = new DOMDocument();
$dom->loadHTML($a);
$domx = new DOMXPath($dom);
$entries = $domx->evaluate("//p");
$arr = array();
foreach ($entries as $entry) {
$arr[] = '<' . $entry->tagName . '>' . $entry->nodeValue . '</' . $entry->tagName . '>';
}
print_r($arr);
A: <?php
$ps = array();
$count = preg_match_all('/<p[^>]*>(.*?)<\/p>/is', $a, $matches);
for ($i = 0; $i < $count; ++$i) {
$ps[] = $matches[0][$i];
}
That could be one way. Or you could use a loop with strpos
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Converting ArgoUML to SQL I was wondering if there any program that can convert ArgoUML files into sql code?
Thanks
A: Try argouml-db. It uses this plugin for argo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Error in Window application when it will call WCF I have developed window application and in that i am calling WCF at particular time interval however there is no error in inserting data into database through WCF but in log entry i am getting one error regarding WCF Endpoint as per below
2011-22-09 10:16>>Error: There was no endpoint listening at
myserviceUrl(.svc) that could accept the message. This is often
caused by an incorrect address or SOAP action. See InnerException, if
present, for more details.
app.config file as per below and i guess that probably error should be in below configuration
<client>
<endpoint address="myserviceUrl(.svc)"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IApicaAzureMonitorAgentReceiverWCF"
contract="Dashboard2WCFData.IApicaAzureMonitorAgentReceiverWCF"
name="BasicHttpBinding_IApicaAzureMonitorAgentReceiverWCF" />
</client>
Below is my (WCF)service's configuration..
<configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</configSections>
<dataConfiguration defaultDatabase="Connectionstr"/>
<connectionStrings>
<add name="Connectionstr" connectionString="myconnectionstring"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Please help me to sort out of this issues.
Thanks.
A: You need to specify in address attribute the whole virtual path
for example http://localhost/yousite/myservice.svc
A: You need to make sure that the endpoint is configured at the service side, not just your client. In other words, if the client uses myserviceUrl(.svc), the address needs to be specified in the service's config file.
Based on the error message you got, try this in the service's config file:
<endpoint address="myserviceUrl(.svc)"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IApicaAzureMonitorAgentReceiverWCF"
contract="Dashboard2WCFData.IApicaAzureMonitorAgentReceiverWCF"
name="BasicHttpBinding_IApicaAzureMonitorAgentReceiverWCF" />
Note that you'll need to ensure your service has the appropriate binding section named "BasicHttpBinding_IApicaAzureMonitorAgentReceiverWCF".
If you need a more thorough example, post your service's config file and we'll help you out.
UPDATE
Add an endpoint section, and a binding section if you have any values set to other than the default values:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<services>
<service name="myServiceName">
<endpoint address="myserviceUrl(.svc)"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IApicaAzureMonitorAgentReceiverWCF"
contract="Dashboard2WCFData.IApicaAzureMonitorAgentReceiverWCF"
name="BasicHttpBinding_IApicaAzureMonitorAgentReceiverWCF"/>
<endpoint name="mexHttpBinding"
contract="IMetadataExchange"
binding="mexHttpBinding"
address="mex" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IApicaAzureMonitorAgentReceiverWCF" />
</basicHttpBinding>
</bindings>
In the <binding name="" section is where you'd set the values for the binding. If you don't do this (and don't specify the section in the endpoint's bindingConfiguration attribute) WCF will use the default values for basicHttpBinding.
NOTE: With WCF 4.0 and later, you actually don't need to specify an endpoint (or create a .svc file if hosting under IIS), as WCF will supply a default endpoint based on the URI of the service. See A Developer's Introduction to Windows Communication Foundation 4 for details on this and other new features in 4.0.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java GridBagLayout automated construction I designed a GUI using GridBagLayout and GridBagConstraints. It contains a variable number of rows, each with one of a few possible column layouts. To test the code, I comprised the GUI of panels with different colors that illustrate the location and resizing behavior of all the cells in each row and column. This test GUI works fine, but now I need to automate its construction. Specifically, I need the rows to be one of three different types. If you run the code below and look at the resulting GUI, you can see that row1 is one type, rows 2,6,and7 are another type, and rows 3,4,and5 are yet a third type. I need each of these three types of rows to be encapsulated in its own class. What's more, I need my code to be able to create a variable number of rows of the third type (illustrated by rows 3,4,and5 in the example). (This is for data analysis software. The panels will load data views and tools for manipulating the data views.)
When I try to encapsulate the rows into their own classes, the GUI stops looking like it should look. The test code below generates a GUI layout the way that it should look. Can anyone show me how to alter this code so that it has the functionality described in the first paragraph above?
You can just paste my test code below into your IDE to get it working right away. The test code is in two separate files, as follows:
The code for GridBagLayoutDemo.java is:
import java.awt.*;
import javax.swing.JFrame;
public class GridBagLayoutDemo {
final static boolean RIGHT_TO_LEFT = false;
public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);}
pane.setLayout(new GridBagLayout());
// top row (fill, gridx, gridy, gridwidth 1, weightx 0, weighty 0, ipady 0)
TestPanel panelr1c1 = new TestPanel(Color.black);
GridBagConstraints constraint_r1c1 = getGridBagConstraints(GridBagConstraints.NONE,0,0,1,0,0,0);
pane.add(panelr1c1,constraint_r1c1);
TestPanel panelr1c2 = new TestPanel(Color.blue);
GridBagConstraints constraint_r1c2 = getGridBagConstraints(GridBagConstraints.HORIZONTAL,1,0,1,0.8,0,0);
pane.add(panelr1c2,constraint_r1c2);
TestPanel panelr1c2a = new TestPanel(Color.green);
GridBagConstraints constraint_r1c2a = getGridBagConstraints(GridBagConstraints.HORIZONTAL,2,0,1,0.8,0,0);
pane.add(panelr1c2a,constraint_r1c2a);
TestPanel panelr1c3 = new TestPanel(Color.red);
GridBagConstraints constraint_r1c3 = getGridBagConstraints(GridBagConstraints.NONE,3,0,1,0,0,0);
pane.add(panelr1c3,constraint_r1c3);
TestPanel panelr1c4 = new TestPanel(Color.blue);
GridBagConstraints constraint_r1c4 = getGridBagConstraints(GridBagConstraints.NONE,4,0,1,0,0,0);
pane.add(panelr1c4,constraint_r1c4);
// second row (fill, gridx, gridy, gridwidth 1, weightx 0, weighty 0, ipady 0)
TestPanel panelr2c1 = new TestPanel(Color.magenta);
GridBagConstraints constraint_r2c1 = getGridBagConstraints(GridBagConstraints.NONE,0,1,1,0,0,0);
pane.add(panelr2c1,constraint_r2c1);
TestPanel panelr2c2 = new TestPanel(Color.pink);
GridBagConstraints constraint_r2c2 = getGridBagConstraints(GridBagConstraints.HORIZONTAL,1,1,2,1.0,0,0);
pane.add(panelr2c2,constraint_r2c2);
TestPanel panelr2c3 = new TestPanel(Color.black);
GridBagConstraints constraint_r2c3 = getGridBagConstraints(GridBagConstraints.NONE,3,1,1,0,0,0);
pane.add(panelr2c3,constraint_r2c3);
TestPanel panelr2c4 = new TestPanel(Color.pink);
GridBagConstraints constraint_r2c4 = getGridBagConstraints(GridBagConstraints.NONE,4,1,1,0,0,0);
pane.add(panelr2c4,constraint_r2c4);
// third row (fill, gridx, gridy, gridwidth 1, weightx 0, weighty 0, ipady 0)
TestPanel panelr3c1 = new TestPanel(Color.gray);
GridBagConstraints constraint_r3c1 = getGridBagConstraints(GridBagConstraints.VERTICAL,0,2,1,0,0.5,40);
pane.add(panelr3c1,constraint_r3c1);
TestPanel panelr3c2 = new TestPanel(Color.orange);
GridBagConstraints constraint_r3c2 = getGridBagConstraints(GridBagConstraints.BOTH,1,2,2,1.0,0.5,40);
pane.add(panelr3c2,constraint_r3c2);
TestPanel panelr3c3 = new TestPanel(Color.red);
GridBagConstraints constraint_r3c3 = getGridBagConstraints(GridBagConstraints.VERTICAL,3,2,1,0,0.5,40);
pane.add(panelr3c3,constraint_r3c3);
TestPanel panelr3c4 = new TestPanel(Color.orange);
GridBagConstraints constraint_r3c4 = getGridBagConstraints(GridBagConstraints.VERTICAL,4,2,1,0,0.5,40);
pane.add(panelr3c4,constraint_r3c4);
// fourth row (fill, gridx, gridy, gridwidth 1, weightx 0, weighty 0, ipady 0)
TestPanel panelr4c1 = new TestPanel(Color.black);
GridBagConstraints constraint_r4c1 = getGridBagConstraints(GridBagConstraints.VERTICAL,0,3,1,0,0.5,40);
pane.add(panelr4c1,constraint_r4c1);
TestPanel panelr4c2 = new TestPanel(Color.white);
GridBagConstraints constraint_r4c2 = getGridBagConstraints(GridBagConstraints.BOTH,1,3,2,1.0,0.5,40);
pane.add(panelr4c2,constraint_r4c2);
TestPanel panelr4c3 = new TestPanel(Color.green);
GridBagConstraints constraint_r4c3 = getGridBagConstraints(GridBagConstraints.VERTICAL,3,3,1,0,0.5,40);
pane.add(panelr4c3,constraint_r4c3);
TestPanel panelr4c4 = new TestPanel(Color.blue);
GridBagConstraints constraint_r4c4 = getGridBagConstraints(GridBagConstraints.VERTICAL,4,3,1,0,0.5,40);
pane.add(panelr4c4,constraint_r4c4);
// fifth row (fill, gridx, gridy, gridwidth 1, weightx 0, weighty 0, ipady 0)
TestPanel panelr5c1 = new TestPanel(Color.darkGray);
GridBagConstraints constraint_r5c1 = getGridBagConstraints(GridBagConstraints.VERTICAL,0,4,1,0,0.5,40);
pane.add(panelr5c1,constraint_r5c1);
TestPanel panelr5c2 = new TestPanel(Color.yellow);
GridBagConstraints constraint_r5c2 = getGridBagConstraints(GridBagConstraints.BOTH,1,4,2,1.0,0.5,40);
pane.add(panelr5c2,constraint_r5c2);
TestPanel panelr5c3 = new TestPanel(Color.white);
GridBagConstraints constraint_r5c3 = getGridBagConstraints(GridBagConstraints.VERTICAL,3,4,1,0,0.5,40);
pane.add(panelr5c3,constraint_r5c3);
TestPanel panelr5c4 = new TestPanel(Color.orange);
GridBagConstraints constraint_r5c4 = getGridBagConstraints(GridBagConstraints.VERTICAL,4,4,1,0,0.5,40);
pane.add(panelr5c4,constraint_r5c4);
// sixth row (fill, gridx, gridy, gridwidth 1, weightx 0, weighty 0, ipady 0)
TestPanel panelr6c1 = new TestPanel(Color.green);
GridBagConstraints constraint_r6c1 = getGridBagConstraints(GridBagConstraints.NONE,0,5,1,0,0,0);
pane.add(panelr6c1,constraint_r6c1);
TestPanel panelr6c2 = new TestPanel(Color.blue);
GridBagConstraints constraint_r6c2 = getGridBagConstraints(GridBagConstraints.HORIZONTAL,1,5,2,1.0,0,0);
pane.add(panelr6c2,constraint_r6c2);
TestPanel panelr6c3 = new TestPanel(Color.red);
GridBagConstraints constraint_r6c3 = getGridBagConstraints(GridBagConstraints.NONE,3,5,1,0,0,0);
pane.add(panelr6c3,constraint_r6c3);
TestPanel panelr6c4 = new TestPanel(Color.black);
GridBagConstraints constraint_r6c4 = getGridBagConstraints(GridBagConstraints.NONE,4,5,1,0,0,0);
pane.add(panelr6c4,constraint_r6c4);
// seventh row (fill, gridx, gridy, gridwidth 1, weightx 0, weighty 0, ipady 0)
TestPanel panelr7c1 = new TestPanel(Color.darkGray);
GridBagConstraints constraint_r7c1 = getGridBagConstraints(GridBagConstraints.NONE,0,6,1,0,0,0);
pane.add(panelr7c1,constraint_r7c1);
TestPanel panelr7c2 = new TestPanel(Color.white);
GridBagConstraints constraint_r7c2 = getGridBagConstraints(GridBagConstraints.HORIZONTAL,1,6,2,1.0,0,0);
pane.add(panelr7c2,constraint_r7c2);
TestPanel panelr7c3 = new TestPanel(Color.yellow);
GridBagConstraints constraint_r7c3 = getGridBagConstraints(GridBagConstraints.NONE,3,6,1,0,0,0);
pane.add(panelr7c3,constraint_r7c3);
TestPanel panelr7c4 = new TestPanel(Color.green);
GridBagConstraints constraint_r7c4 = getGridBagConstraints(GridBagConstraints.NONE,4,6,1,0,0,0);
pane.add(panelr7c4,constraint_r7c4);
}
// Create the GUI and show it. For thread safety, this method should be invoked from the event-dispatching thread.
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("GridBagConstraint Practice");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread: creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {public void run() {createAndShowGUI();}});
}
private static GridBagConstraints getGridBagConstraints(int fill, int gridx, int gridy, int gridwidth, double weightx, double weighty, int ipady){
GridBagConstraints myGridBagConstraints = new GridBagConstraints();
myGridBagConstraints.fill=fill;
myGridBagConstraints.gridx=gridx;
myGridBagConstraints.gridy=gridy;
myGridBagConstraints.gridwidth=gridwidth;
myGridBagConstraints.weightx=weightx;
myGridBagConstraints.weighty=weighty;
myGridBagConstraints.ipady=ipady;
return myGridBagConstraints;
}
}
The code for TestPanel.java is:
import java.awt.Color;
import javax.swing.JPanel;
public class TestPanel extends JPanel {
public TestPanel (Color myColor){this.setBackground(myColor);}
}
A: Rule number 1 for Swing layouts: Whatever you do, do not use GridBagLayout. GridBagLayout was fine in 1998. Its design is problematic, it is buggy, and it has not evolved. Code is extremely verbose, hard to write, hard to understand and hard to maintain.
I recommend MigLayout, it's the most versatile and intuitive layout manager I have seen. Look at the quick start guide on the MigLayout site, it's a lot less difficult than GridBagLayout and much more powerful. Here is your example in in MigLayout and I've shown you how to refactor your row types:
import net.miginfocom.swing.MigLayout;
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutDemo {
final static boolean RIGHT_TO_LEFT = false;
public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
pane.setLayout(new MigLayout("insets 0, gap 0, wrap", "[][fill, grow][fill, grow][][]", "[fill]"));
addType1(pane, Color.BLACK, Color.BLUE, Color.GREEN, Color.RED, Color.BLUE);
addType2(pane, Color.MAGENTA, Color.PINK, Color.BLACK, Color.PINK);
addType3(pane, Color.GRAY, Color.ORANGE, Color.RED, Color.ORANGE);
addType3(pane, Color.BLACK, Color.WHITE, Color.GREEN, Color.BLUE);
addType3(pane, Color.DARK_GRAY, Color.YELLOW, Color.WHITE, Color.ORANGE);
addType2(pane, Color.GREEN, Color.BLUE, Color.RED, Color.BLACK);
addType2(pane, Color.DARK_GRAY, Color.WHITE, Color.YELLOW, Color.GREEN);
}
private static void addType1(Container pane, Color c1, Color c2, Color c3, Color c4, Color c5) {
pane.add(new TestPanel(c1));
pane.add(new TestPanel(c2));
pane.add(new TestPanel(c3));
pane.add(new TestPanel(c4));
pane.add(new TestPanel(c5));
}
private static void addType2(Container pane, Color c1, Color c2, Color c3, Color c4) {
pane.add(new TestPanel(c1));
pane.add(new TestPanel(c2), "spanx 2");
pane.add(new TestPanel(c3));
pane.add(new TestPanel(c4));
}
private static void addType3(Container pane, Color c1, Color c2, Color c3, Color c4) {
pane.add(new TestPanel(c1));
pane.add(new TestPanel(c2), "spanx 2, pushy, hmin pref+40");
pane.add(new TestPanel(c3));
pane.add(new TestPanel(c4));
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("MigLayout Practice");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
class TestPanel extends JPanel {
public TestPanel(Color myColor) {
this.setBackground(myColor);
}
}
This yields the exact same layout as your example. Probably you want hmin 40 instead of hmin pref+40, the latter produces the same result as setting ipady=40 in GridBagConstraints.
And please use the upper case constants in the Color class, the lower-case constants should really be deprecated.
For anyone who wonders what this layout looks like, here it is:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Android Java code to mimic a 2 Keystroke sequence (to perform a device screenshot) I have been trying to get a bitmap screenshot of a SurfaceView for days but the more I look into it, there doesn't seem to be a solution at present for Android OS 2.3.4 based OSs my device from HTC.
So on to Plan B, where I just found out another blog: "On my HTC Evo 3d, all I have to do is hold the power button for 1-2 sec and then hit the home button and it takes a screen shot. No app required." Turns out this works perfectly on my tablet.
I also know from digging around there are these intents: android.intent.action.SCREEN_OFF & android.intent.category.HOME
(So I tried a bunch of code experiments to try to mimic the 2-key combo in code to get a screenshot in this brute force manor. Unfortunately without success).
So my ? -- Does anyone have any insights into a method to invoke this 'screenshot sequence' for my HTC device from java code? (Presume I need to fool the OS into thinking I am holding down the power key AND tap the Home key, simultaneously)...
More: Here is a snip of the code I am attempting:
Button click for test... ...
Thread t = new Thread() {
public void run() {
Instrumentation inst = new Instrumentation();
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_POWER);
Instrumentation inst2 = new Instrumentation();
inst2.sendKeyDownUpSync(KeyEvent.KEYCODE_HOME);
} // run
}; // thread t
Doesnt work as the inst.sendKeyDownUpSync is wrong as I need a sendKeyDown (& hold) behavior or its equivel
Many thanks for any advise. If I do get this working, I will post the solution here. Cheers GH
PS; I presume there is some custom intent under the hood doing this? Is there a system log somewhere to trey to peek at the call tree to find out what it is ?
EDIT (MORE)... 9/24/11
More. Still not working but I am heading down this path & think it is closer...
// Attempt to SIMULATE A Long press (DOWN) + HOME to tell the HTC to invoke the 'Screenshot' command (WARNING: HTC Tablet specific behavior!)
Thread tt = new Thread() {
public void run() {
final KeyEvent dapowerkey = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_POWER);
Handler onesecondhandler = new Handler();
onesecondhandler.postDelayed(new Runnable() {
public void run() {
// fpr about 1 second send power down keystrokes (DOWN ONLY)
while (true) { dispatchKeyEvent(dapowerkey); }
} // we are done running on the timer past time point
}, 750); // 3/4 second key press
// send the HOME keystroke
Instrumentation inst1 = new Instrumentation();
inst1.sendKeyDownUpSync(KeyEvent.KEYCODE_HOME);
} // outer thread run tp mpt block the GUI
}; // outer thread t
tt.start();
...
Also thought if I can send the right intent directly to the proper place on the device that I might be able to kick off a screen capture function directly (which is what I really want. Through some log examinations (when you Long-Power + Home click on HTC) a program called 'com.htc.mysketcher' (FlashActivity) is being called...
Again, if I figure this out then I will post to the group... Cheers GH
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to set Background image for iphone app in phonegap I am new in phonegap development and i am developing one project for iphone application with use of phonegap framework.
I am setting http://www.wallpaperbase.com/wallpapers/computer/mac/mac_8.jpg image as a background of my iphone application but its showing problem with image means image not properly displaying on my iphone Device like as given image example below.
Please solve my issue ASPS.
Please check my code and let me know what's wrong in it.
A: You need to try this on line number 15 in index.html page-
<body style="background: url(mac_8.jpg) no-repeat;background-size: 100%;" >
then your app's background image will look like this -
only if you made changes in info.plist to support for landscape mode for iPhone
One important thing - take background image of size 320X480 or 640X940 (iPhone4)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: how to arrange downloaded information to fit into rows? SqlConnection connection = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");
SqlCommand Command = connection.CreateCommand();
SqlDataReader SQLRD;
Command.CommandText = "Select * from Attendance";
connection.Open();
SQLRD = Command.ExecuteReader();
string data = "";
while (SQLRD.Read())
{
data += SQLRD[0].ToString()+ "\n";
data += SQLRD[1].ToString() + "\n";
data += SQLRD[2].ToString() + "\n";
data += SQLRD[3].ToString() + "\n";
data += SQLRD[4].ToString() + "\n";
data += SQLRD[5].ToString() + "\n";
data += SQLRD[6].ToString() + "\n";
data += SQLRD[7].ToString() + "\n";
}
SQLRD.Close();
connection.Close();
string filename = @"C:\download.csv";//specified location
FileStream fs = new FileStream(filename,FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(data);
sw.Flush();
sw.Close();
fs.Close();
This is what i have done so far. currently upon clicking on download all information appear in 1 single column and is not separated into rows. I need to know how can i arrange them into rows. Also can i also know how am i to display a dialog box when the user clicks on download. Currently the file is just stored in the specified location?
A: When exporting to .csv format, you want to put commas (,) between the columns, and line returns (\n) between the rows. Currently, you are putting a line return between every single column. Try something like this:
while (SQLRD.Read())
{
data += SQLRD[0].ToString() + ",";
// ^^^ note the change from '\n' to ','
data += SQLRD[1].ToString() + ",";
data += SQLRD[2].ToString() + ",";
...
data += SQLRD[7].ToString(); // final column doesn't need a ','
data += "\n"; // final line separator for the entire row
}
Best regards,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: User and ROles (how can i handle this?) In my view, I'd like to add a User to a role using checkboxes. I list all the roles then check two or three to add the user to that role. How do I handle this?
A: You could do something like this in your post...
[HttpPost]
public ActionResult UserDetails(UserClass user, bool admin, bool superAdmin, bool GodRole)
{
MembershipUser muser = Membership.GetUser(user.UserName);
if (admin)
Roles.AddUserToRole(muser.UserName, "admin");
if (superAdmin)
Roles.AddUserToRole(muser.UserName, "superAdmin");
if (GodRole)
Roles.AddUserToRole(muser.UserName, "GodRole");
return View();
}
Hope this helps...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to click the popwindow in the actionbar? I have created action bar.in that when i click on one of the menu a pop window should be displayed.I have done that.But after the pop up window displays i am not able to perform other function in my action bar.howw can i acheive that.I have posted my code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mDisplayMode = tab.getPosition();
System.out.println("text");
// Do stuff based on new tab selected
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// Do Nothing
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// Do nothing
}*/
ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tabA = bar.newTab().setText("Home");
ActionBar.Tab tabB = bar.newTab().setText("Listings");
ActionBar.Tab tabC = bar.newTab().setText("Remote");
Fragment fragmentA = new ATab();
Fragment fragmentB = new BTab();
Fragment fragmentC = new CTab();
bar.setDisplayShowHomeEnabled(true);
tabA.setTabListener(new MyTabsListener(fragmentA));
tabB.setTabListener(new MyTabsListener(fragmentB));
tabC.setTabListener(new MyTabsListener(fragmentC));
bar.addTab(tabA);
bar.addTab(tabB);
bar.addTab(tabC);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.settings:
newGame();
return true;
case R.id.help:
// showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void newGame() {
LayoutInflater inflater = (LayoutInflater)
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
PopupWindow pw = new PopupWindow(
inflater.inflate(R.layout.settings, null, true), 300, 600, true);
// The code below assumes that the root container has an id called 'main'
pw.showAtLocation(this.findViewById(R.id.settings), Gravity.RIGHT, 0, 0);
}
protected class MyTabsListener implements ActionBar.TabListener {
private Fragment mfragment;
public MyTabsListener(Fragment fragment) {
this.mfragment = fragment;
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.add(R.id.fragment_place, mfragment, null);
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
ft.remove(mfragment);
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Stig JSON library parse error: How do you accommodate new lines in JSON? I have some xml that is coming back from a web service. I in turn use xslt to turn that xml into json (I am turning someone else's xml service into a json-based service). My service, which is now outputting JSON, is consumed by my iphone app using the de facto iphone json framework, SBJSON.
The problem is, using the [string JSONValue] method chokes, and I can see that it's due to line breaks. Lo and behold, even the FAQ tells me the problem but I don't know how to fix it.
The parser fails to parse string X
Are you sure it's legal JSON? This framework is really strict, so won't accept stuff that (apparently) several validators accepts. In particular, literal TAB, NEWLINE or CARRIAGE RETURN (and all other control characters) characters in string tokens are disallowed, but can be very difficult to spot. (These characters are allowed between tokens, of course.)
If you get something like the below (the number may vary) then one of your strings has disallowed Unicode control characters in it.
NSLocalizedDescription = "Unescaped control character '0x9'";
I have tried using a line such as: NSString *myString = [myString stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
But that doesn't work. My xml service is not coming back as CDATA. The xml does have a line break in it as far as I can tell (how would I confirm this). I just want to faithfully transmit the line break into JSON.
I have actually spent an entire day on this, so it's time to ask. I have no pride anymore.
Thanks alot
A: Escaping a new line character should work. So following line should ideally work. Just check if your input also contains '\r' character.
NSString *myString = [myString stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
You can check which control character is present in the string using any editor which supports displaying all characters (non-displayable characters as well). e.g. using Notepad++ you can view all characters contained in a string.
A: It sounds like your XSLT is not working, in that it is not producing legal JSON. This is unsurprising, as producing correctly formatted JSON strings is not entirely trivial. I'm wondering if it would be simpler to just use the standard XML library to parse the XML into data structures that your app can consume.
A: I don't have a solution for you, but I usually use CJSONSerializer and CJSONDeserializer from the TouchJSON project and it is pretty reliable, I have never had a problem with line breaks before. Just a thought.
http://code.google.com/p/touchcode/source/browse/TouchJSON/Source/JSON/CJSONDeserializer.m?r=6294fcb084a8f174e243a68ccfb7e2c519def219
http://code.google.com/p/touchcode/source/browse/TouchJSON/Source/JSON/CJSONSerializer.m?r=3f52118ae2ff60cc34e31dd36d92610c9dd6c306
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to display notification using C#? I am developing an application to monitor changes to files within a folder (eg.add files, delete files, update files). I'd like to display information about detected changes in a notification similar to the one displayed by Skype.
Can anyone suggest how this could be implemented?
A: A broad question calls for a broad answer: take a look at the FileSystemWatcher class to detect files changing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Android MediaPlayer - Sometimes No Video is Played Even Though Audio Plays I am developing an Android App and I'm using the Android SDK's MediaPlayer to play some videos in my app. When I play the video in my app, about one out of five times, the audio plays without video. It's not a simple coding error because most of the time the video plays perfectly.
I have considered that a race condition in my code caused the bug. However, I added a number of debug statements and everything seems to be set up properly when the video does not play.
I have scanned the web and SO trying to find solutions but none have been adequate (see below).
Has anyone run into this type of problem before? If so, what did you do?
Similar Questions:
MediaPlayer Video not played
android media player shows audio but no video
android video, hear sound but no video
Some More Details:
*
*I've come across this bug on two phones. On a Samsung Charge video plays 80% of the time and 20% of the time there's audio but no video. On a T-Mobile Comet it's much worse; video only plays about 10% of the time.
*It's not a problem with the file, I've tried various video files and codecs and get the same issues.
*It's not a problem with the storage medium. I've tried playing the video when it was stored on internal storage and the sdcard, neither makes a difference. I have even tried reading some of the file before playing it, hoping that the system will cache it, but that doesn't seem to help either.
Update:
I've been debugging this and looking through logcat. I've found that when the video works, something like the following appears in logcat:
09-28 00:09:03.651: VERBOSE/PVPlayer(10875): setVideoSurface(0x65638)
But when video doesn't play, it looks like there's a null entry:
09-28 00:03:35.284: VERBOSE/PVPlayer(10875): setVideoSurface(0x0)
Update 2:
When the video fails to play, the function MediaPlayer.OnInfoListener with parameters what==MEDIA_ERROR_UNKNOWN(0x1) and extra==35. I looked through the Android code-base to try to determine what unknown error 35 means. I came across the file pv_player_interface.h, which indicates that error code 35 corresponds to something called a PVMFInfoTrackDisable. I googled that term which brought me to a file called pvmf_return_codes.pdf. That file gave me the following unintelligible explanation:
4.34. PVMFInfoTrackDisable
Notification that paticular track is
disable. This one is on a per track basis. For uncompressed
audio/video formats, during the process of selecting tracks available
in content, if the decoder doesn't support the track, a
PVMFInfoTrackDisable event is sent. The event, if necessary, will be
sent once per track.
I feel like I've gone a long way, but am no closer to finding an answer... still investigating.
A: Following speedplane's suggestions I came up with the following code. If the MediaPlayer.getVideoHeight() returns 0 in onPrepared then I delay for 1 second and try again. Now if it does not play the first time it usually will play 1 second later. I have seen it take several tries though.
private void videoPlayer(String path){
if (mMediaController == null)
{
mMediaController = new MediaController(this);
mVideoView.setMediaController(mMediaController);
}
if (!mMediaController.isShowing())
mMediaController.show();
getWindow().setFormat(PixelFormat.TRANSLUCENT);
mVideoView.setVideoPath(path);
mVideoView.requestFocus();
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(final MediaPlayer mp) {
mVideoView.seekTo(mImageSeek);
if (mp.getVideoHeight() == 0) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mVideoView.stopPlayback();
mMediaController = null;
videoPlayer(mImageFilepath);
}
}, 1000);
} else
mVideoView.start();
}
});
}
A: I have been studying this bug 2 weeks , and i have understand more or less the real problem . Of course i'm talking about The Evil Info 35 Message . If you have met this wonderfull strange error , now you can be happy and shot some vendors like samsung :D ...
The problem comes cause the surface view can't be seen by the user (activity in tabhost or pause-wakeup function , not in focus sometimes , not in front sometimes too (maybe)).
That's cause when some reset that video it runs ok , cause it gains focus or maybe another activity/object is not overlapping it.
When some of those happen , the mediaplayer thinks you can't see the video or it can't play , and it disable video track, giving you the worst headache in your worklife while listening the music track.
Will see next bug , good luck . :D
A: I solved the problem, albeit in a totally hackish way. There are two problems actually:
*
*The Evil Info 35 Message: I found that occasionally MediaPlayer.OnInfoListener will get called with extra==35. When this happens, you're screwed and the video will not play properly. I have no idea what causes it. The only fix I found was to try restarting the video and going through the whole prepareAsync process over again. Video playback usually works the second time.
*Video Size Not Set: Even after MediaPlayer.OnPreparedListener gets issued (or equivalently prepare() returns) the video size may not be been set. The video size will usually be set a couple of miliseconds after prepare returns, but for a few moments it is in a nebulous state. If you call MediaPlayer.start() before the video size is set, then playback will sometimes (but not always) fail. There are two potential solutions to this: (1) poll MediaPlayer.getVideoHeight() or getVideoWidth() until they're non-zero or (2) wait until OnVideoSizeChangedListener is called. Only after one of these two events, should you call start().
With these two fixes, video playback is much more consistent. It's very likely that these problems are bugs with my phones (Samsung Charge and a T-Mobile Comet) so I won't be surprised if there are different, but similar problems on other phones.
A: The fundamental question is:
before surfaceCreated invoked you start video playback, when the holder is not ready for MediaPlayer, so that you only hear the sound but can not see the picture!
The right way is:
A: I had that problem too on my Desire HD about 1 or 2 times. I tried many things but the error was allways there. Afterall i choosed to install a custom rom on my device. Afterwards it worked perfectly and I never had a this issue again.
I know its not that kind of answer you'd like to hear but i didn't find an other soultions.
Here you find custom roms for your device: XDA Developers
I hope I could help you out.
Best Regards and Happy Movie watching
safari =)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: How to send custom value to facebook iframe I m working on a facebook iframe application.
Facebook $_REQUEST response is as bellow:
Array
(
[signed_request] => some value
[PHPSESSID] => somevalue
[fbs_251034681599274] => somevalue
)
but i want one more parameter to its REQUEST so i want its response like bellow
Array
(
[fb] => some value
[signed_request] => some value
[PHPSESSID] => somevalue
[fbs_251034681599274] => somevalue
)
and that fb key will be dynamically.
Please help me how can i do it.
Best Regards,
Krishna Karki
A: If you want to identify users you need to use fb authorization (https://developers.facebook.com/docs/guides/web/#login) and then you can get some unique ids
OR you can generate that keys on your server (where that iframe source is)
if you just want to send some data with interaction on that iframe, do it same as you do it on a non-iframe-facebook-app page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery-UI Thickbox not working properly I have a query on the behaviour of the jquery-ui component ThickBox. The issue is,
Im using the thickbox in my master page. The login page of my website contains few asp controls where 'causesvalidation' property of the asp controls are set to 'true'. When the link associated with the thickbox class is clicked, the pages where validations are not set will show the hidden div . Why the same not working with the other pages where the validations are set to true? Is there any way to skip the validation when an anchor tag is used?
Please help...
A: Make the anchor a server control and set the CausesValidation property of the anchor in to false. Also, ASP.NET has ValidationGroups, which might help you out as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Highlighting the 'All' category in wp_list_categories I have given the following arguments in the wp_list_categories function.
<?php wp_list_categories('show_option_all=All&hide_empty=0&title_li=¤t_category=All'); ?>
I want the 'All' option to be visible in any category listing. However, since by default, all posts load, the styling for current_category should also apply to 'All'. However, since All does not have a category ID, I do not know how to apply the current-cat class to 'All'.
Any suggestions?
A: You could fetch the list into a variable (add echo=0 to the parameters), and insert a custom class using string replace.
Update:
Something like this:
<?php
function str_replace_once($needle , $replace , $haystack){
$pos = strpos($haystack, $needle);
if ($pos === false) {
return $haystack;
}
return substr_replace($haystack, $replace, $pos, strlen($needle));
}
$args = array( 'show_option_all' => 'All',
'hide_empty' => '0',
'title_li' => '',
'current_category' => 'All',
'echo' => '0');
$str = wp_list_categories($args);
$str = str_replace_once('<li>', '<li class="current-cat">', $str);
echo $str;
?>
A: You can use preg_replace to remove some of the complexity. The last parameter limits the number of occurrences to replace.
$list = wp_list_categories([
'show_option_all' => 'All',
'hide_empty' => false,
'title_li' => '',
'current_category' => 'All',
'echo' => false
]);
$list = preg_replace('/<li>/', '<li class="current-cat">', $list, 1);
echo $list;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Voice command for screen unlock android I want to use voice command to screen unlock an android phone.
I have tried the voice recognition sample code from android, but how do i integrate it to achieve this feature?
I have some doubts,
1) would i have to use service for this feature?
2) when the phone screen is locked, can it have access to internet? (because google voice is using internet)
3) I have looked through PowerManager class, but using which method can i invoke my voiceReconigtion activity when i pressed the Power button? (phone is in sleep,locked mode)
Any guide or solution/feedback is much appreciated!
Thank You
A: I am almost positive you'll have to run this in a service, as it seems that it would be destroyed as soon as it's out of focus and the GC needs allocations...
As far as the waking from sleep, I believe this is the right direction.
Best of luck.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to Hide/Show button in android home screen widget I am a beginner of android development. Current, I am working on creating a small home screen widget that is changing wallpaper of the mobile on click the button. The setting wallpaper is working fine but I want to make a clickable small picture (ImageView) to allow user to show and hide this setting button.
I setup it on service and use PendingIntent in order to attach my onClick event to the same service, but I cannot detect the property of button whether showing or hiding.
Therefore,is there any suggestion and solution to make my ImageView to show or hide the button in home screen widget?
Thanks in advance..
A: You can use mButton.setVisibility(View.GONE) to hide the button.
You can also check state of button's visibility in a boolean variable using mButton.isShown().
Edited:
For Example
In onReceive() of AppWidgetProvider,
remoteViews = new RemoteViews( context.getPackageName(), R.layout.yourwidgetlayout );
remoteViews.setViewVisibility(viewId, visibility);
So for hiding your Button
remoteViews.setViewVisibility(R.id.buttonId,View.INVISIBLE);
Edit - 2: According to Kartik's comment,
Sample Code:
public class ButtonHideShowWidget extends AppWidgetProvider {
private static boolean status = false;
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction()==null) {
Bundle extras = intent.getExtras();
if(extras!=null) {
remoteViews = new RemoteViews( context.getPackageName(), R.layout.your_widget_layout );
if(status){
remoteViews.setViewVisibility(R.id.buttonId,View.INVISIBLE);
status = false;
}else{
remoteViews.setViewVisibility(R.id.buttonId,View.VISIBLE);
status = true;
}
watchWidget = new ComponentName( context, ButtonHideShowWidget.class );
(AppWidgetManager.getInstance(context)).updateAppWidget( watchWidget, remoteViews );
//Toast.makeText(context, "Clicked "+status, 2000).show();
}
}
}
}
A: Call setVisibility(View.Invisible); with the help of button object created by you after the user clicks the button.
A: // To remove button
Button button = (Button) findViewById(R.id.button);
button.setVisibility(View.GONE);
// To transparent button
Button button = (Button) findViewById(R.id.button);
button.setVisibility(View.INVISIBLE);
A: You should not be doing this in onReceive(Context, Intent) method as mentioned in official documentation
This is called for every broadcast and before each of the above callback methods. You normally don't need to implement this method because the default AppWidgetProvider implementation filters all App Widget broadcasts and calls the above methods as appropriate.
You should do this in onAppWidgetOptionsChanged().
See the official docs.
A: public class Showing extends AppWidgetProvider {
private static boolean status = false;
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction()==null) {
Bundle extras = intent.getExtras();
if(extras!=null) {
remoteViews = new RemoteViews( context.getPackageName(), R.layout.your_widget_layout );
if(status){
remoteViews.setViewVisibility(R.id.buttonId,View.INVISIBLE);
status = false;
}else{
remoteViews.setViewVisibility(R.id.buttonId,View.VISIBLE);
status = true;
}
watchWidget = new ComponentName( context, ButtonHideShowWidget.class );
(AppWidgetManager.getInstance(context)).updateAppWidget( watchWidget, remoteViews );
//Toast.makeText(context, "Clicked "+status, 2000).show();
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: alternative for the deprecated __proto__ Granted I'm a javascript noob (at best). The following code seems to work fine. Any ideas how to keep the same "initializer" approach and make it work without using __proto__ and without converting everything to constructor functions?
var Employee =
{
paygrade: 1,
name: "",
dept: "general",
init: function()
{
return this;
},
salary: function()
{
return this.paygrade * 30000;
}
};
var WorkerBee =
{
paygrade: 2,
projects: ["Project1", "Project2"],
init: function()
{
this.__proto__ = Inherit_Employee; // Inherit My Employee "Pseudo Prototype"
return this;
}
};
var SalesPerson =
{
dept: "Sales",
quota: 100,
init: function()
{
this.__proto__ = Inherit_WorkerBee; // Inherit My WorkerBee "Pseudo Prototype"
return this;
}
};
var Engineer =
{
dept: "Engineering",
machine: "im the start machine",
init: function()
{
this.__proto__ = Inherit_WorkerBee; // Inherit My WorkerBee "Pseudo Prototype"
return this;
}
};
var Inherit_Employee = Object.create(Employee).init(); // Create My Employee Pseudo-Prototype
var Inherit_WorkerBee = Object.create(WorkerBee).init(); // Create My WorkerBee Pseudo-Prototype
var jane = Object.create(Engineer).init();
var jill = Object.create(Engineer).init();
I do have one approach that works, but I'm wondering if there is a more efficient approach. For now, what I have done is replace the lines that reference __proto__ with a call to my own inheritence function like this.
init: function()
{
inherit(this, WorkerBee); // Inherit WorkerBee
return this;
}
And this is my inherit() function
function inherit( childObject, parentObject )
{
// childObject inherits all of parentObjects properties
//
for (var attrname in parentObject)
if ( childObject[attrname] == undefined )
childObject[attrname] = parentObject[attrname];
// childObject runs parentObject 'init' function on itself
//
for (var attrname in parentObject)
if ( typeof parentObject[attrname] == "function" )
if ( attrname == 'init' )
parentObject[attrname].call(childObject);
}
A: Why you dont use standard javascript function inheritance? For example:
function inherit(childClass, parentClass) {
var f = function() {}; // defining temp empty function
f.prototype = parentClass.prototype;
f.prototype.constructor = f;
childClass.prototype = new f;
childClass.prototype.constructor = childClass; // restoring proper constructor for child class
parentClass.prototype.constructor = parentClass; // restoring proper constructor for parent class
}
Employee = function Employee( /*list of constructor parameters, if needed*/ ) {}
Employee.prototype.paygrade = 1;
Employee.prototype.name = "";
Employee.prototype.dept = "general";
Employee.prototype.salary = function() {
return this.paygrade * 30000;
}
WorkerBee = function WorkerBee( /*list of constructor parameters, if needed*/ ) {
this.projects = ["Project1", "Project2"];
}
inherit(WorkerBee, Employee); // for this implementation of *inherit* must be placed just after defining constructor
WorkerBee.prototype.paygrade = 2;
WorkerBee.prototype.projects = null; // only literals and function-methods can properly initialized for instances with prototype
Engineer = function Engineer( /*list of constructor parameters, if needed*/ ) {}
inherit(Engineer, WorkerBee);
Engineer.prototype.dept = "Programming";
Engineer.prototype.language = "Objective-C";
var jane = new Engineer( /*Engineer parameters if needed*/ );
var jill = new Engineer( /*Engineer parameters if needed*/ );
var cow = new Employee( /*Employee parameters if needed*/ );
A: Object.getPrototypeOf
// old-way
obj.__proto__
// new-way
Object.getPrototypeOf(obj)
A: __proto__ will be in ES6, so maybe if you're reading this now, you shouldn't need this but it's still good to know
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: eclipse rcp : help to create a customized StyledText widget I want a customized StyledText widget which can accept a keyword list,then highlight these keywords!
I found it's very hard to implement it by myself.
A: God damned! after spent hours searching the web, I finally found some sample code from the book The Definitive Guide to SWT and JFace, it's quite simple :
Main class :
package amarsoft.rcp.base.widgets.test;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import amarsoft.rcp.base.widgets.SQLSegmentEditor;
public class PageDemo extends ApplicationWindow {
public PageDemo(Shell parentShell) {
super(parentShell);
final Composite topComp = new Composite(parentShell, SWT.BORDER);
FillLayout fl = new FillLayout();
fl.marginWidth = 100;
topComp.setLayout(fl);
new SQLSegmentEditor(topComp);
}
/**
* @param args
*/
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
new PageDemo(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
package amarsoft.rcp.base.widgets;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
/**
* SQL语句/SQL语句片段编辑器,除了内容编辑之外,提供一个额外的功能——常用SQL语句关键字高亮显示。
* @author ggfan@amarsoft
*
*/
public class SQLSegmentEditor extends Composite{
private StyledText st;
public SQLSegmentEditor(Composite parent) {
super(parent, SWT.NONE);
this.setLayout(new FillLayout());
st = new StyledText(this, SWT.WRAP);
st.addLineStyleListener(new SQLSegmentLineStyleListener());
}
}
package amarsoft.rcp.base.widgets;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.LineStyleEvent;
import org.eclipse.swt.custom.LineStyleListener;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.graphics.Color;
import org.eclipse.wb.swt.SWTResourceManager;
public class SQLSegmentLineStyleListener implements LineStyleListener {
private static final Color KEYWORD_COLOR = SWTResourceManager
.getColor(SWT.COLOR_BLUE);
private List<String> keywords = new ArrayList<String>();
public SQLSegmentLineStyleListener() {
super();
keywords.add("select");
keywords.add("from");
keywords.add("where");
}
@Override
public void lineGetStyle(LineStyleEvent event) {
List<StyleRange> styles = new ArrayList<StyleRange>();
int start = 0;
int length = event.lineText.length();
System.out.println("current line length:" + event.lineText.length());
while (start < length) {
System.out.println("while lopp");
if (Character.isLetter(event.lineText.charAt(start))) {
StringBuffer buf = new StringBuffer();
int i = start;
for (; i < length
&& Character.isLetter(event.lineText.charAt(i)); i++) {
buf.append(event.lineText.charAt(i));
}
if (keywords.contains(buf.toString())) {
styles.add(new StyleRange(event.lineOffset + start, i - start, KEYWORD_COLOR, null, SWT.BOLD));
}
start = i;
}
else{
start ++;
}
}
event.styles = (StyleRange[]) styles.toArray(new StyleRange[0]);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jquery replacing spaces not working in IE I'm sort of new to jquery so I hope somebody can help me with this problem.
I'm working on grails, and
I have this jQuery object:
var tableIds = $("#myTable tbody tr td:first-child").text().toString()
when I alert() this, it has the id's some info (first column) of every row on myTable like:
1 1213 2324 23123
(to get the spaces between the id's I had to add manually the '& nbsp;' in the first td of myTable)
Now, when I try to:
var idArray = new Array()
idArray = tableIds.split(" ")
it doesn't work, the "split" just leave the idArray as a string with the original spaces
just as tableIds.
What I had to do was to replace the spaces with hyphens:
tableIds = tableIds.replace(/\s/g,"-")
and then split("-") works, dunno why... but ONLY in CHROME!! not in IE, and I need this to work in the stupid IE.
IE keeps showing me "1 1213 2324 23123", it did not found the spaces to replace and just left it like that.
Anyone have a clue on this?
Hope you can help me, if not, thanks anyway.
A: I think you might be going about this in the wrong way. If you want to get an array of ID's of the elements that jQuery has picked up via that selector, try doing this instead:
var ids = [];
$("#myTable tbody tr td:first-child").each(function () {
ids.push($(this).attr('id'));
});
//now the ids array will have all of the ID's of the elements in it
The 'each' runs the passed function over every element that was selected.. so you can grab all of the ID's like that very reliably. There might be more optimized ways, but this method has never failed me.
Edit: after re-reading, I realized you're probably looking for the text id that you've given.. something like..
| 1 | dog | $5
| 2 | cat | $2
| 3 | fish | $1.10
So.. using the same idea as I wrote above...
var ids = [];
$("#myTable tbody tr td:first-child").each(function () {
ids.push($(this).text());
});
//ids will be [1, 2, 3]
A: Try replacing your spaces with regular white space after each id.
A: Hmmm... I could be way off in assuming your mistake, but bear with me here:
It sounds like you're setting the ID of each td that you want to select to be a string with a bunch of spaces in it (or hyphens, or whatever).
jQuery's selector syntax is build so that you don't have to do this. You should be able to select the elements you want with the above syntax, and then iterate over them with an each() loop. Consider this:
var anArray = [];
$("#myTable tbody tr td:first-child").each(function(){
//This code will run for every element matched by the above selector
var contentsOfCell = $(this).text();
anArray.push(contentsOfCell);
});
Hope this helps!
A: You can extract the contents of the first <td> of each row using jQuery's .each() to iterate over all the results from your initial selector, putting each value in the array as you go:
var idArray = [];
$("#myTable tbody tr td:first-child").each(function() {
idArray.push($(this).text());
});
I don't know what's up with the regex not finding the spaces, unless IE thinks that non-breaking spaces are not whitespace?
A: Thanks to everyone! I didn't try replacing non-breaking spaces with simple spaces, becouse adding spaces manually on my TD's wasn't actually a good idea.
but as Stephen and nnnnnn and Chazbot said, this did the trick!
var ids = [];
$("#myTable tbody tr td:first-child").each(function () {
ids.push($(this).text());
})
I didn't know you can "each" this kind of jquery objects, I should've known it :D
Something new to learn.
Thanks again!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Passing URL with parameter I am passing url with some string value and NSInteger value in this url but when I put breakpoint on this and I tab on trace then it show me this message exc-bad-access in url I given bold please see that 'bold' I want to pass there value:
[ NSInteger day,NSInteger day1,NSString *fromDate1, NSString *fromDate1,NSString *OriginCode,NSString *DestinCode].
I get all value on url when I put the breakpoint but when I step into breakpoint my app crashes, why it crash? Help me. Where am I wrong?
-(void)sendRequest
{
stringWithFormat:@"http://www.google.com?AvailabilitySearchInputFRSearchView%24ButtonSubmit=Search%20For%20Flights%20&AvailabilitySeast=",day,day1,DestinCode,"2011-09","2011-09",OriginCode];
NSString *urlString = [NSString stringWithFormat:@"http://www.bookairways tickt.com/Sales/FRSearch.aspx?AvailabilitySearchInputFRSearchView%24ButtonSubmit=Search%20For%20Flights%20&AvailabilitySearchInputFRSearchView%24DropDownListMarketDay1=**%i**&AvailabilitySearchInputFRSearchView%24DropDownListMarketDay2=**%i**&AvailabilitySearchInputFRSearchView%24DropDownListMarketDestination1=**%@**&AvailabilitySearchInputFRSearchView%24DropDownListMarketMonth1=**%@**&AvailabilitySearchInputFRSearchView%24DropDownListMarketMonth2=**%@**&AvailabilitySearchInputFRSearchView%24DropDownListMarketOrigin1=**%@**&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_ADT=1&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_CHD=0&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_INFANT=0&AvailabilitySearchInputFRSearchView%24RadioButtonFlowSelector=FlightAndCar&AvailabilitySearchInputFRSearchView%24RadioButtonMarketStructure=RoundTrip&AvailabilitySearchInputFRSearchView%24discountPax=0&__EVENTARGUMENT=&__EVENTTARGET=&__VIEWSTATE=%2FwEPDwUBMGRkg4UKvNNb1NbM14%2F2n9zUxhNQ%2B%2BA%3D&errorlist=",day,day1,DestinCode,fromDate1,fromDate2,OriginCode];
//urlString=[urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(@"************url:%@",url);
NSURLRequest *theRequest=[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(@"%@",webData);
} else {
}
}
A: make your url properly like this:-
NSURL *url = [NSURL URLWithString:[*yourstring* stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
A: Harish this will help u to in creating the url check this our http://wiki.akosma.com/IPhone_URL_Schemes
like this
NSString *template = @"appigotodo://com.example.xyzapp/import?name=%@¬e=%@&due-date=%@&priority=%@&repeat=%@";
NSString *name = @"Buy%20some%20milk";
NSString *note = @"Stop%20on%20the%20way%20home%20from%20work.";
NSString *dueDate = @"2009-07-16";
NSString *priority = @"1";
NSString *repeat = @"101";
NSString *stringURL = [NSString stringWithFormat:template, name, note, dueDate, priority, repeat];
NSURL *url = [NSURL URLWithString:stringURL];
[[UIApplication sharedApplication] openURL:url];
A: Two things:
*
*The URL has many % symbols that are not being used as placeholders. The % symbols that are not between '**' in your code need to be escaped like so: %%. In other words, SearchInputFRSearchView%24Button should be SearchInputFRSearchView%%24Button.
*You are using %i to put integers into your string. You should be using %d instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Calculate size in Hex Bytes what is the proper way to calculate the size in hex bytes of a code segment. I am given:
IP = 0848 CS = 1488 DS = 1808 SS = 1C80 ES = 1F88
The practice exercise I am working on asks what is the size (in hex bytes) of the code segment and gives these choices:
A. 3800 B. 1488 C. 0830 D. 0380 E. none of the above
The correct answer is A. 3800, but I haven't a clue as to how to calculate this.
A: How to calculate the length:
*
*Note CS. Find the segment register that's nearest to it, but greater.
*Take the difference between the two, and multiply by 0x10 (read: tack on a 0).
In your example, DS is closest. 1808 - 1488 == 380. And 380 x 10 = 3800.
BTW, this only works on the 8086 and other, similarly boneheaded CPUs, and in real mode on x86. In protected mode on x86 (which is to say, unless you're writing a boot sector or a simple DOS program), the value of the segment register has very little to do with the size of the segment, and thus the stuff above simply doesn't apply.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to put CheckBoxPreference on pop out dialog like ListPreference I have several preferences items that a user can choose from and wanted to have them on a CheckBoxPreference widget. Since its a list of over 7 Items; on a preference activity with other options, it may lead to an unsightly scrolling IMHO. So I wanted to have it like the ListPreference pop out which is built into it, how could I have that pop out for CheckBoxPreference? Thanks guys
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SpicIE toolbar, SHDocVw.IWebBrowser2 execScript problem? I'm developing an addon for IE8+.
Main function:
- when I click the toolbar, it will display a box inside every single page, ex: google.com, bing.com, codeproject.com... by using execScript to execute jQuery.
Therefore, what Im doing is run javascript in the current page.
Everything has done except when that page perform an Pop-up, it doesnt work anymore.
I click the toolbar, nothing happen, but when I look at the pop-up, surprise! has the box which im trying to display. So, I think the current tab and the popup of its is running the same process.
I have change registry key TabProcGrowth to 20, to make sure every single tab run by its own process, but maybe it not work with popup.
sr for my bad english, any suggestion is welcome.
Thanks in advance.
update:
I have changed the way to develop my addon, so I change my question, too. (But any suggestion for the 1st question still very useful for me).
My new question still mention the "execScript" problem.
HOW to execute javascript with every individual tab of IE browser with TabProcGrowth = 0. I need this value set to 0 because I have the timer to request to the server every interval1 (ex: 60s). So if there are more than one processes of IE, the addon will send multi request to server at the sametime.
In my situation now, I set TabProcGrowth to 0. Open IE, open some tabs. Click the toolbar at the newest tab, it works, ofcourse!. But when I click toolbar at the old one, nothing happen. The script still be execute but it takes effect on the newest tab.
It's the big problem for me, resolve this problem, you guys save my life.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: phpbb3's slow indexing of new messages I try to found solution to improve phpbb3 new message indexing. I have about 10000 messages on my forum, and each new message adds VERY long time (20-30 sec). I've checked mysql_slow.log and found long queries there which is actually adding message into phpbb3's index.
Do someone have or find any ready solutions?
A: Let MySQL run for 72+ hours (without being restarted) and then download and run MySQL Tuner:
(as root)
cd ~/
wget http://www.mysqltuner.pl/ -O ./mysqltuner.pl
chmod +x ./mysqltuner.pl
./mysqltuner.pl
That will give you a good idea of what tweaks you can do to improve performance based upon your actual usage and needs. After you make the tweaks you'll want to restart MySQL and then give it another 48 to 72 hours before you run the tuner again to see if there is any finer tuning you can do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How access HTML5 video methods with jQuery? I'm writing an HTML5 app and I'm trying to access native video methods (play, pause, etc...) and use jQuery. I don't want to use any other plugins.
var movie = $('#video_with_controls');
$('#buttonX').click(function() {
movie.play();
});
But when I execute the preceding code, I get the following console error message:
Object has no method 'play'
How do I fix this? Thanks.
A: HTML5 video DOM element does have .play() method. There is no play method in jQuery yet. What you're doing wrong is firing play from a jQuery selector that returns array of elements.
For example $('#clip') returns [<video width="390" id="clip" controls>…</video>] that actually is an array of one DOM element. To access the actual DOM element you need to address one of array elements by doing something like $('#clip')[0]. Now you can tell this DOM element to PLAY.
So just do this:
var movie = $('#video_with_controls');
$('#buttonX').click(function() {
movie[0].play(); //Select a DOM ELEMENT!
});
This is my example:
HTML:
<video width="390" id="clip" controls="">
<source src="http://slides.html5rocks.com/src/chrome_japan.webm" type="video/webm; codecs="vp8, vorbis"">
</video>
<input type="button" id="play" value="PLAY" />
jQuery
$('#play').click(function(){
$('#clip')[0].play()
});
That works: http://jsbin.com/erekal/3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How can I find what locks are involved in a process I am running a SQL transaction with a bunch of statements in it.
The transaction was causing other processes to deadlock very occasionally, so I removed some of the things from the transaction that weren't really important. These are now done separately before the transaction.
I want to be able to compare the locking that occurs between the SQL before and after my change so that I can be confident the change will make a difference.
I expect more locking occurred before because more things were in the transaction.
Are there any tools that I can use? I can pretty easily get a SQL profile of both cases.
I am aware of things like sp_who, sp_who2, but the thing I struggle with for those things is that this is a snapshot in a particular moment in time. I would like the full picture from start to finish.
A: You can use SQL Server Profiler. Set up a profiler trace that includes the Lock:Acquired and Lock:Released events. Run your "before" query. Run your "after" query. Compare and contrast the locks taken (and types of locks). For context, you probably still want to also include some of the statement or batch events also, to see which statements are causing each lock to be taken.
A: you can use in built procedure:-- sp_who2
sp_who2 also takes a optional parameter of a SPID. If a spid is passed, then the results of sp_who2 only show the row or rows of the executing SPID.
for more detail info you can check: master.dbo.sysprocesses table
SELECT * FROM master.dbo.sysprocesses where spid=@1
below code shows reads and writes for the current command, along with the number of reads and writes for the entire SPID. It also shows the protocol being used (TCP, NamedPipes, or Shared Memory).
CREATE PROCEDURE sp_who3
(
@SessionID int = NULL
)
AS
BEGIN
SELECT
SPID = er.session_id
,Status = ses.status
,[Login] = ses.login_name
,Host = ses.host_name
,BlkBy = er.blocking_session_id
,DBName = DB_Name(er.database_id)
,CommandType = er.command
,SQLStatement =
SUBSTRING
(
qt.text,
er.statement_start_offset/2,
(CASE WHEN er.statement_end_offset = -1
THEN LEN(CONVERT(nvarchar(MAX), qt.text)) * 2
ELSE er.statement_end_offset
END - er.statement_start_offset)/2
)
,ObjectName = OBJECT_SCHEMA_NAME(qt.objectid,dbid) + '.' + OBJECT_NAME(qt.objectid, qt.dbid)
,ElapsedMS = er.total_elapsed_time
,CPUTime = er.cpu_time
,IOReads = er.logical_reads + er.reads
,IOWrites = er.writes
,LastWaitType = er.last_wait_type
,StartTime = er.start_time
,Protocol = con.net_transport
,transaction_isolation =
CASE ses.transaction_isolation_level
WHEN 0 THEN 'Unspecified'
WHEN 1 THEN 'Read Uncommitted'
WHEN 2 THEN 'Read Committed'
WHEN 3 THEN 'Repeatable'
WHEN 4 THEN 'Serializable'
WHEN 5 THEN 'Snapshot'
END
,ConnectionWrites = con.num_writes
,ConnectionReads = con.num_reads
,ClientAddress = con.client_net_address
,Authentication = con.auth_scheme
FROM sys.dm_exec_requests er
LEFT JOIN sys.dm_exec_sessions ses
ON ses.session_id = er.session_id
LEFT JOIN sys.dm_exec_connections con
ON con.session_id = ses.session_id
OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) as qt
WHERE @SessionID IS NULL OR er.session_id = @SessionID
AND er.session_id > 50
ORDER BY
er.blocking_session_id DESC
,er.session_id
END
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to capture XUL Panel Element in javascript I am trying to access XUL Panel Element through javascript to open and close it dynamically.
<?xml version="1.0"?>
<?xml-stylesheet type="text/css" href="chrome://global/skin/" ?>
<?xml-stylesheet type="text/css"
href="chrome://textareaautocomplete/skin/browserOverlay.css" ?>
<!DOCTYPE overlay SYSTEM
"chrome://textareaautocomplete/locale/browserOverlay.dtd">
<overlay id="textareaautocomplete-browser-overlay"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/x-javascript"
src="chrome://textareaautocomplete/content/browserOverlay.js" />
<stringbundleset id="stringbundleset">
<stringbundle id="textareaautocomplete-string-bundle"
src="chrome://textareaautocomplete/locale/browserOverlay.properties" />
</stringbundleset>
<menupopup id="menu_ToolsPopup">
<menu id="xs-textareaautocomplete-menu" label="&textareaautocomplete.menu.label;"
accesskey="&textareaautocomplete.menu.accesskey;"
insertafter="javascriptConsole,devToolsSeparator">
<menupopup>
<menuitem id="textareaautocomplete-ta-menu-item"
label="&textareaautocomplete.cache.start.label;"
accesskey="&textareaautocomplete.cache.accesskey;"
oncommand="TextareaAutocomplete.BrowserOverlay.main();" />
</menupopup>
</menu>
</menupopup>
<panel id="textareaautocomplete-ta-dropdown-panel">
<textbox id="search"/>
</panel>
</overlay>
try {
let panel = document.getElementById("textareaautocomplete-ta-dropdown-panel");
panel.openPopup(node, "after_start", 0, 0, false, false);
}
catch(e) {
window.alert("Failed to set drop down: " + e.name + ": " + e.message);
}
This gives me following error message in exception:
panel is null
Please let me know if something is missing or not right! One more point is that I am able to access other elements like stringbundleset, menupopup just by changing the id in same javascript code.
A: Wrap your panel inside a vbox or hbox
For example: in your case
<hbox>
<panel id="textareaautocomplete-ta-dropdown-panel">
<textbox id="search"/>
</panel>
<hbox>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: java with Oauth for Google and facebook authontication i wont to implement authentication using google and facebook in my application
any one share example that work for authentication in java webapp
without any java framework
i try with socialaut
its using struts and spring framework but i not use that framework in my application so give any example that work in simple tomcat application without any framework
A: add this code on login page request
SocialAuthConfig config = SocialAuthConfig.getDefault();
config.load(); // load your keys information
SocialAuthManager manager = new SocialAuthManager();
manager.setSocialAuthConfig(config);
String successUrl = "http://localhost:8080/yourapp/status
String url = manager.getAuthenticationUrl("facebook", successUrl);
session.setAttribute("authManager", manager);
redirect yout page to url for authentication
add this code on /status url
SocialAuthManager manager = (SocialAuthManager)session.getAttribute("authManager");
AuthProvider provider = manager.connect(paramsMap);
// get profile
Profile p = provider.getUserProfile();
// you can obtain profile information
System.out.println(p.getFirstName());
// OR also obtain list of contacts
List<Contact> contactsList = provider.getContactList();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Most idiomatic way to write batchesOf size seq in F# I'm trying to learn F# by rewriting some C# algorithms I have into idiomatic F#.
One of the first functions I'm trying to rewrite is a batchesOf where:
[1..17] |> batchesOf 5
Which would split the sequence into batches with a max of five in each, i.e:
[[1; 2; 3; 4; 5]; [6; 7; 8; 9; 10]; [11; 12; 13; 14; 15]; [16; 17]]
My first attempt at doing this is kind of ugly where I've resorted to using a mutable ref object after running into errors trying to use mutable type inside the closure. Using ref is particularly unpleasant since to dereference it you have to use the ! operator which when inside a condition expression can be counter intuitive to some devs who will read it as logical not. Another problem I ran into is where Seq.skip and Seq.take are not like their Linq aliases in that they will throw an error if size exceeds the size of the sequence.
let batchesOf size (sequence: _ seq) : _ list seq =
seq {
let s = ref sequence
while not (!s |> Seq.isEmpty) do
yield !s |> Seq.truncate size |> List.ofSeq
s := System.Linq.Enumerable.Skip(!s, size)
}
Anyway what would be the most elegant/idiomatic way to rewrite this in F#? Keeping the original behaviour but preferably without the ref mutable variable.
A: This can be done without recursion if you want
[0..20]
|> Seq.mapi (fun i elem -> (i/size),elem)
|> Seq.groupBy (fun (a,_) -> a)
|> Seq.map (fun (_,se) -> se |> Seq.map (snd));;
val it : seq<seq<int>> =
seq
[seq [0; 1; 2; 3; ...]; seq [5; 6; 7; 8; ...]; seq [10; 11; 12; 13; ...];
seq [15; 16; 17; 18; ...]; ...]
Depending on how you think this may be easier to understand. Tomas' solution is probably more idiomatic F# though
A: Hurray, we can use List.chunkBySize, Seq.chunkBySize and Array.chunkBySize in F# 4, as mentioned by Brad Collins and Scott Wlaschin.
A: Implementing this function using the seq<_> type idiomatically is difficult - the type is inherently mutable, so there is no simple nice functional way. Your version is quite inefficient, because it uses Skip repeatedly on the sequence. A better imperative option would be to use GetEnumerator and just iterate over elements using IEnumerator. You can find various imperative options in this snippet: http://fssnip.net/1o
If you're learning F#, then it is better to try writing the function using F# list type. This way, you can use idiomatic functional style. Then you can write batchesOf using pattern matching with recursion and accumulator argument like this:
let batchesOf size input =
// Inner function that does the actual work.
// 'input' is the remaining part of the list, 'num' is the number of elements
// in a current batch, which is stored in 'batch'. Finally, 'acc' is a list of
// batches (in a reverse order)
let rec loop input num batch acc =
match input with
| [] ->
// We've reached the end - add current batch to the list of all
// batches if it is not empty and return batch (in the right order)
if batch <> [] then (List.rev batch)::acc else acc
|> List.rev
| x::xs when num = size - 1 ->
// We've reached the end of the batch - add the last element
// and add batch to the list of batches.
loop xs 0 [] ((List.rev (x::batch))::acc)
| x::xs ->
// Take one element from the input and add it to the current batch
loop xs (num + 1) (x::batch) acc
loop input 0 [] []
As a footnote, the imperative version can be made a bit nicer using computation expression for working with IEnumerator, but that's not standard and it is quite advanced trick (for example, see http://fssnip.net/37).
A: A friend asked me this a while back. Here's a recycled answer. This works and is pure:
let batchesOf n =
Seq.mapi (fun i v -> i / n, v) >>
Seq.groupBy fst >>
Seq.map snd >>
Seq.map (Seq.map snd)
Or an impure version:
let batchesOf n =
let i = ref -1
Seq.groupBy (fun _ -> i := !i + 1; !i / n) >> Seq.map snd
These produce a seq<seq<'a>>. If you really must have an 'a list list as in your sample then just add ... |> Seq.map (List.ofSeq) |> List.ofSeq as in:
> [1..17] |> batchesOf 5 |> Seq.map (List.ofSeq) |> List.ofSeq;;
val it : int list list = [[1; 2; 3; 4; 5]; [6; 7; 8; 9; 10]; [11; 12; 13; 14; 15]; [16; 17]]
Hope that helps!
A: This isn't perhaps idiomatic but it works:
let batchesOf n l =
let _, _, temp', res' = List.fold (fun (i, n, temp, res) hd ->
if i < n then
(i + 1, n, hd :: temp, res)
else
(1, i, [hd], (List.rev temp) :: res))
(0, n, [], []) l
(List.rev temp') :: res' |> List.rev
A: Here's a simple implementation for sequences:
let chunks size (items:seq<_>) =
use e = items.GetEnumerator()
let rec loop i acc =
seq {
if i = size then
yield (List.rev acc)
yield! loop 0 []
elif e.MoveNext() then
yield! loop (i+1) (e.Current::acc)
else
yield (List.rev acc)
}
if size = 0 then invalidArg "size" "must be greater than zero"
if Seq.isEmpty items then Seq.empty else loop 0 []
let s = Seq.init 10 id
chunks 3 s
//output: seq [[0; 1; 2]; [3; 4; 5]; [6; 7; 8]; [9]]
A: My method involves converting the list to an array and recursively chunking the array:
let batchesOf (sz:int) lt =
let arr = List.toArray lt
let rec bite curr =
if (curr + sz - 1 ) >= arr.Length then
[Array.toList arr.[ curr .. (arr.Length - 1)]]
else
let curr1 = curr + sz
(Array.toList (arr.[curr .. (curr + sz - 1)])) :: (bite curr1)
bite 0
batchesOf 5 [1 .. 17]
[[1; 2; 3; 4; 5]; [6; 7; 8; 9; 10]; [11; 12; 13; 14; 15]; [16; 17]]
A: I found this to be a quite terse solution:
let partition n (stream:seq<_>) = seq {
let enum = stream.GetEnumerator()
let rec collect n partition =
if n = 1 || not (enum.MoveNext()) then
partition
else
collect (n-1) (partition @ [enum.Current])
while enum.MoveNext() do
yield collect n [enum.Current]
}
It works on a sequence and produces a sequence. The output sequence consists of lists of n elements from the input sequence.
A: You can solve your task with analog of Clojure partition library function below:
let partition n step coll =
let rec split ss =
seq {
yield(ss |> Seq.truncate n)
if Seq.length(ss |> Seq.truncate (step+1)) > step then
yield! split <| (ss |> Seq.skip step)
}
split coll
Being used as partition 5 5 it will provide you with sought batchesOf 5 functionality:
[1..17] |> partition 5 5;;
val it : seq<seq<int>> =
seq
[seq [1; 2; 3; 4; ...]; seq [6; 7; 8; 9; ...]; seq [11; 12; 13; 14; ...];
seq [16; 17]]
As a premium by playing with n and step you can use it for slicing overlapping batches aka sliding windows, and even apply to infinite sequences, like below:
Seq.initInfinite(fun x -> x) |> partition 4 1;;
val it : seq<seq<int>> =
seq
[seq [0; 1; 2; 3]; seq [1; 2; 3; 4]; seq [2; 3; 4; 5]; seq [3; 4; 5; 6];
...]
Consider it as a prototype only as it does many redundant evaluations on the source sequence and not likely fit for production purposes.
A: This version passes all my tests I could think of including ones for lazy evaluation and single sequence evaluation:
let batchIn batchLength sequence =
let padding = seq { for i in 1 .. batchLength -> None }
let wrapped = sequence |> Seq.map Some
Seq.concat [wrapped; padding]
|> Seq.windowed batchLength
|> Seq.mapi (fun i el -> (i, el))
|> Seq.filter (fun t -> fst t % batchLength = 0)
|> Seq.map snd
|> Seq.map (Seq.choose id)
|> Seq.filter (fun el -> not (Seq.isEmpty el))
I am still quite new to F# so if I'm missing anything - please do correct me, it will be greatly appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: css float not behaving in IE7 Hi I know IE7 css float issues have been asked here a few times but I still can't resolve my issue.
Please have a look at this page. I'm using IE9 in IE7 mode and have changed the widths of the divs and the items inside them, checked the clear:lefts and the heights but the main div won't float to the left of the nav.
Can anyone spot the cause?
A: Taking out the #main { clear: left; } and removing the .narrow#main { margin-top: -40px; } did it for me.
At least, it seems to work in IE9's IE7 mode.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: OnMouseOver DIV trouble Ok so my basic problem is as follows. I have an image that causes everything else on the page disable using a blank div with a z-index. This is during a mouseover event of the image. Next the code goes into setting the z-index on the div that I want to be able to click or mouseover. Also I wrapping these images in a div that is used for a mouseout event to hide the images I do not want to show.
However when mousing over the images or text inside the div it causes the mouseout event to trigger. I have looked into event bubbling but it does not seem to be what is happening. Is there a way to turn off the mouseout event to object inside of the div with the mouseover event?
Long story short I need to make a mouseout event not trigger on nested items.
Thanks in advance.
A: Instead of using mouseout you may go this way:
*
*when blocking the UI by overlaying the page with the blank div observe the mouseover-event of the wrapper-div
*When mouseover fires on the wrapper-div start observing the mouseover-event of the blank div
*When the mouseover fires on the blank div reset the page(remove the blank div)
The approach should be clear, if the mouse is over the blank div it must be outside the wrapper-div.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MapView throwing IllegalArgumentException - Wrong Image Size: 192 192 I'm getting excessive crash reports from users on a Samsung Vibrant Galaxy S. After searching around for solutions to this issue, the only thing I came across was an open issue over at Google Code: http://code.google.com/p/android/issues/detail?id=4599
The thread suggests extending MapView and catching the exceptions. Is this the best approach, or is there something better? I'd like to completely fix this issue rather than throw a bandage on it.
Here's the Stack Trace:
java.lang.IllegalArgumentException: wrong image size: 192 192
at com.google.googlenav.map.MapTile.getImage(Unknown Source)
at com.google.googlenav.map.Map.drawTile(Unknown Source)
at com.google.googlenav.map.Map.drawMapBackground(Unknown Source)
at com.google.googlenav.map.Map.drawMap(Unknown Source)
at com.google.android.maps.MapView.drawMap(MapView.java:1048)
at com.google.android.maps.MapView.onDraw(MapView.java:486)
at android.view.View.draw(View.java:6597)
at android.view.ViewGroup.drawChild(ViewGroup.java:1533)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1260)
at android.view.ViewGroup.drawChild(ViewGroup.java:1531)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1260)
at android.view.View.draw(View.java:6600)
at android.widget.FrameLayout.draw(FrameLayout.java:352)
at android.view.ViewGroup.drawChild(ViewGroup.java:1533)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1260)
at android.view.View.draw(View.java:6600)
at android.widget.FrameLayout.draw(FrameLayout.java:352)
at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1884)
at android.view.ViewRoot.draw(ViewRoot.java:1374)
at android.view.ViewRoot.performTraversals(ViewRoot.java:1139)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1658)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4363)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:862)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
at dalvik.system.NativeStart.main(Native Method)
A: Hopefully someone else will show up with another answer to prove me wrong, but in my personal experience with device-specific issues, catching the exceptions often seems to be the best you can do.
Edit regarding your comment below: That is a point, and I did run into some new problems with specific devices using customised WebView code when extending WebView once.
There are a ton of people on here with far more experience than me, and I hope one of them will drop in to give a more definitive answer or less hacky solution, but if necessary, you could always use android.os.Build.DEVICE, android.os.Build.MODEL and/or android.os.Build.PRODUCT to determine whether the app is running on a Samsung Vibrant Galaxy S, and (via reflection) use the custom MapView class only if it is.
A: May be You have done mistake here, so change the code to correct form, or enter
<uses-library android:name="com.google.android.maps" // in manifest under inside applicaiton tag
android:required="true"/>
//wrong usage of activity
public class A extends Actvitiy
{
}
//correct usage
public class A extedns MapsActivity
{
//your all program...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: android- usage of SP I have doubts regarding the following ones. please clarify it.
1. What is the problem if i set the text of text view in xml file instead of java file(String.xml)?
2. What is the usage of SP? Give me one example.can anybody helpme.
thanks
A: Regarding your first question: strings.xml file is used for storing string resources, especially for the sake of resolving the localization issues. You can store multiple strings.xml files inside your project in different folders depending on the localization. This makes translating your application to a different language easier: you just create another strings.xml file, translate all the strings and put it inside the corresponding folder. Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I enable spell check feature in HTML text area? I want to enable spell check feature in HTML text areas. I am using ColdFusion. Is this possible?
A: You could try to enable native spellcheck support for input forms, like this:
<input type="text" size="50" spellcheck="true">
<textarea spellcheck="true"></textarea>
You can also designate a correct language dictionary to use. If not specified, the browser's default language dictionary will be used. You can override browser defaults by specifying the lang attribute .
<input type="text" spellcheck="true" lang="en">
A: I have used Foundeo's spell checker before. Very easy to integrate and customise.
A: The browser will automatically spell check if it supports that feature. For JavaScript based spell checking, see here:
http://www.javascriptspellcheck.com/
-Sunjay
A: If using React, you have to capitalize the c:
spellCheck='true'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Install apk file via code forcibly I have a scenario where I have to install an apk file through code and I dont want the user to have option either install or cancel it. For ex, I want to create an app similar to the android market. In that app, I will display list of my applications and display an install button for each app. When the user clicks the install button, the app should be installed directly without asking the user to install or not. I found a link which have a method installPackage in PackageManager. I am getting compilation error when I use it. It seems that it is remove from the android framework.
Is there nay possibility to do this ?
thanks,
Senthil
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Alternative to using Thread.current in API wrapper for Rails I've developed an application that allows our customers to create their own membership protected websites. My application then connects to an outside API service (customer specific api_key/api_url) to sync/update/add data to this other service. Well, I've had an API wrapper written for this other service that has worked up to this point. However, I'm now seeing very random drops where the connection is nil. Here is how I'm currently using the connection:
I have a xml/rpc connection class
class ApiConnection
attr_accessor :api_url, :api_key, :retry_count
def initialize(url, key)
@api_url = url
@api_key = key
@retry_count = 1
end
def api_perform(class_type, method, *args)
server = XMLRPC::Client.new3({'host' => @api_url, 'path' => "/api/xmlrpc", 'port' => 443, 'use_ssl' => true})
result = server.call("#{class_type}.#{method}", @api_key, *args)
return result
end
end
I also have a module that I can include in my models to access and call the api methods
module ApiService
# Set account specific ApiConnection obj
def self.set_account_api_conn(url, key)
if ac = Thread.current[:api_conn]
ac.api_url, ac.api_key = url, key
else
Thread.current[:api_conn] = ApiConnection.new(url, key)
end
end
########################
### Email Service ###
########################
def api_email_optin(email, reason)
# Enables you to opt contacts in
Thread.current[:api_conn].api_perform('APIEmailService', 'optIn', email, reason)
end
### more methods here ###
end
Then in the application controller I create a new ApIConnection object on every request using a before filter which sets the Thread.current[:api_conn]. This is because I have hundreds of customers each with their own api_key and api_url, using the application at the same time.
# In before_filter of application controller
def set_api_connection
Thread.current[:api_conn] = ApiService.set_account_api_conn(url, key)
end
Well my question is that I've read that using Thread.current is not the most ideal way of handling this, and I'm wondering if this is the cause for the ApiConnection to be nil on random requests. So I would like to know how I could better setup this wrapper.
A: Answer 1
I'd expect that the problem is the next request coming before the connection has finished, and then the before_filter overwrites the connection for the still ongoing connection. I'd try to stay away from threads. It's easier to fork_off, but there's certain caveats to that as well, especially regarding performance.
I try to move logic like this over to a background job of some sort. A common solution is delayed job https://github.com/collectiveidea/delayed_job that way you don't have to mess with threads and it's more robust and easy to debug. You can then start background jobs to asynchronously sync the service whenever somebody logs in.
@account.delay.optin_via_email(email,user)
This will serialize the account, save it to the job queue, where it will be picked up by delayed job unserialized and the method after delay will be called. You can have any number of background jobs, and even some job queues dedicated to certain types of actions (via using job priorities - let's say two bj for high prio jobs and one dedicated to low prio jobs)
Answer 2
Just make it as an object instead
def before_filter
@api_connection = ApiConnection.new(url, key)
end
then you can use that connection in your controller methods
def show
#just use it straight off
@api_connection.api_perform('APIEmailService', 'optIn', email, reason)
# or send the connection as a parameter to some other class
ApiService.do_stuff(@api_connection)
end
Answer 3
The easiest solution might just be to create the api connection whenever you need it
class User < ActiveRecord::Base
def api_connection
# added caching of the the connection in object
# doing this makes taking a block a little pointless but making methods take blocks
# makes the scope of incoming variables more explicit and looks better imho
# might be just as good to not keep @conn as an instance variable
@conn = ApiConnection.new(url, key) unless @conn
if block_given?
yield(@conn)
else
@conn
end
end
end
that way you can easily just forget about the creation of the connection and have a fresh one handy. There might be performance penalities with this but I suspect that they are insignificant unless there's an extra login request
@user.api_connection do { |conn| conn.optin_via_email(email,user) }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Changing the Value of a MySQL ENUM Value, Throughout a Table I'm wondering if it is possible to change an ENUM value throughout a table, so that in all the rows where said ENUM value is represented, the change is made as well.
A: If you want to change the value of an enum:
Suppose your old enum was:
ENUM('English', 'Spanish', 'Frenchdghgshd', 'Chinese', 'German', 'Japanese')
To change that use:
-- Add a new enum value
ALTER TABLE `tablename` CHANGE `fieldname` `fieldname` ENUM
('English', 'Spanish', 'Frenchdghgshd', 'Chinese', 'German', 'Japanese', 'French');
-- Update the table to change all the values around.
UPDATE tablename SET fieldname = 'French' WHERE fieldname = 'Frenchdghgshd';
-- Remove the wrong enum from the definition
ALTER TABLE `tablename` CHANGE `fieldname` `fieldname` ENUM
('English', 'Spanish', 'Chinese', 'German', 'Japanese', 'French');
MySQL will probably go through all the rows in your table trying to update stuff, I've heard stories of a planned optimization around that, but I'm not sure if that actually happened.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: 'Freezing' Arrays in Javascript? Since the ECMA-262 specifications Javascript has gained the Object.freeze() method, which allows for objects, whose properties can not be changed, added or removed.
var obj = {'a':1, 'b:2'};
Object.freeze(obj);
Object.isFrozen(obj); // returns true
obj.a = 10; // new assignment has no affect
obj.a; // returns 1
So far so good.
I am wondering, whether freeze() should also work on Arrays.
var arr = [1, 2];
Object.freeze(arr);
Object.isFrozen(arr); // returns true
arr[0] = 10;
arr; // returns [10, 2] ... ouch!
Maybe I am wrong, but I was under the impression, that Array inherits from Object.
typeof obj // "object"
typeof arr // "object"
Any ideas, pointers, enlightenments would be highly appreciated.
A: Yes, it is applicable to arrays too.
const arr = [1,2,3,4];
Object.freeze(arr);
Object.isFrozen(arr)// true
arr.push(5) // you will get a type error
arr.pop() // you will get a type error
A: Yes, freeze should work for Arrays, the behavior you are experiencing is clearly an implementation bug.
This bug might be related to the fact that array objects implement a custom [[DefineOwnProperty]] internal method (the magic that makes the length property work).
I just tested it on two implementations and it works properly (Chrome 16.0.888, and Firefox Aurora 8.02a).
About your second question, well, array objects inherit from Array.prototype which inherits from Object.prototype, for example, you can access non shadowed methods from Object.prototype directly on array objects:
['a'].hasOwnProperty('0'); // true
But this isn't related about how the typeof works, this operator will return 'object' for any object intance, regardless its kind, and for the null value, which people has always complained about.
The rest of possible return values of the typeof operator, correspond to the primitive types of the language, Number, String, Boolean, Symbol and Undefined.
A: Instead of freeze, use spread operator to copy things without modifying them (if you are using a transpiler, of course):
const second = {
...first,
test: 20
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "63"
} |
Q: Possible to control frame of a MovieClip that's in a Scroll Pane component? Is there a way to control the frames of a movieclip that's in the scroll pane component?
On my stage I've got four buttons setup.
I've got the following actionscript but get an error.
import flash.events.MouseEvent;
scrollPane.source = pm_mc;
scrollPane.setSize(975, 500);
scrollPane.scrollDrag = true;
start_but.addEventListener(MouseEvent.CLICK, start);
function start(e:MouseEvent):void
{
scrollPane.pm_mc.gotoAndStop(1);
}
previous_but.addEventListener(MouseEvent.CLICK, previous);
function previous(e:MouseEvent):void
{
scrollPane.pm_mc.prevFrame();
}
next_but.addEventListener(MouseEvent.CLICK, next);
function next(e:MouseEvent):void
{
scrollPane.pm_mc.nextFrame();
}
end_but.addEventListener(MouseEvent.CLICK, end);
function end(e:MouseEvent):void
{
scrollPane.pm_mc.gotoAndStop(31);
}
stop();
The errors I get are all the same:
Access of possibly undefined property pm_mc through a reference with static type fl.containers:ScrollPane
I'm still very much learning AS3.
Thanks in advance for any responses.
A: You need to refer to the movie clip as:
scrollPane.source.gotoAndStop(1);
So in your code:
Replace scrollPane.pm_mc with scrollPane.source.
Update
I guess I understand what you are trying to do now. You have a symbol in your library (which is not on your stage) and you want to create an instance of it and add it to the scrollPane. If I am right try this.
import flash.events.MouseEvent;
scrollPane.source = new pm_mc();
scrollPane.setSize(975, 500);
scrollPane.scrollDrag = true;
start_but.addEventListener(MouseEvent.CLICK, start);
function start(e:MouseEvent):void
{
scrollPane.source.gotoAndStop(1);
}
previous_but.addEventListener(MouseEvent.CLICK, previous);
function previous(e:MouseEvent):void
{
scrollPane.source.prevFrame();
}
next_but.addEventListener(MouseEvent.CLICK, next);
function next(e:MouseEvent):void
{
scrollPane.source.nextFrame();
}
end_but.addEventListener(MouseEvent.CLICK, end);
function end(e:MouseEvent):void
{
scrollPane.source.gotoAndStop(31);
}
stop();
Note the new pm_mc(). It creates an instance of the library symbol (a MovieClip).
Also you can refer to the scrollPane contents like this
((MovieClip)(scrollPane.content)).nextFrame();
Both the content and the source should work for your purpose.
A: you are getting errors because you are getting movieclip from scrollPane in wrong way. check following code.
start_but.addEventListener(MouseEvent.CLICK, start);
function start(e:MouseEvent):void
{
(Object(scrollPane.content)).gotoAndStop(1);
}
i hope it will work...............
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding a custom object to NIB in XCode 4.1 is way too much complicated compared to 3.2 In XCode 3.2, IB has a Classes tab in the Library to let you add your own class to nib file. But in XCode 4.1 that tab is disappeared. There is an item called "Custom Objects" in object library but I never figure out how to use it.
So in XCode 4.1 if I want to add my own class to nib I have to drag general object then change it in Identity inspector. Way too much complicated and not straightforward at all.
Anyone knows why xcode 4.1 introduced this change ?
Thanks.
A: The typical way things work is the more simple something is, the less customization you can do. I agree I dislike the new IB, although it does make room for more customization.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: java.lang.StackOverflowError while using a RegEx to Parse big strings This is my Regex
((?:(?:'[^']*')|[^;])*)[;]
It tokenizes a string on semicolons. For example,
Hello world; I am having a problem; using regex;
Result is three strings
Hello world
I am having a problem
using regex
But when I use a large input string I get this error
Exception in thread "main" java.lang.StackOverflowError
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4168)
at java.util.regex.Pattern$Loop.match(Pattern.java:4295)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4227)
at java.util.regex.Pattern$BranchConn.match(Pattern.java:4078)
at java.util.regex.Pattern$CharProperty.match(Pattern.java:3345)
at java.util.regex.Pattern$Branch.match(Pattern.java:4114)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4168)
at java.util.regex.Pattern$Loop.match(Pattern.java:4295)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4227)
How is this caused and how can I solve it?
A: It might help to add a + after the [^;], so that you have fewer repetitions.
Isn't there also some construct that says “if the regular expression matched up to this point, don't backtrace”? Maybe that comes in handy, too. (Update: it is called possessive quantifiers).
A completely different alternative is to write a utility method called splitQuoted(char quote, char separator, CharSequence s) that explicitly iterates over the string and remembers whether it has seen an odd number of quotes. In that method you could also handle the case that the quote character might need to be unescaped when it appears in a quoted string.
'I'm what I am', said the fox; and he disappeared.
'I\'m what I am', said the fox; and he disappeared.
'I''m what I am', said the fox; and he disappeared.
A: Unfortunately, Java's builtin regex support has problems with regexes containing repetitive alternative paths (that is, (A|B)*). This is compiled into a recursive call, which results in a StackOverflow error when used on a very large string.
A possible solution is to rewrite your regex to not use a repititive alternative, but if your goal is to tokenize a string on semicolons, you don't need a complex regex at all really, just use String.split() with a simple ";" as the argument.
A: If you really need to use a regex that overflows your stack, you can increase the size of your stack by passing something like -Xss40m to the JVM.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "46"
} |
Q: Dynamic highlight color in ListView How can I make background highlight color dependent on some property of ListViewItem?
A: This is an issue that people often ask for. Actually, for some reasons, when an item is selected in a ListView or ListBox, the Background color is not the one that is changed. It is a bit more tricky. In fact you need to override the value of the static color resources to which the item template is bound. So to change the higlighting colors of the items you have to do like this:
<ListView>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Orange"/>
</Style.Resources>
</Style>
</ListView.ItemContainerStyle>
</List>
Here is a more developed explanation: Trigger for ListBoxItem
A: EDIT:
For changing selected background, you will have to override the ListViewItem's Template.
See this... http://msdn.microsoft.com/en-us/library/ms788717(v=vs.90).aspx.
Replace the {StaticResource SelectedBackgroundBrush} with your preferred background brush in the template.
To change backgrounds based on ANY other property that the control template does not rely upon, You can use triggers ...
<ListView ...>
<ListView.Resources>
<Style TargetType="{x:Type ListViewItem}">
<Style.Triggers>
<Trigger Property="SomeListViewItemProperty" Value="Value1">
<Setter Property="Background" Value="Red" />
</Trigger>
<Trigger Property="SomeListViewItemProperty" Value="Value2">
<Setter Property="Background" Value="Yellow" />
</Trigger>
</Style.Triggers>
</Style>
<ListView.Resources>
</ListView>
I hope this answers your question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I create a custom assignment using a replacement function? I have defined a function called once as follows:
once <- function(x, value) {
xname <- deparse(substitute(x))
if(!exists(xname)) {
assign(xname, value, env=parent.frame())
}
invisible()
}
The idea is that value is time-consuming to evaluate, and I only want to assign it to x the first time I run a script.
> z
Error: object 'z' not found
> once(z, 3)
> z
[1] 3
I'd really like the usage to be once(x) <- value rather than once(x, value), but if I write a function once<- it gets upset that the variable doesn't exist:
> once(z) <- 3
Error in once(z) <- 3 : object 'z' not found
Does anyone have a way around this?
ps: is there a name to describe functions like once<- or in general f<-?
A: If you are willing to modify your requirements slightly to use square brackets rather than parentheses then you could do this:
once <- structure(NA, class = "once")
"[<-.once" <- function(once, x, value) {
xname <- deparse(substitute(x))
pf <- parent.frame()
if (!exists(xname, pf)) assign(xname, value, pf)
once
}
# assigns 3 to x (assuming x does not currently exist)
once[x] <- 3
x # 3
# skips assignment (since x now exists)
once[x] <- 4
x # 3
A: As per item 3.4.4 in the R Language Reference, something like a names replacement is evaluated like this:
`*tmp*` <- x
x <- "names<-"(`*tmp*`, value=c("a","b"))
rm(`*tmp*`)
This is bad news for your requirement, because the assignment will fail on the first line (as x is not found), and even if it would work, your deparse(substitute) call will never evaluate to what you want it to.
Sorry to disappoint you
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Foreach loop repetition problem This code gives four 4's and I only want one 4.. Can anyone identify the problem??
$value1 = "0";
$entries = array($var1_1a>$var1_1b, $var1_2a>$var1_2b, $var1_3a>$var1_3b,
$var3_1a>$var3_1b, $var3_2a>$var3_2b, $var3_3a>$var3_3b);
if (count($entries) == 0)
echo "0";
else foreach($entries as $entry)
{
if($entry > $value1)
{
echo array_sum($entries);
}
}
A: $value1 = "0";
$entries = array($var1_1a>$var1_1b, $var1_2a>$var1_2b, $var1_3a>$var1_3b,
$var3_1a>$var3_1b, $var3_2a>$var3_2b, $var3_3a>$var3_3b);
if (count($entries) == 0)
echo "0";
else foreach($entries as $entry)
{
if($entry > $value1)
{
echo array_sum($entries);
break; //I think it will checking condition repeatedly
}
}
A: Why do you even have a foreach loop? echo array_sum($entries); is independent of the values you're looping through.
This should be adequate:
$entries = array($var1_1a>$var1_1b, $var1_2a>$var1_2b, $var1_3a>$var1_3b,
$var3_1a>$var3_1b, $var3_2a>$var3_2b, $var3_3a>$var3_3b);
echo array_sum($entries);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQuery problem with HTML entities I use this code to receive data from an php file
$.ajax({
url: "includes/cpf.inc.php",
type: "POST",
data:{p_request:"1bdd249a5d673a721be31d7444af81af1af4c5b6",
p_userid:"<?php echo $dbu_userid; ?>",
p_curpass:$("#txtcurpass").val(),
p_newpass:$("#txtnewpass").val(),
p_cnewpass:$("#txtcnewpass").val()
},
cache:false,
success:function(msg){
$("#chPassLoad").css("visibility","hidden");
wilPrompt("#chpasStat",msg.substr(0,1),msg.substr(2));
if(msg.substr(0,1)=="0"){
$("#txtcurpass").attr("value","");
$("#txtnewpass").attr("value","");
$("#txtcnewpass").attr("value","");
}
},
beforeSend:function(){
$("#chPassLoad").css("visibility","visible");
}
});
and the data that will be receive from cpf.inc.php contains html entities like this
おはようございます漢字
and that html entities are Japanese characters
おはようございます漢字
now my problem is when I will receive data from the variable msg it returns something like this
pX[hς܂
Is there any code I need to append on the $.ajax parameters to encode this html entities correctly? thanks
A: I am guessing that you need to set the charset for the request.. here is how you can do it:
$.ajaxSetup({
'beforeSend' : function(xhr) {
xhr.overrideMimeType('text/html; charset=UTF-8'); //set the right charset here
},
});
or
$.ajax({
url: "includes/cpf.inc.php",
type: "POST",
data:{p_request:"1bdd249a5d673a721be31d7444af81af1af4c5b6",
p_userid:"<?php echo $dbu_userid; ?>",
p_curpass:$("#txtcurpass").val(),
p_newpass:$("#txtnewpass").val(),
p_cnewpass:$("#txtcnewpass").val()
},
cache:false,
success:function(msg){
$("#chPassLoad").css("visibility","hidden");
wilPrompt("#chpasStat",msg.substr(0,1),msg.substr(2));
if(msg.substr(0,1)=="0"){
$("#txtcurpass").attr("value","");
$("#txtnewpass").attr("value","");
$("#txtcnewpass").attr("value","");
}
},
beforeSend:function(xhr) {
xhr.overrideMimeType('text/html; charset=UTF-8');
$("#chPassLoad").css("visibility","visible");
}
});
A: I faced same problem using PHP base64_encode($str) to pass XML code to jquery and decode the string with jQuery.base64. JPN fonts get problem / Chinese fonts is normal.
Use htmlentities($str,,'utf-8') instead of base64_encode is OK.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Changing the Telerik MVC Grid columns dynamically on client-side I would like to show my table data in grid. The table has more than 50 columns. By default they are displayed fine but I need a way to hide/show columns which are not required on screen.
So is there any way to achieve this? I think right clicking on the header should show all headers in a list box, allowing selection of which columns we want, then refresh the grid.
Please let me know if Telerik supports this and, if so, how?
A: No builtin feature available and this is one of many reasons why we are still thinking about other grids instead of telerik.
In the demo site there is a page where they show all the column names with checkboxes on top of the grid and you can check/uncheck to show/hide columns. see that sample source code, is simple to implement but still is custom code to add manually. I love the devexpress grid with customization popup and columns dragdrop from there but nothing like that for us in Telerik :-(
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: BST Insert C++ Help typedef struct treeNode {
treeNode* left;
treeNode* right;
int data;
treeNode(int d) {
data = d;
left = NULL;
right = NULL;
}
}treeNode;
void insert(treeNode *root, int data) {
if (root == NULL) {
cout << &root;
root = new treeNode(data);
}
else if (data < root->data) {
insert(root->left, data);
}
else {
insert(root->right, data);
}
}
void inorderTraversal(treeNode* root) {
if (root == NULL)
return;
inorderTraversal(root->left);
cout<<root->data;
inorderTraversal(root->right);
}
int main() {
treeNode *root = new treeNode(1);
cout << &root << endl;
insert(root, 2);
inorderTraversal(root);
return 0;
}
So I'm pretty tired, but I was whipping some practice questions up for interview prep and for some reason this BST insert is not printing out that any node was added to the tree. Its probably something im glossing over with the pointers, but I can't figure it out. any ideas?
A: void insert(treeNode *root, int data) {
if (root == NULL) {
cout << &root;
root = new treeNode(data);
}
This change to root is lost as soon as the function ends, it does not modify the root passed as argument but its own copy of it.
A: Take note that when u insert the node, use pointer to pointer (pointer alone is not enough):
So, here is the fixed code:
void insert(treeNode **root, int data) {
if (*root == NULL) {
cout << root;
*root = new treeNode(data);
}
else if (data < (*root)->data) {
insert(&(*root)->left, data);
}
else {
insert(&(*root)->right, data);
}
}
And in main:
int main() {
treeNode *root = new treeNode(1);
cout << &root << endl;
insert(&root, 2);
inorderTraversal(root);
return 0;
}
A: Your logic is correct!
The only issue is that when you create a local variable, even if it is a pointer, its scope is local to the function. In your main:
...
insert(root, 2);
...
function call sends a copy of the root which is a pointer to treeNode (not the address of root). Please note that
void insert(treeNode *root, int data)
gets a treeNode pointer as an argument (not the address of the pointer). Attention: This function call may look like "call by pointer" (or reference) but it is actually "call by value". The root you define in the main function and the root inside the insert method have different addresses in the stack (memory) since they are different variables. The former is in main function stack in the memory while the latter is in insert method. Therefore once the function call insert finishes executing, its stack is emptied including the local variable root. For more details on memory refer to: stacks/heaps.
Of course the data in the memory that you allocated using:
*root = new treeNode(data);
still stays in the heap but you have lost the reference to (address of) it once you are out of the insert function.
The solution is either passing the address of original root to the function and modifying it (as K-ballo and dip has suggested) OR returning the modified local root from the function. For the first approach please refer to the code written by dip in his/her answer.
I personally prefer returning the modified root from the function since I find it more convenient especially when implementing other common BST algorithms. Here is your function with a slight modification of your original code:
treeNode* insert(treeNode *root, int data) {
if (root == NULL) {
root = new treeNode(data);
}
else if (data < root->data) {
root->left=insert(root->left, data);
}
else {
root->right=insert(root->right, data);
}
return treeNode;
}
The function call in main will be:
int main() {
treeNode *root = new treeNode(1);
cout << &root << endl;
root = insert(root, 2);
inorderTraversal(root);
return 0;
}
Hope that helps!
A: After a while seeing some complicated methods of dealing with the Binary tree i wrote a simple program that can create, insert and search a node i hope it will be usefull
/*-----------------------Tree.h-----------------------*/
#include <iostream>
#include <queue>
struct Node
{
int data;
Node * left;
Node * right;
};
// create a node with input data and return the reference of the node just created
Node* CreateNode(int data);
// insert a node with input data based on the root node as origin
void InsertNode (Node* root, int data);
// search a node with specific data based on the root node as origin
Node* SearchNode(Node* root, int data);
here we define the node structure and the functions mentioned above
/*----------------------Tree.cpp--------------*/
#include "Tree.h"
Node* CreateNode(int _data)
{
Node* node = new Node();
node->data=_data;
node->left=nullptr;
node->right=nullptr;
return node;
}
void InsertNode(Node* root, int _data)
{
// create the node to insert
Node* nodeToInsert = CreateNode(_data);
// we use a queue to go through the tree
std::queue<Node*> q;
q.push(root);
while(!q.empty())
{
Node* temp = q.front();
q.pop();
//left check
if(temp->left==nullptr)
{
temp->left=nodeToInsert;
return;
}
else
{
q.push(temp->left);
}
//right check
if(temp->right==nullptr)
{
temp->right=nodeToInsert;
return;
}
else
{
q.push(temp->right);
}
}
}
Node* SearchNode(Node* root, int _data)
{
if(root==nullptr)
return nullptr;
std::queue<Node*> q;
Node* nodeToFound = nullptr;
q.push(root);
while(!q.empty())
{
Node* temp = q.front();
q.pop();
if(temp->data==_data) nodeToFound = temp;
if(temp->left!=nullptr) q.push(temp->left);
if(temp->right!=nullptr) q.push(temp->right);
}
return nodeToFound;
}
int main()
{
// Node * root = CreateNode(1);
// root->left = CreateNode(2);
// root->left->left = CreateNode(3);
// root->left->left->right = CreateNode(5);
// root->right = CreateNode(4);
// Node * node = new Node();
// node = SearchNode(root,3);
// std::cout<<node->right->data<<std::endl;
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Detect USB tethering on android Is there any way to know (pro grammatically) in your Activity/Application that the user has enabled USB tethering on his phone?
A: you can also use reflection to access the hidden function for setting usb tethering.
Here is my code.
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Log.d(TAG,"test enable usb tethering");
String[] available = null;
int code=-1;
Method[] wmMethods = cm.getClass().getDeclaredMethods();
for(Method method: wmMethods){
if(method.getName().equals("getTetherableIfaces")){
try {
available = (String[]) method.invoke(cm);
break;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
}
}
for(Method method: wmMethods){
if(method.getName().equals("tether")){
try {
code = (Integer) method.invoke(cm, available[0]);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
break;
}
}
if (code==0)
Log.d(TAG,"Enable usb tethering successfully!");
else
Log.d(TAG,"Enable usb tethering failed!");
For disabling usb tethering, you just need to change the reflection method name "getTetherableIfaces" to "getTetheredIfaces", change "tether" to "untether".
Please check.
A: Looking through the Settings.System documentation points to the answer being no, its not possible to do this.
Link to said documentation
A: This should work on all phones, confirmed on some Android 7,6 and 5 devices;
Method: interface rndisX (typically rndis0) only shows up when usb tethering is enabled.
Code Example:
private static boolean isTetheringActive(Context context){
try{
for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();){
NetworkInterface intf=en.nextElement();
for(Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){
InetAddress inetAddress=enumIpAddr.nextElement();
if(!intf.isLoopback()){
if(intf.getName().contains("rndis")){
return true;
}
}
}
}
}catch(Exception e){e.printStackTrace();}
return false;
}
A: Here is a solution to Listen for tethering state changes :
First you need to be familiar with BroadcastReceiver.
you can find a lot of tutorial (google : how to listen for connectivity changes ...)
In order to get the Tethering state update, you need to use a hidden filter action of Android (see ConnectivityManager)
and in your BroadcastReceiver class :
IntentFilter filter = new IntentFilter("android.net.conn.TETHER_STATE_CHANGED");
then register the filter to your BroadcastReceiver :
myApplicationContext.registerReceiver(this, filter);
on your onReceive(final Context context,final Intent intent) method, the Intent.extras information contains 3 arrays filled with the corresponding tethered network interface :
erroredArray / availableArray / activeArray
It's a little bit tricky but you can get the tethering status information.
In addition, you can do some reflexion on hidden function of Android code :
Search for getTetherableIfaces() in the Connectivity Manager.
Here is a link : https://github.com/android/platform_frameworks_base/blob/master/core/java/android/net/ConnectivityManager.java#L1604
A: You can get the Network Interfaces and check what is active like this:
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
NetworkInterface rndis = null;
NetworkInterface wlan = null;
while(interfaces.hasMoreElements()) {
NetworkInterface nif = interfaces.nextElement();
if(hasIP4Address(nif)) {
if(nif.getDisplayName().startsWith("rndis"))
rndis = nif;
else if (nif.getDisplayName().startsWith("wlan"))
wlan = nif;
}
}
// Let the user choose Wi-Fi or rndis connect
if (rndis != null) {
socket.setNetworkInterface(rndis);
Log.i(TAG, "Subscribe: with interface rndis");
} else if(wlan != null) {
socket.setNetworkInterface(wlan);
Log.i(TAG, "Subscribe: with interface wlan");
}
A: I have found that if I check for usb0 network interface
it only has an ip address once tethering has been set up.
public static String getIPAddressUsb(final boolean useIPv4) {
try {
final List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (final NetworkInterface intf : interfaces) {
if (intf.getDisplayName().startsWith("usb")) {
final List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (final InetAddress addr : addrs) {
final String sAddr = addr.getHostAddress().toUpperCase();
final boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
if (useIPv4) {
if (isIPv4) { return sAddr; }
} else {
if (!isIPv4) {
final int delim = sAddr.indexOf('%');
return delim < 0 ? sAddr : sAddr.substring(0, delim);
}
}
}
}
}
} catch (final Exception ex) {
// for now eat exceptions
}
return "";
}
boolean isUsbTethered(){
String ipAddr = MipnAndroidApplication.getIPAddressUsb(true);
if (ipAddr.length() == 0) {
Log.i(LOG_TAG, "tethering not enabled");
return false;
} else {
Log.i(LOG_TAG, "tethering enabled :)");
return true;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: C Build error when getting the value of sin() I have recently started learning C as a side project. I am working under OpenSuse with the latest NetBeans using the GCC as toolset for compiling.
One of the very first programs that I made was this:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
*
*/
int main(int argc, char** argv) {
double rad = 1;
double result = 0;
result = sin(rad);
return (EXIT_SUCCESS);
}
This is a simple, no-brainer example that should have worked without a problem. However, I get a Build Error: Exit code 2(error in line 18, undefined reference to sin) when trying to compile.
Interestingly enough, if I remove the assignment of the value of sin(rad) to result OR replace rad with a hard coded value, the program compiles just fine.
What am I doing wrong here?
A: In C, you need to link to the math library:
Add this to the command line options:
-lm
A: Be sure that your are linking with the math library.
$ gcc myprog.c -lm
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android :how to set Fixed no(5 ) of Rows shows in ListView then after Scroll? how to set Fixed no of Rows shows in ListView ? i want to set 5 Rows only show in Listview not all Rows. so how can i achive this Goal?
A: yes, you can achieve via adapter class, Try with following code in your adapter class.
public int getCount() {
return 5;
}
If you set this, the adapter class load only 5 items.
A: This can be achieved by setting the row item height to fixed dps and the List View height to be 5 times of row height in exact dps.
A: Here it is how I did it:
Step 1: Set fixed height to the item list ITEM_LIST_HEIGHT
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="25dp">
</TextView>
Step 2: Set fixed height to the list, more exactly LIST_HEIGHT = NUMBER_OF_ITEMS_TO_DISPLAY x ITEM_LIST_HEIGHT. For example for 6 items 150;
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="150dp"/>
I hope it helps !
A: You can custom your adapter. But I think your idea is SET MAX ITEM OF LIST VIEW. (I think it will better).
So you will custom your adapter look like:
private class CustomAdapter<T> extends ArrayAdapter<T> {
private static final int MAX_ROW_DISPLAY = 5;
private List<T> mItems;
public CustomAdapter(Context context, int resource, List<T> objects) {
super(context, resource, objects);
mItems = objects;
}
@Override
public int getCount() {
if (mItems == null) {
return 0;
}
return Math.min(MAX_ROW_DISPLAY, mItems.size());
}
}
Hope this help u !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: startActivityForResult is undefined for class CustomizeDialog extends Dialog I am working in android. i want to make a custom dialog in which i want to add a paypal button.
this is the code for my program:-
public class CustomizeDialog extends Dialog implements OnClickListener {
Button close;
String TAG="CustomizeDialog";
Context customize_dialog;
CheckoutButton launchSimplePayment;
public CustomizeDialog(Context context,String title_of_song,String artist_of_song,float price_of_song) {
super(context);
customize_dialog=context;
setContentView(R.layout.paypal_custom_dialog);
close = (Button) findViewById(R.id.paypal_close);
PayPal pp = PayPal.getInstance();
if (pp == null) {
try {
pp = PayPal.initWithAppID(context, "", PayPal.ENV_NONE);
} catch (IllegalStateException e) {
throw new RuntimeException(e);
}
pp.setShippingEnabled(false);
}
launchSimplePayment = pp.getCheckoutButton(context,
PayPal.BUTTON_118x24, CheckoutButton.TEXT_PAY);
LinearLayout lnr = (LinearLayout) findViewById(R.id.Paypal_Custom_Dialog_View);
launchSimplePayment.setOnClickListener( this);
lnr.addView(launchSimplePayment);
close.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == close)
dismiss();
if(v==launchSimplePayment)
{
PayPalPayment payment = new PayPalPayment();
payment.setSubtotal(new BigDecimal("2.25"));
payment.setCurrencyType("USD");
payment.setRecipient("kuntal_1316186174_biz@gmail.com");
payment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
Intent checkoutIntent =
PayPal.getInstance().checkout(payment,customize_dialog);
startActivityForResult(checkoutIntent, 1); **//this line is creating error that startActivityForResult() is undefined for type CustomizeDialog**
}
}
are we not apply CustomizeDialog() for a activity which is extending Dialog ? (as i done in my this program)
please suggest me what should i do for this ?
Thank you in advance...
A: You can use the Activity whose theme is Dialog. This way you can achieve startActivityForResult as well as make it look like Dialog.
A: this is my solution:-
*
*i changed the extends Dialog to Activity.
*I have changed the theme of activity in menifast file to dialog as follows:-
<activity android:name=".CustomizeDialog" android:label="@string/app_name"
android:theme="@android:style/Theme.Dialog" />
*and this is the code which i have changed:-
--
package com.pericent.musicapp;
import java.math.BigDecimal;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalActivity;
import com.paypal.android.MEP.PayPalPayment;
import com.paypal.android.MEP.PayPalAdvancedPayment;
import com.paypal.android.MEP.PayPalInvoiceData;
import com.paypal.android.MEP.PayPalInvoiceItem;
import com.paypal.android.MEP.PayPalReceiverDetails;
public class CustomizeDialog extends Activity implements OnClickListener {
Button close;
String TAG="CustomizeDialog";
CheckoutButton launchSimplePayment;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.paypal_custom_dialog);
Log.v(TAG, "i am gooing to perform close");
close = (Button) findViewById(R.id.paypal_close);
text_view_price.setText("Price : "+50);
PayPal pp = PayPal.getInstance();
if (pp == null) {
try {
pp = PayPal.initWithAppID(this, "", PayPal.ENV_NONE);
} catch (IllegalStateException e) {
throw new RuntimeException(e);
}
pp.setShippingEnabled(false);
}
launchSimplePayment = pp.getCheckoutButton(this,
PayPal.BUTTON_118x24, CheckoutButton.TEXT_PAY);
LinearLayout lnr = (LinearLayout) findViewById(R.id.Paypal_Custom_Dialog_View);
launchSimplePayment.setOnClickListener( this);
lnr.addView(launchSimplePayment);
close.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v==launchSimplePayment)
{
PayPalPayment payment = new PayPalPayment();
payment.setSubtotal(new BigDecimal("2.25"));
payment.setCurrencyType("USD");
payment.setRecipient("kuntal_1316186174_biz@gmail.com");
payment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
Intent checkoutIntent = PayPal.getInstance().checkout(payment,this);
startActivity(checkoutIntent);//startActivityForResult(checkoutIntent, 1);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (resultCode) {
case Activity.RESULT_OK:
break;
case Activity.RESULT_CANCELED:
break;
case PayPalActivity.RESULT_FAILURE:
}
super.onActivityResult(requestCode, resultCode, data);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Load EToken Certificate in ANY Browser I am working on an applicaion which does authentication based on EToken (Specifically we are using aladdin eTokens). Previously we are using just normal (File Certificates) certificates to which were added in clients browser, and its working well with Mozilla and Internet Explorer, we are using applet to load the certificates in the browser.
Now, the problem comes with the eToken it also load the certificates when we insert the device into the machine but I am not able to load the particular certificate in Mozilla Firefox the same applet code is working fine with IE. In firefox I am getting error something like java.security.InvalidKeyException: Unsupported key type: null that says that the private/public key is null, Mozilla is not able to access the keys of the eToken Certificate.
If you got any clue please help me out.
A: It seems the issue is more related with pkcs11.cfg
Check configuration file
${java.home}/lib/security/pkcs11.cfg
It should help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it possible to open a download ebook file via iBook? I got a question, which is, what if I can download a ebook file, eg .epub or PDF, then I list this file on a tableview, now I select one of the books.
Can I open via iBook?
Or I need to implement a reader to open the file?
Also got another question , I download a pdf file in my folder
The path I log it out , looks right
Here is the code:
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *ePubSubFolder = [docPath stringByAppendingPathComponent:@"Books"];
NSString *pdfPath = [ePubSubFolder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",self.pdfFileName]];
CFURLRef pdfURL = CFURLCreateWithFileSystemPath (NULL,(CFStringRef)pdfPath, kCFURLPOSIXPathStyle, FALSE);
NSLog(@"PDF URL: %@", pdfURL);
pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
CFRelease(pdfURL);
The log result is
../iPhone%20Simulator/4.3.2/Applications/06BA5929-3531-4AC3-B524-6CC74DC7E2C9/Documents/Books/Repeat%20After%20Me%20User's%20Guide.pdf
Do I did something wrong ?I won't show any thing on my view.
Many thanks for all reply or answer :-)
A: in IOS when you open a pdf using any application you get an option on the top right corner click on it and you can see options like open in ibooks etc.. I have tried this with many apps.
this is what I do to use some pdf on my ios devices.. load the file into a dropbox folder on the comp open it in the device in dropbox and then move it over to ibooks..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ">" character when import post from blogger to wordpress When I import the posts from my blogger account, I get all of posts have ">" character at first.
So example my correct post :
Lorem Ipsum Dolor
This is the post content. Lorem Ipsum Dolor Sit Amet
But, at import result it gets like this :
>Lorem Ipsum Dolor
>
This is the post content. Lorem Ipsum Dolor Sit Amet
I've try with all of my blogs in my blogger account.
I use WP 3.2.1
A: This was mentioned on the Wordpress.org forums: http://wordpress.org/support/topic/extra-character-on-blogger-import
With a link to this site: http://core.trac.wordpress.org/ticket/13458
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP mysql : possible to check if a link is open? Imagine the simple snippet below:
<?
mysql_close();
?>
This will obviously output the following warning (may look different depending on what version of php_mysql(i) you are using):
mysql_close(): no MySQL-Link resource supplied in .....
As there is no link open.
Is there a way in php to test if a mysql link is already established or not?
Thanks!
Note, have been getting a few comments regarding the use of mysql_close(). I just used that as an example. Furthermore, there are (many) situations when the use of mysql_close() is appropriate.
A: If you keep track of the resource identifier, you can use if ($link) which will get destroyed if you call mysql_close and then it will no longer evaluate true.
A: well i'm not sure but see the answer here
Is closing the mysql connection important?
From the documentation:
Note: The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mysql_close().
A: If you need reconnect to mysql, look at this function:
http://www.php.net/manual/ru/function.mysql-ping.php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Copying an instance of a PHP class while preserving the data in a base class? I have the following three classes:
class a
{ public $test; }
class b extends a { }
class c extends a
{
function return_instance_of_b() { }
}
As you can see, both classes b and c derive from a. In the return_instance_of_b() function in c, I want to return an instance of the class b. Basically return new b(); with one additional restriction:
I need the data from the base class (a) to be copied into the instance of b that is returned. How would I go about doing that? Perhaps some variant of the clone keyword?
A: You can use the get_class_vars function to retrieve the names of the variables you want to copy, and just loop to copy them.
The variables that are defined are protected so they are visible to get_class_vars in its scope (since c extends a), but not directly accessible outside the class. You can change them to public, but private will hide those variables from get_class_vars.
<?php
class a
{
protected $var1;
protected $var2;
}
class b extends a
{
}
class c extends a
{
function __construct()
{
$this->var1 = "Test";
$this->var2 = "Data";
}
function return_instance_of_b()
{
$b = new b();
// Note: get_class_vars is scope-dependant - It will not return variables not visible in the current scope
foreach( get_class_vars( 'a') as $name => $value) {
$b->$name = $this->$name;
}
return $b;
}
}
$c = new c();
$b = $c->return_instance_of_b();
var_dump( $b); // $b->var1 = "Test", $b->var2 = "Data
A: I believe you can achieve this with some reflection. Not very pretty code, I'm sure there is a much more succinct method to achieve this but here you go.
class a
{
public $foo;
public $bar;
function set($key, $value) {
$this->$key = $value;
}
function get($key) {
return $this->$key;
}
}
class b extends a
{
function hello() {
printf('%s | %s', $this->foo, $this->bar);
}
}
class c extends a
{
public $ignored;
function return_instance_of_b() {
$b = new b();
$reflection = new ReflectionClass($this);
$parent = $reflection->getParentClass();
foreach($parent->getProperties() as $property) {
$key = $property->getName();
$value = $property->getValue($this);
$b->$key = $value;
}
return $b;
}
}
$c = new c();
$c->set('foo', 'bar');
$c->set('bar', 'bar2');
$c->set('ignored', 'should be!');
$b = $c->return_instance_of_b();
$b->hello();
// outputs bar | bar2
Additionally you could use nickb's answer but instead of hard coding the class you could use get_parent_class
function return_instance_of_b()
{
$b = new b();
foreach(get_class_vars(get_parent_class(__CLASS__)) as $name => $value) {
$b->$name = $this->$name;
}
return $b;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: awk command to check whether the SSH connection to peerIP is success The command
ssh -q -o "BatchMode=yes" user@host "echo 2>&1" && echo "OK" || echo "NOK"
will help in checking whether the SSH connection to peer IP is a success or not.
But I am having only Peer IP so
ssh -q -o "BatchMode=yes" peerIP 2>&1" && echo "OK" || echo "NOK"
doesnt work.
Anyone knows how can i solve it? A One-liner command is required and it should work on AIX, HP, Linux... any help or suggestion is very much appreciated.
A: Why do you mention awk ?
Whatever, here a solution that works for me:
ssh USER@HOST 'env |grep SSH_CLIENT && echo "OK" || echo "NOK"'
When SSH is connected to the host, some environment variable will be set.
Also, when your connection to a remote host without using a User in the SSH URL, your current should be set by default. You can change that behavior in your */etc/ssh/ssh_config* .
Maybe that will fix it.
Good luck
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7509957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.