text stringlengths 8 267k | meta dict |
|---|---|
Q: jQuery Form Plugin & jQuery DatePicker Not Working Together I'm trying to use jQuery's Form Plugin. I'm using the JSON example here.
For some reason the datepickers are not showing on the page, when I use the jQuery Form Plugin. In my jquery file I've got:
jQuery.noConflict();
jQuery(document).ready(function($) {
$('#csf_map_form').ajaxForm(function() {
dataType: 'json',
success: process_json
});
function process_json(data) {
alert(data.csf_map_offense_group1);
}
$('#csf_map_start_date').datepicker({
dateFormat : 'mm/dd/yy',
yearRange : '2011:2011',
changeMonth: true,
changeYear: true,
defaultDate : new Date(2011, 8-1,1),
minDate : new Date(2011, 1-1,1),
maxDate : new Date(2011, 8-1, 25)
});
$('#csf_map_end_date').datepicker({
dateFormat : 'mm/dd/yy',
yearRange : '2011:2011',
changeMonth: true,
changeYear: true,
defaultDate : new Date(2011, 8-1, 25),
minDate : new Date(2011, 1-1,1),
maxDate : new Date(2011, 8-1, 25)
});
});
In my php file, the form looks like:
//start form
$output .= '<form id="csf_map_form" action="path-to-file/csf_map_form_handler.php" method="post" >';
//1st datepicker
$output .= '<div>';
$output .= '<label for="csf_map_start_date">Start Date:</label>';
$output .= '<div id="csf_map_start_date" style="font-size: 10px;"></div>';
$output .= '</div>';
//2nd datepicker
$output .= '<div>';
$output .= '<label for="csf_map_end_date">End Date:</label>';
$output .= '<div id="csf_map_end_date" style="font-size: 10px;"></div>';
$output .= '</div>';
//radio button group div
$output .= '<div style="float: left; width: 150px; margin: auto; padding-left: 20px; ">';
$output .= '<label for="csf_map_group1">Select Offense:</label><br />';
$output .= '<input type="radio" name="csf_map_group1" checked="checked" value="TINY">Tiny</input><br />';
$output .= '<input type="radio" name="csf_map_group1" value="MEDIUM"/>Medium</input><br />';
$output .= '<input type="radio" name="csf_map_group1" value="LARGE">Large</input><br />';
$output .= '</div>'; //end radiobuttons
$output .='<input type="submit" value="Submit" />';
$output .= '</form>';
For some reason the ajaxForm is conflicting with the datepicker. If I comment out the function starting $('csf_map_form').ajaxForm and the process_json function, then the datepickers in the form work fine. If I don't comment them out then the datepickers don't appear. But, the alert fires when submit is clicked. It alerts what was selected in the radiobutton.
Any ideas as to what is going on? How do I get them to play nice? What error am I making?
Thank you.
A: Hurray, I figured it out.
1) I changed the inline datepickers to the default-- replace the divs on the datepickers with .
2) I was missing the '#' in the $('#csf_map_form').
3) In the csf_map_form_handler.php, I was only returning only one part of the form's info. When I changed it, so that I returned the start and end dates and the radiobutton's selection, it worked.
Thank you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How come I get ClassNotFoundException when backupAgent tries to start I use the BackupAgentHelper to backup the SharedPreferences in my Android app. I have tested it in the emulator (Android 1.6 and 2.2) and on my own phone (Android 2.3.3) and it all works well. However, today I got a crash report in the Developer Console looking like this:
java.lang.RuntimeException: Unable to create BackupAgent com.xxx.yyy.MyBackupAgent: java.lang.ClassNotFoundException: com.xxx.yyy.MyBackupAgent in loader dalvik.system.PathClassLoader[/mnt/asec/com.xxx.yyy-2/pkg.apk]
at android.app.ActivityThread.handleCreateBackupAgent(ActivityThread.java:2114)
at android.app.ActivityThread.access$3200(ActivityThread.java:132)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1138)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:143)
at android.app.ActivityThread.main(ActivityThread.java:4196)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: com.xxx.yyy.MyBackupAgent in loader dalvik.system.PathClassLoader[/mnt/asec/com.xxx.yyy-2/pkg.apk]
at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at android.app.ActivityThread.handleCreateBackupAgent(ActivityThread.java:2064)
... 10 more
The backupAgent is declared in the application tag in the Manifest as:
android:backupAgent="com.xxx.yyy.MyBackupAgent"
Apparantly, the class MyBackupAgent is present since I can build the .apk and it runs just fine on several devices. So how can it be that it does not find the class here? One thing I notice in the message above is that the app seems to be installed in a path which have my package name AND an appended "-2" at the end. Can this cause the classloader to not see the class in my package since I specify the full package name and class in the android:backupAgent, or is that part irrelevant? Can anybody understand what the reason can be that the class cannot be found?
Worth to mention is that my app can be installed on SD card.
Excuse me for replacing my real package name with com.xxx.yyy in the message above.
A: To me it seems like there's a duplicate package being installed on the device. If I were you, I'd test:
*
*Has the package name been inadvertently been changed.
*Have you tried to clean the project, uninstall the app from your test device, re-build and re-installed it?
I know these questions may seem like Captain Obvious to you but I can't tell you how many times these two things have saved me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the best way to push a user to another page? I am using jQuery 1.6.2.
I have a function in a page that needs to direct the user to another page within the site and pass some variables along with it.
The function will post some data, then retrieve some data and then make a decision on where to take the user next.
Is this the best way to move someone to a specific page?
Is this the best way to code this piece?
QueryString = "?ArtistID=" + ArtistID;
window.location = 'MyNewPage.cfm' + QueryString
What other options are there?
A: You should be modifying href (and i would inline the pointless global variable )
window.location.href = 'MyNewPage.cfm?ArtistID=" + ArtistID;
A: This is a generally valid and accepted way to change location.
A few other ways could also work:
location.href = str;
location.assign(str);
location.replace(str); //Doesn't create new entry in the back button history
A: Use the following property
document.location.href = theUrl;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ajax Submit problem I have this code that works ok when search button is pressed, but if one hits the enter button, it does not return any value from the database.
function showDetails(str){
if (str==""){
document.getElementById("searchDiv").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("searchDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_details.php?q="+str,true);
xmlhttp.send();
}
Here's how I'm using it in a separate page.
searchField is a text input field in my form.
<button type="button" name="search" onclick="showDetails(searchField.value)">Search</button>
Like I said, it returns data from the server only when the search button is pressed but not when you hit the enter button on the computer keyboard. Is there any way I can make it respond to both?
A: That's because you haven't bound any event to the pressing of a key. Your event is very clearly labeled onclick. So it responds to a click. Bind it to a keypress, check if that keypress is the enter key, and if so trigger the ajax request.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cannot run C program compiled with MinGW Dev-C++ on 64bit Vista A few days ago I started programming with C after programming with C++, however, my Windows Vista 64bit machine was unable to create a C project. I recompiled the code with the MinGW Dev-C++ compiler without issue.
However, when I ran the code I received the following error:
Unsupported 16-Bit Application
The program or feature "\??\C:\Dev-Cpp\gcc.exe" cannot start or run due to incompatibity with 64-bit versions of Windows. Please contact the software vendor to ask if a 64-bit Windows compatible version is available.
Is this a problem with compiling C code using a C++ compiler?
A: The error you're seeing is from using an ancient (as in 16-bit Windows 3.1 era) software that Windows 64-bit does not provide backwards-compatibility for. This has nothing to do with C or C++, just a really old compiler.
You can either install windows 7 with XP-mode, which provides a virtual 32-bit XP machine running nearly seamlessly under Windows 7, or some other 32-bit virtualization solution or download a newer version of gcc.exe or some other compiler that's less than 20 years old:
See cygwin, MingGW, or Visual Studio Express.
A: I got the same error message when accidentally adding the -c switch which tells the compiler to not link the executable. Removing the switch made it work again.
> gcc --help
...
-c Compile and assemble, but do not link
A: It is some kind of problem with Mingw. The problem is not because you are using an old compiler. It happened to me with the last version of Mingw compilers.
I found a workaround that may help some people. This problem manifests when building my project with a Makefile. If I build it manually by the command line it works fine, the resulting .exe executes with no problems.
By compiling manually I mean for example for c++:
c:\mydir> g++ source1.cpp source2.cpp -o myprog.exe
My application was very small, just a few sources I needed to test some changes. If you have a more complex application with a Makefile this workaround probably won't help you.
A: I had a similar problem and it was msiemens' answer that give me the hint to solve it. It's not related to the MinGW version. It was just that my .exe file was not actually an executable.
I was trying to compile and build with the command:
> g++ -c cpptest.cpp -o cpptest.exe
But with -c, g++ just compiles without linking. The resulting cpptest.exe is just the cpptest.o file (binary object file, but not executable) with a different name.
To compile and link I then used (as indicated by Alejandro):
> g++ cpptest.cpp -o cpptest.exe
Or in two steps:
> g++ -c cpptest.cpp -o cpptest.o
> g++ cpptest.o -o cpptest.exe
These create the actual executable.
A: I had the same error while using Notepad++, I found the mistake I made. I was trying to create an executable file from a header file.
The file needs to be saved as a file.cpp or file.c instead of file.hpp or file.h
I was also switching languages, however from C to C++
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: SystemEvent.TimeChange showing same time even timezone changes I have wrote this simple console app to test when we change the timezone manually on windows 7 using set date time window whether timechange event is triggered or not? The answer is YES it triggered but i am printing current time which is not showing properly..
static void Main(string[] args)
{
SystemEvents.TimeChanged += new EventHandler(SystemEvents_TimeChanged);
Console.Read();
}
static void SystemEvents_TimeChanged(object sender, EventArgs e)
{
Console.WriteLine(DateTime.Now);
}
Once you run console app and then try to change the timezone it always reflects one time change but then it somehow stuck to that time even if you change the timezone to different timezone or same.
Am I missing something?
to verify whether system time has changed or not i have opened command prompt and use date and 'time' command to print the current time which shows perfect according to timezone.
A: I believe the system time zone is being cached. You can clear this cache though:
TimeZoneInfo.ClearCachedData();
Put that just before your DateTime.Now call, and it looks like it works fine. (Works on my machine, anyway :)
EDIT: As noted in comments, it appears that in some cases you also need to call CultureInfo.CurrentCulture.ClearCachedData(). I didn't, but I dare say it doesn't hurt to do so :)
A: Stupid question, but are you changing the time, or just the time zone? 5:00 is 5:00, the fact that you changed the timezone (and by extension 'moved' the computer an hour or two ahead or behind) won't change the fact that the system clock is set to 5:00.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: What's fastest way to re-test iPhone core data migration to a new version? What's fastest way to re-test iPhone core data migration to a new version?
That is, how would one set up an easy/quick way to:
*
*set up older version of app on simulator
*run the new version of the app from Xcode which will as part of running it on the simulator effectively run the migration
BACKGROUND- haven't had to do a migration yet. It's not to me in Xcode how to do the first bullet in particular. Would one use a previous image/snapshot as part of the approach?
A: What I always did is:
*
*navigate to your applications folder /Users/username/Library/Application Support/iPhone Simulator/4.3.2/ notice the iOS version number, its the one you're using in the simulator
*there should be one or more folders with hash values, found the one you're working with
*in the documents folder should be your .sqlite database file (as long as you haven't changed the directory in code)
*backup that one (for example version 1)
*when you want to test the migration, simply replace this db file with your backup
(the hash may change when you delete and rebuild your app)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: integrate jquery validation engine with mvc3 I pretty new with MVC3 but i'm already learning how handle custom validation, and client-server. But what happens if instead of using jquery-validate for the validations on client side I want to use another plugin called jquery-validation engine. How to start?
A: Well you start by turning off unobtrusive validation:
<appSettings>
...
<add key="ClientValidationEnabled" value="false"/>
</appSettings>
and removing all references to jquery.validate.js and jquery.validate-unobtrusive.js scripts from your page. Then you read the documentation of the plugin you are willing to use, try out some of the demos, download the plugin, import required scripts to your page and you start attaching to your form elements. Don't expect miracles. There is nothing that will replicate your server side validation rules defined by data annotations on the client unless you write the code for yourself.
If you keep the ClientValidationEnabled parameter to true in your web.config the Html helpers will continue to emit HTML-5 data-* attributes that you could use to dynamically define your client validation rules based on the server validation rules (the same way jquery.validate-unobtrusive.js does it). So you could write your own jquery.validation-engine-unobtrusive.js file.
A: If you want to use jquery-validation engine take a look at Pieter's blog he's implemented a HTML Helper Extension method to use the data annotations in mvc with the jquery-validation engine.
A: get your js/css files all downloaded and added. what we have is a file called jquery.validationEngine-en.js which contains the rules for validation. for example
(function($) {
$.fn.validationEngineLanguage = function() {};
$.validationEngineLanguage = {
debugMode: false,
newLang: function() {
$.validationEngineLanguage.allRules = {
"required":{
"regex":"none",
"alertText":"This field is required.",
"alertTextCheckboxMultiple":"Please select an option.",
"alertTextCheckboxe":"This checkbox is required."} };
},
confirmInput: function(caller) {
var confirmBox = $(caller).find('input.confirm_box');
if (confirmBox.is(':checked')) {
return false;
} else {
return true;
}
}
};
})(jQuery);
$(document).ready(function() {
$.validationEngineLanguage.newLang();
});
For required, it shows the text to pop up in the tooltip when the validation fails for a required field. the function below is a custom validation function that will check to make sure the confirm box is checked before the submit can go through.
you use these by adding to the element a class like so:
<input type="checkbox" class="validate[required,custom[confirmInput]]" />
Or something like that
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the -mso- prefix for in CSS? I understand what other browser specific code names such as -moz- and -webkit- are used, the former for mozilla and the later for chrome and safari, but what is -mso- exactly? It stands for Microsoft Office, but a web page is never brought up in that program, is it?
A: Mso- attributes are used for coding HTML Emails. Since Outlook 2007, Microsoft decided to use the Word rendering engine in their email client. This creates a lot of quirks in how HTML Email shows up in Outlook, thus the need to use mso- attributes in HTML.
A: Your example code:
<style> /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} </style>
Looks like what would happen if someone copied and pasted text from a Microsoft Word Document into a WYSIWYG editor in a content management system.
MS Word puts in a ton of nasty code that is not needed. It's better to tell your content authors to paste in plain text instead of from MS Word.
A: The mso prefix in CSS is used to denote a set of style applies to the Microsoft outlook renderer.
example the below code can be used to preserve the same font size for superscript in both Gmail and outlook
style="font-size: smaller; mso-text-raise: 60%;"
A: To give further info about MSO (Microsoft Office programs like MS Word)...
As a new webmaster (12 yrs ago, now) who did not know HTML, I took over a website. And I added 6 more over a few years. Took me several years to learn what the WYSIWYG editor (old Frontpage 2000) did with code. After learning in-line styles, I started learning beginner CSS. But it's been slow; I'm finally working with an External Style Sheet.
Then, several years ago, I decided to truly clean up my code--I started with the 6 webs because I knew those the best. Now, I am working on the 7th and hardest site, the one I inherited. It has code from Access, Word, Spreadsheets, Frontpage Tables, etc.
A variety of MSO tags are throughout the site. I look up every piece so I know what it did on my site. Typically, I get rid of the code even if removing it messes up the page.
On your example:
<style> /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} </style>
This is a style for a 'normal' Table. It gives row; column size; padding & margins for cells; and then styles for paragraphs. The Language is redundant since that should be in your META section. Table info and FONT should be in your External CSS.
Once you check your META tag, and Ext. CSS, delete the entire style. NOTE: However, this means your table might look weird until you redo the code. Check your CSS for your Table styles and apply one.
It's very unnerving to tear apart a webpage or website. Look up the item on Google... then, when you know what that tag does, be brave and delete the MSO tag.
Can you delete just part? Usually, yes.
Can you leave part? If you don't know what it does, yes you can keep a piece of code while you research what it means. Just use Search to refind the code piece.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Objective-C: help me convert a timestamp to a formatted date/time I'm really struggling to convert this timestamp to a nice formatted date string.
Here's the timestamp: "1316625985"
And here's the function I've made:
-(NSString*)timestamp2date:(NSString*)timestamp{
NSString * timeStampString =timestamp;
//[timeStampString stringByAppendingString:@"000"]; //convert to ms
NSTimeInterval _interval=[timeStampString doubleValue];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
[_formatter setDateFormat:@"dd/MM/yy"];
return [_formatter stringFromDate:date];
}
Trouble is, it keeps returning dates in 1972! (31/7/72) This is wrong, since it's a September 2011 date...
Can anyone suggest any solution?
Many thanks in advance,
A: Just divide your [timeStampString doubleValue] by a thousand like:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timeStampString doubleValue]/1000.0];
NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
[_formatter setDateFormat:@"dd/MM/yy"];
return [_formatter stringFromDate:date];
or try [timeStampString longLongValue]/1000.0 instead
Good Luck!
A: Did you check that the string (timestampString) and the double value (_interval) are the same, and that the doubleValue does really takes all the characters of your string into account?
Maybe the interpretation of the string into double crops the value?
Are you also sure that the timestamp you are interpretting is really a UNIX timestamp, meaning it counts the number of seconds elapsed since 01/01/1970 (and not days since 01/01/1970?… or not seconds but since another date?)
(Maybe give an example of the value of the timestamp you are trying to interpret)
A: You can pass [timeStampString doubleValue] directly into dateWithTimeIntervalSince1970: instead of converting it into an NSTimeInterval.
Also, try adding some NSLog statements to see what your values are at various points, that should help track down where the difference is.
Hope this helps!
A: Isn't epoch seconds since 1/1/1970? are you sure that you didn't leave the millisecond line in?
When I ran you're logic (without your line append 000 for ms), it worked. Here's what I did:
NSString * timeStampString = @"1316641549";
NSTimeInterval _interval=[timeStampString doubleValue];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
NSLog(@"%@", date);
It outputted:
2011-09-21 17:46:14.384 Craplet[13218:707] 2011-09-21 21:45:49 +0000
A: While using NSInterval to get the interval, make sure the timestamp is in seconds and not milliseconds. If it is in milliseconds, just divide the NSInterval value by 1000 and then try formatting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: What machine learning algorithm should I use for Connect 4? I have an AI that is good at playing Connect 4 (using minimax). Now I want to use some machine learning algorithm to learn from this AI that I have, and I would like to do that by just letting them play against each other.
What algorithm would be good for this, and how would I train it? If someone could just name a way of doing this I can easily Google it by my self. But right now I don't know what to Google...
A: Connect Four is a solved game, meaning that there is a strategy that will always allow the player who goes first to win. You could try to do a machine learning approach, but it would pointless except as an exercise.
You can read how Victor Allis used an expert system to find the winning strategy in his master's thesis (pdf).
A: You could definitely use a neural network to do this. Since it can be hard to find the right amount of input and output nodes and all the weights, I recommend using evolutionary computation techniques (such as a genetic algorithm) to do this.
Hope this helps. Cheers!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Beautiful Soup - how to parse table's columns and insert them into two lists I am trying to parse a table with two columns and insert the text from each column into two lists.
I need some ideas how to do it.
from BeautifulSoup import BeautifulSoup
s = """<table><tr><td valign="top" width="25%"><b>Text1</b><a href="#">Link1</a>:</b></td><td>AAAA<a href="#">BBBB</a></td></tr>
<tr><td valign="top" width="25%"><b>Text2:</b></td><td>CCCC<a href="#">DDDD</a></td></tr>
<tr><td valign="top" width="25%"><b><a href="#">Link2</a>:</b></td><td><a href="#">EEEE</a> FFFF</td></tr></table>
<tr><td valign="top" width="25%"><b>Text3 <br> Text4:</b></td><td><a href="#">EEEE</a> FFFF</td></tr></table>"""
a = BeautifulSoup(s)
b = a.findAll('td', text=True)
left = []
right = []
for i in b:
print i
What I get:
Text1
Link1
:
AAAA
BBBB
What I need:
left = ["Text1", "Link1"]
right = [AAAA", "BBBB"]
A: Get the row first, and then get the cell:
left = []
right = []
for tr in a.findAll('tr'):
l, r = tr.findAll('td')
left.extend(l.findAll(text=True))
right.extend(r.findAll(text=True))
I haven't tested this, but pretty sure it should work :)
EDIT: fixed (hopefully)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQuery Selector Question -- How to find all HREF's with a target = _blank? My "JQuery Selector Foo" stinks. I need to find all HREF's with a target attr of _blank and replace them with a common window/target. Assistance is greatly appreciated!
A: try
$("a[target=_blank]").each(function () {
var href = $(this).attr("href"); // retrive href foreach a
$(this).attr("href", "something_you_want"); // replace href attribute with wich u want
// etc
});
let me know what do you want, for more help
A: $("a[target='_blank']").attr('target', 'sometarget');
Do you mean something like that?
A: If you're specifically looking for href values which have blank values then do the following
$('a[href=""]').each(function() {
$(a).attr('href', 'theNewUrl');
});
This will catch only anchor tags which have a href attribute that is empty. It won't work though for anchors lacking an href tag
<a href="">Link 1</a> <!-- Works -->
<a>Link 2</a> <!-- Won't work -->
If you need to match the latter then do the following
$('a').each(function() {
var href = $(this).attr('href') || '';
if (href === '') {
$(this).attr('href', 'theNewUrl');
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: CUDA: Is it OK to pass a pointer to struct to a device function? Inside of a kernel, is it OK to pass the address of a struct, which is declared inside the kernel, to a device function? The device function's argument is a pointer to a struct.
A: Yes, as the following program demonstrates:
#include <stdio.h>
struct my_struct
{
int x;
};
// foo receives its argument by pointer
__device__ void foo(my_struct *a)
{
a->x = 13;
}
__global__ void kernel()
{
my_struct a;
a.x = 7;
// expect 7 in the printed output
printf("a.x before foo: %d\n", a.x);
foo(&a);
// expect 13 in the printed output
printf("a.x after foo: %d\n", a.x);
}
int main()
{
kernel<<<1,1>>>();
cudaThreadSynchronize();
return 0;
}
The result:
$ nvcc -arch=sm_20 test.cu -run
a.x before foo: 7
a.x after foo: 13
A: If you have allocated memory on the device and use it only within the device, then yes you can pass it to whatever device function you want.
The only time you need to worry about anything like that is when you want to use an address from the host on the device or an address from the device on the host. In those cases, you must first use the appropriate memcopy and get a new device or host specific address.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Supporting Single Sign-On with Active Directory We have a SaaS app written on .NET and we need to offer various methods of SSO to our customers.
A while ago we standardized on OpenID, hoping that this would become a universal standard and liberate us from having to support different standards. Unfortunately, enterprises never quite got on board with OpenID and we are always asked to support Active Directory. (Our app just needs basic authentication, not fine-grained authorization to use different objects/permissions/etc.)
We're hoping to avoid a lot of extra development -- if we want to offer easy integration to the greatest number of Windows A.D. users, which should we support -- LDAP or SAML? And if SAML, 1.x or 2.x?
A: Huge difference between LDAP and SAML support for SSO. I would imagine almost every enterprise customer you have will not like you opening up a firewall port directly to their AD/LDAP store containing all their user data. More likely they will have some kind of SAML-based solution in place that provides a MUCH more secure SSO solution. Companies are also starting to push back on employees entering corporate user creds into login forms not hosted by the company (helps reduce phishing).
Since you are already a SaaS, why not use a service that gives your application SAML support so you don't have to? Check out PingConnect for SaaS Providers. [Note: I work for Ping] Nothing to install, just some minor code changes to the auth logic in your application. If you really want an on-premise SAML solution, there are 150+ SaaS Providers using our PingFederate software to provide SAML 1.0/1.1/2.0/WS-Fed protocol support to their customers.
HTH - Ian
A: You can enable SSO for a user base in Active Directory with SAML2, OpenID or with Passive STS support. It is important to have multiple protocol support, since different applications capable of supporting different protocols. For example, Google Apps, Salesforce support SAML2, while LifeRay, Drupal support OpenID..
Disclaimer : I am an architect from WSO2
The open source WSO2 Identity Server can be deployed over an active directory [just a configuration] and it will automatically give all the users in AD an OpenID.
Further the Identity Server can be used as an SAML2 IdP, OpenID provider or as a PassiveSTS IdP.
Specially when providing SSO for SharePoint users - you may need to use PassiveSTS.
You can see the cloud deployment of WSO2 Identity Server from here..
If your concern is from a service provider end, then it would be ideal to have SAML2 as well as OpenID support...
A: If you want to adress quickly and directly Active-Directory LDAP is the shortest way.
But for me LDAP and SAML are covering different scope.
In one hand, LDAP is an open protocol that allow you a direct access to an authtification server. You stay independant to the LDAP directory.
In the other hand, I think that if the users of your service are able to be authenticated in their companies SAML allow you to make a trust relationship with these companies and to avoid managing user/password. For your client that deploy Active-Directory lets have a look to Active Directory Federation Services.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Get hostname of current request in node.js Express So, I may be missing something simple here, but I can't seem to find a way to get the hostname that a request object I'm sending a response to was requested from.
Is it possible to figure out what hostname the user is currently visiting from node.js?
A: If you need a fully qualified domain name and have no HTTP request, on Linux, you could use:
var child_process = require("child_process");
child_process.exec("hostname -f", function(err, stdout, stderr) {
var hostname = stdout.trim();
});
A: First of all, before providing an answer I would like to be upfront about the fact that by trusting headers you are opening the door to security vulnerabilities such as phishing. So for redirection purposes, don't use values from headers without first validating the URL is authorized.
Then, your operating system hostname might not necessarily match the DNS one. In fact, one IP might have more than one DNS name. So for HTTP purposes there is no guarantee that the hostname assigned to your machine in your operating system configuration is useable.
The best choice I can think of is to obtain your HTTP listener public IP and resolve its name via DNS. See the dns.reverse method for more info. But then, again, note that an IP might have multiple names associated with it.
A: Here's an alternate
req.hostname
Read about it in the Express Docs.
A: You can use the os Module:
var os = require("os");
os.hostname();
See http://nodejs.org/docs/latest/api/os.html#os_os_hostname
Caveats:
*
*if you can work with the IP address --
Machines may have several Network Cards and unless you specify it node will listen on all of them, so you don't know on which NIC the request came in, before it comes in.
*Hostname is a DNS matter --
Don't forget that several DNS aliases can point to the same machine.
A: If you're talking about an HTTP request, you can find the request host in:
request.headers.host
But that relies on an incoming request.
More at http://nodejs.org/docs/v0.4.12/api/http.html#http.ServerRequest
If you're looking for machine/native information, try the process object.
A: You can simply use below code to get the host.
request.headers.host
A: I think what you want is to identify cross-origin requests, you would instead use the Origin header.
const origin = req.get('origin');
Use this you can get a request Client-Side URL
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "219"
} |
Q: PHP session cookie seems to gone when URL does not have WWW in front of it I put this on my index file:
session_set_cookie_params(31536000);
session_start();
It keeps users logged in even when the browser is closed and re-opened.
However, it only works when a WWW in front of my URL. Is there a way to make it work without the WWW in front of the URL?
A: As per the docs, use this:
session_set_cookie_params( 31536000, '/', '.example.com' );
This will allow the session cookie to be valid for every path (second argument) and every subdomain of example.com (third argument). Replace .example.com with your own of course.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Excluding Documents From UITableView Somehow on the simulator, it has gotten the data from a file that doesn't exist, yet persists in the simulator's memory. Because apps are sandboxed, it must be from an early method that I neglected to delete, but searching through my app's methods, none of them CREATE files, just view them.
My question is this: can data be excluded from a UITableView that is displaying content from the app's
\documents
folder? I only want to display files that end in .pdf.
A: Iterate through each file and look for the suffix .pdf. See NSString hasSuffix
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Preferring non-member non-friend functions to member functions This question title is taken from the title of item #23 in Effective C++ 3rd Edition by Scott Meyers. He uses the following code:
class WebBrowser {
public:
void clearCache();
void clearHistory();
void removeCookies();
//This is the function in question.
void clearEverything();
};
//Alternative non-member implementation of clearEverything() member function.
void clearBrowser(WebBrowser& wb) {
wb.clearCache();
wb.clearHistory();
wb.removeCookies();
};
While stating that the alternative non-member non-friend function below is better for encapsulation than the member function clearEverything(). I guess part of the idea is that there are less ways to access the internal member data for the WebBrowser if there are less member functions providing access.
If you were to accept this and make functions of this kind external, non-friend functions, where would you put them? The functions are still fairly tightly coupled to the class, but they will no longer be part of the class. Is it good practice to put them in the class's same CPP file, in another file in the library, or what?
I come from a C# background primarily, and I've never shed that yearning for everything to be part of a class, so this bewilders me a little (silly though that may sound).
A: Usually, you would put them in the associated namespace. This serves (somewhat) the same function as extension methods in C#.
The thing is that in C#, if you want to make some static functions, they have to be in a class, which is ridiculous because there's no OO going on at all- e.g., the Math class. In C++ you can just use the right tool for this job- a namespace.
A: So clearEverything is a convenience method that isn't strictly necessary. But It's up to you to decide if it's appropriate.
The philosophy here is that class definitions should be kept as minimal as possible and only provide one way to accomplish something. That reduces the complexity of your unit testing, the difficulty involved in swapping out the whole class for an alternate implementation, and the number of functions that could need to be overridden by sub-classes.
In general, you shouldn't have public member functions that only invoke a sequence of other public member functions. If you do, it could mean either: 1) you're public interface is too detailed/fine-grained or otherwise inappropriate and the functions being called should be made private, or 2) that function should really be external to class.
Car analogy: The horn is often used in conjunction w/ slamming on your brakes, but it would be silly to add a new pedal/button for that purpose of doing both at once. Combining Car.brake() and Car.honk() is a function performed by Driver. However, if a Car.leftHeadLampOn() and Car.rightHeadLampOn() were two separate public methods, it could be an example of excessively fine grained control and the designer should rethink giving Driver a single Car.lightsOn() switch.
In the browser example, I tend to agree with Scott Meyers that it should not be a member function. However, it could also be inappropriate to put it in the browser namespace. Perhaps it's better to make it a member of the thing controlling Web browser, e.g. part of a GUI event handler. MVC experts feel free to take over from here.
A: I do this a lot. I've always put them into the same .cpp as the other class member functions. I don't think there is any binary size overhead depending where you put them though. (unless you put it in a header :P)
A: If you want to go down this route the imlementation of clearEverything should be put in both the header (declaration) and implementation of the class - as they are tightly coupled and seems the best place to put them.
However I would be inclined to place them as a part of the class - as in the future you may have other things to clear or there may be a better or faster implementation to implement clearEverythingsuch as droppping a database an just recreate the tables
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python Interpreter: Can't assign to literal I wrote a program with this code in it:
('<') = raw_input(v1), ('>') = raw_input(v2)
and recieve the message syntax error: can't assign to literal. What am I doing wrong?
A:
What am I doing wrong?
You're attempting to assign something the user enters to an instance of a String. That doesn't work.
To grab your question in a comment on another answer and attempt to incorporate it, if you want to be able to type v1 and have it return '<', you need to do this:
v1 = '<'
It sounds like, before you go much further, you strongly need to work through some of the basic programming concepts like assignment, variables, and functions.
A: To take a stab at what you mean:
user_provided_value = raw_input("Say something:")
if user_provided_value == "v1":
print "Heavier than a duck!"
elif user_provided_value == "v2":
print "Lighter than a duck!"
else:
print "You must enter either v1 or v2"
What you are saying is (ignoring the v1 and v2 variables):
('<') #1 Set '<'
#2 [ ('<') is the same as simply saying '<' ]
= #3 to be the result of assigning
#5 to a tuple composed of
raw_input() #6 what the user types in at the prompt
, #7 (the comma operator creates a tuple)
('>') #8 And '>'
= # to be
raw_input() #4 what the user types in at the prompt
Typing those lines out in legible English, you are saying:
"Set '<' to be the result of assigning a user-defined value from raw_input() to the tuple raw_input(), '>'".
Saying, "Set some fixed value to be equal to the user-provided value" is the algebraic equivalent of saying "Set 5 to be equal to the value of the previous equation."
* Since the comma operator is one of the least binding operators, you are actually setting the tuple composed of the strings raw_input(), '>' to be equal to the string from the second raw_input call.
The statement can be broken down as follows:
Set the string '<' to be the value resulting from evaluating the statement raw_input(), '>' = raw_input()
raw_input(), '>' = raw_input() is interpreted as:
Set the tuple composed of the results of calling raw_input() and '>' to be equal to the results of calling raw_input()
A: Are you trying to get input with < and > as the prompts? If so, this is what you should be doing:
v1 = raw_input('<')
v2 = raw_input('>')
raw_input takes in the prompt as a parameter, and the output of this function call (what you type in the terminal) gets assigned into v1 and v2.
Another option in one line, since it looks like you are trying to do one line:
v1, v2 = raw_input('<'), raw_input('>')
The reason you are getting that error message is ('<') is what is called a literal. A literal is a value that is explicitly typed out in your code. Basically, not a variable. This is like saying 3 = len(mylist)... How do you assign the output of the len function to 3? You can't, because 3 is not a variable. You should only be assigning into a variable, in python (and most other languages) typically some sort of word-like set of characters, like v1 or myinput:
v1 = len(mylist)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: memory of a process in Lua How can I get the meomory of any Process in Lua?
Is it possible in Lua? Is C# it is possible but I am not sure.
In C# we can use PerformanceCounter class to get the
PerformanceCounter WorkingSetMemoryCounter = new PerformanceCounter("Process",
"Working Set", ReqProcess.ProcessName);
What is equivalent of this in Lua?
Suppose there are 5 process of IE (Internet Explorer) running . How to get a List of those process?
A: To elaborate on what others have said, Lua is a scripting language designed for embedding. That means that it runs inside another application.
Lua.exe is one such application. But it is not the only application that Lua scripts can be written to be executed on.
When within a Lua script, you have access to exactly and only what the surrounding application environment allows. If the application does not explicitly allow you to access things like "files" or "the operating system", then you don't get to access them. Period.
Lua's standard library (which an application can forbid scripts to use. Lua.exe allows it, but there are some embedded environments that do not) is very small. It doesn't offer a lot of amenities, which make Lua ideal for embedded environments: small standard libraries mean smaller executables. Which is why you see a lot more Lua in mobile applications than, say, Python. Also, the standard library is cross-platform, so it does not access platform-specific libraries.
Modules, user-written programs (either in Lua or C/C++) can be loaded into Lua.exe's environment. Such a module could give your Lua script access to things like "processes", how much memory the process is taking, and so forth. But if you do not have access to such a module, then you're not getting that info from within a Lua script.
The most you are going to be able to do is get the size of the memory that this particular Lua environment is directly allocating and using, as @lhf said: collectgarbage "count".
A: To get the memory allocated by Lua in Kbytes, use collectgarbage"count".
A: Lua does not comes with this built-in functionality. You could write a binding to a library that provides you that or you could interface with a program to do that (like reading the output of "ps -aux | grep firefox").
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Semicolons superfluous at the end of a line in shell scripts? I have a shell script which contains the following:
case $1 in
0 )
echo $1 = 0;
OUTPUT=3;;
1 )
echo $1 = 1;
OUTPUT=4;;
2 )
echo $1 = 2;
OUTPUT=4;;
esac
HID=$2;
BUNCH=16;
LR=.008;
Are semicolons completely superfluous in the snippet above? And is there any reason for some people using double semicolons?
It appears semicolons are only a separator, something you would use instead of a new line.
A: In the special case of find, ; is used to terminate commands invoked by -exec. See the answer of @kenorb to this question.
A: According to man bash:
metacharacter
A character that, when unquoted, separates words. One of the following:
| & ; ( ) < > space tab
control operator
A token that performs a control function. It is one of the following symbols:
|| & && ; ;; ( ) | |& <newline>
So, the ; can be metacharacter or control operator, while the ;; is always a control operator (in case command).
In your particular code, all ; at the end of line are not needed. The ;; is needed however.
A: Single semicolons at the end of a line are superfluous, since the newline is also a command separator. case specifically needs double semicolons at the end of the last command in each pattern block; see help case for details.
A: @Opensourcebook-Amit
newlines equivalent to single semicolon ; on terminal or in shell script.
See the below examples:
On terminal:
[root@server test]# ls;pwd;
On shell script:
[root@server test]# cat test4.sh
echo "Current UserName:"
whoami
echo -e "\nCurrent Date:";date;
[root@server test]#
But I am not agree with the comment that & is equivalent to newline or single semicolon
& is run commands in background also a command separator but not worked as semicolon or newline.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "124"
} |
Q: How to store int in Core Data with NSTableView binding NSArrayController? I'm developing a core data a application and I have a attribute of an entity that have type "integer16" (int).
I would to set it through a NSTableView, that is bind to core data through a NSArrayController.
I put a NSDateFormatter in the NSTableViewColumn to format the date's column, and it works because NSDateFormatter returns a NSDate.
But with NSNumberFormatter doesn't work, because NSNumberFormatter returns a NSNumber, not int or NSInteger (the type set in core data).
Where can I call the method [mynsnumber intValue] to set the int value in my core data every time user changes the value?
A: Because you haven't explained why you're trying to store a date as an integer, I'm going to go for the obvious answer: Use a date type to store a date in Core Data.
If it's not a date, then you really need to explain - in detail - exactly what you're trying to accomplish, rather than ask us how to force it to work the way you think it should.
Specific questions in my mind: What exactly does this attribute represent? How do you want to represent it to your user (how should it be formatted - note I'm not asking you what formatter you want to use; what is the goal, not the means you assumed would get you there)?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Custom windows control attachment issue
Let me preface with a Joe Dirt quote... "I'm new, I'm new. And I don't know what to do"
I have a custom user control comprised of 2 picture boxes (one on top of the other) and 3 labels. The top picture box has an image that repeats, and the bottom one has a static image. Think progress bar...
______________________________________________
| PB1 | PB2 |
|----------------------|---------------------|
| Label1 Label2 Label3 |
|____________________________________________|
The top bars length is a function of the users score, from 0 to 100, at 100 the background bar is no longer viable as the top bar fills up the space entirely.
I have a second control attached to my main form that will dynamically create and attach however many of these progress bars to itself as are needed. The control itself has nothing on it, its just a blank user control.
int spacer = (Height - (ProgressBar.Controls_Height * progressBarCount)) / (progressBarCount+ 1);
for (int i = 0; i < progressBarCount.Count; i++)
{
ProgressBar pb = new ProgressBar(progressBarData) { Left = 0 };
if (i == 0)
{
pb.Top = spacer;
}
else
{
pb.Top = (Controls[i - 1].Bottom + spacer);
}
Controls.Add(pb);
_progressBars.Add(pb);
}
The issue is when attaching one of the Progress Bars to the blank user control is that they do not attach to the left of the user control, and the image of only the background picture box gets cut, but the foreground picture box will draw all the way to the max.
-> ______________________________________________
-> | PB1 | PB2 | |
-> |----------------------|------------------|---|
-> | Label1 Label2 Label3 |
-> |_________________________________________|
I have played with every setting in the properties window on both user controls, with similar results. I am at a bit of a loss here and could use some suggestion.
A: The wrong base image was being used by mistake.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: select midi device in java In my program it is necessary to be able to select the midi device in java.
I have tried using another sequencer that i got from MidiSystem.getDevice().
Simply using setSequence() and starting the sequencer were without success however (i.e no sound).
I'm guessing that I somehow need to connect a Sequencer with a Synthesizer.
How can I do this properly?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: hudson and jenkins parameterized trigger plugin - running the same job multiple times with different parameters I'm trying to run the same job multiple times with different parameters via a parent job. However, only the first of the triggered jobs runs.
The parent job has the checkbox "Trigger parameterized build on other projects" checked, and there are two triggers created, each with a different parameter value for a parameter x on the downstream job. Job 1 has x=1, Job 2 has x=2. Only job 1 is run!?
What am I missing?
A: This is a bug in Hudson.
It was reported to Jenkins and fixed there, both in the core and this particular plugin several months ago.
See also the Jenkins vs Hudson discussion on StackOverflow for further reasons to upgrade to Jenkins.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java equals and hashCode methods - technical constraints I've got question about java's equals(Object o) and hashCode() methods. What are the technical constraints of implementation this both methods? Is there something that I can't do during implement this methods?
A: None. It's just two methods in Object class. You could even change an object's state within this methods and this will freak out every developer and system but it's still valid from technical point of view.
A: You can technically anything inside them you can do in any other methods.
Instead what you concern yourself with are the practical and contractual obligations of the methods.
Good rules of thumb:
*
*If you override one, override the other.
*Variables used in one should be used in the other.
A: a given object must consistently report the same hash value
two objects which equals() says are equal must report the same hash value - so no timestamps in the hashcode :).
Two unequal objects can also have the same hashcode, though it is better to make the hashcode difficult to repoduce.
A: All you need to remember, is:
*
*those constrains are very important
*all are very well documented in javadoc for Object.hashCode() and Object.equals()
Make sure you understand it every time you override any of those methods.
A:
Is there something that I can't do during implement this methods?
Well, as a rule of thumb (and as already @RHT mentioned above and @Antti Sykäri explains here) do your future self a favor and always use EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. Because, quite frankly, at least in my case I never get to remember all the nitty-gritty details that a correct implementation would require. ;-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP Facebook saving user creds? is it possible to save the user details (the Signed request that facebook sends after validation) to a database for future use?
NOTE: i DO NOT mean adding a random signed request, i merely mean the signed request that facebook sends AFTER user has successfully added your app + signed into facebook.
A: Yes. You can save it. Once it's on your server, you can do whatever you like with it.
Should you? I think not. That data is supposed to only be available to you while the user is using your app.
One thing to note: if you want to make calls to the Open Graph API on behalf of the user, any tokens you use will expire when they log out (unless you have requested the "offline access" permission).
After the user has authorized your app, you should continue to get a "user" object in your signed_request that includes their FB user id.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Assigning RootViewController to UIViewController gives warning - why? I want to access the RootViewController of my App in one of its classes in order to present a modal view controller. I do this by getting the ApplicationDelegate and asking it for the RootViewController and store it in a UIViewController
AppDelegate *appDelegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
UIViewController* presentingViewController = appDelegate.viewController;
In my opinion this should work without a warning as RootViewController inherits from UIViewController. However I receive this warning:
Incompatible pointer types initializing 'UIViewController *__strong' with an expression of type 'RootViewController *'
Can someone explain to me why I see this warning?
If it helps - this is the AppDelegate where I define the RootViewController:
@interface AppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
RootViewController *viewController;
}
@property (strong) RootViewController *viewController;
I defined my RootViewController like this:
@interface RootViewController : UIViewController {
}
A: You can assign an object to a variable declared as its superclass. That is no problem and is very useful when you only want to use superclass methods over a set of your own subclasses, especially common with view controllers in a navigation stack when the specific type of next view controller is unknown.
Also think about it. Methods like
[self presentModalViewController:customController animated:YES];
wouldn't work without being able to do this. This method is declared as taking a UIViewController * but you pass in a custom UIViewController subclass with no complaints. Finally
[rootViewController isKindOfClass:[UIViewController class]];
will return YES. QED.
Have you forward declared your class RootViewController in the header for your app delegate?
i.e.
@class RootViewController;
@interface AppDelegate : NSObject <UIApplicationDelegate> {
....
Did you spell it correctly? This is a common area to mistype as xCode doesn't autocomplete forward declarations. It will then autocomplete your typo in the rest of the header file.
Did you remember to import the header file for your RootViewController into the .m file for the AppDelegate? You will still need to do that so the compiler knows about the inheretance.
Your code looks correct at the moment but we don't have all of it.
A: The problem is that RootViewController is not the same class as UIViewController.
In the AppDelegate, you declare viewController to be of type RootViewController. Then, in these lines:
AppDelegate *appDelegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
UIViewController* presentingViewController = appDelegate.viewController;
You are creating presentingViewController, which is of type UIViewController, and setting it to an instance of RootViewController. This is the source of the error.
Fix this by using a consistent type.
Read What's the difference between the RootViewController, AppDelegate and the View Controller classes that I may create? for a nice explanation of the difference between these two types.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Posting to controller with jQuery After reading some information I thought this should work. The JS function is called and jQuery animation is spinning, but the action is not posted to. As well I will want the startDate and endDate to be provided from text inputs but for now even hard-coded is not working. Thanks everyone!
Controller:
public class NewsController : Controller
{
[HttpPost]
public ActionResult Search(string lang, string pageNumber, string startDate, string endDate, string search)
{
}
}
View:
@using (Html.BeginForm())
{
<a href="#" id="go_button">...</a>
}
<script type="text/javascript">
$('#go_button').click(function () {
$.post("/News/Search", { startDate: 'start', endDate: 'end'});
});
A: Make sure that the script is either located after the anchor in the DOM or wrap in a document.ready:
$(function() {
$('#go_button').click(function () {
var url = '@Url.Action("Search", "News")';
$.post(url, { startDate: 'start', endDate: 'end' }, function() {
alert('success');
});
return false;
});
});
This should work, at least it should invoke your action. What this action does, whether it throws an exception or something is another matter, but at least you should get into it and have the startDate and endDate parameters properly assigned:
public class NewsController : Controller
{
[HttpPost]
public ActionResult Search(string lang, string pageNumber, string startDate, string endDate, string search)
{
return Json(new { success = true });
}
}
A: $.post will only post the request to the server - it won't automatically update your page with your view.
You need to include a success function which you then use to insert the View into the DOM.
e.g.
try something like this in the jquery
$(function() {
$('#go_button').click(function () {
var url = '@Url.Action("Search", "News")';
$.post(url, { startDate: 'start', endDate: 'end' }, function() {
$('#result').html(data);
});
return false;
});
});
This will post to your action and put the returned view inside an element with the ID 'result'.
You should have your action return a PartialView, if you don't the Layout to be included.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Qt framework OK for this Windows and Mac GUI? Some background. I'm writing a program that needs to monitor the default audio buffer and write to a virtual COM port. Both those operations are platform specific, and are driven via an GUI.
My question is, would the Qt framework suffice? I'm heard great things about it on my never ending google quest, but I am not sure how well it handles platform-specific code. In theory, I would just need to abstract two platform-specific classes. The rest of the program would be cross-platform compliant, written in C++.
A: Yes Qt is definitely useful for the GUI. However depending on if Qt offers the ability to access the audio buffer and virtual COM port you may have to couple that with the use of Boost ASIO. Boost is also cross-platform like Qt.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java DOM Parser XML I need to extract attribute values from <Item Name="CanonicalSmiles"> from following XML file (part is shown) ?
I tried getElementsByTagName("Item").item(12).getTextContent()); But for different <DocSum>s item(i) is different (ie not 12 always!)
How do I do this??
<?xml version="1.0"?>
<!DOCTYPE eSummaryResult PUBLIC "-//NLM//DTD eSummaryResult, 29 October 2004//EN" "http://www.ncbi.nlm.nih.gov/entrez/query/DTD/eSummary_041029.dtd">
<eSummaryResult>
<DocSum>
<Id>53359352</Id>
<Item Name="CID" Type="Integer">53359352</Item>
<Item Name="SourceNameList" Type="List"></Item>
<Item Name="SourceIDList" Type="List"></Item>
<Item Name="SourceCategoryList" Type="List">
<Item Name="string" Type="String">Journal Publishers</Item>
</Item>
<Item Name="CreateDate" Type="Date">2011/09/19 00:00</Item>
<Item Name="SynonymList" Type="List"></Item>
<Item Name="MeSHHeadingList" Type="List"></Item>
<Item Name="MeSHTermList" Type="List"></Item>
<Item Name="PharmActionList" Type="List"></Item>
<Item Name="CommentList" Type="List"></Item>
<Item Name="IUPACName" Type="String">2-hydroxy-6-[2-(4-hydroxyphenyl)-2-oxoethyl]benzoic acid</Item>
<Item Name="CanonicalSmiles" Type="String">C1=CC(=C(C(=C1)O)C(=O)O)CC(=O)C2=CC=C(C=C2)O</Item>
<Item Name="RotatableBondCount" Type="Integer">4</Item>
<Item Name="MolecularFormula" Type="String">C15H12O5</Item>
<Item Name="MolecularWeight" Type="String">272.252780</Item>
<Item Name="TotalFormalCharge" Type="Integer">0</Item>
<Item Name="XLogP" Type="String"></Item>
<Item Name="HydrogenBondDonorCount" Type="Integer">3</Item>
<Item Name="HydrogenBondAcceptorCount" Type="Integer">5</Item>
<Item Name="Complexity" Type="String">359.000000</Item>
<Item Name="HeavyAtomCount" Type="Integer">20</Item>
<Item Name="AtomChiralCount" Type="Integer">0</Item>
<Item Name="AtomChiralDefCount" Type="Integer">0</Item>
<Item Name="AtomChiralUndefCount" Type="Integer">0</Item>
<Item Name="BondChiralCount" Type="Integer">0</Item>
<Item Name="BondChiralDefCount" Type="Integer">0</Item>
<Item Name="BondChiralUndefCount" Type="Integer">0</Item>
<Item Name="IsotopeAtomCount" Type="Integer">0</Item>
<Item Name="CovalentUnitCount" Type="Integer">1</Item>
<Item Name="TautomerCount" Type="Integer">67</Item>
<Item Name="SubstanceIDList" Type="List"></Item>
<Item Name="TPSA" Type="String">94.8</Item>
<Item Name="AssaySourceNameList" Type="List"></Item>
<Item Name="MinAC" Type="String"></Item>
<Item Name="MaxAC" Type="String"></Item>
<Item Name="MinTC" Type="String"></Item>
<Item Name="MaxTC" Type="String"></Item>
<Item Name="ActiveAidCount" Type="Integer">0</Item>
<Item Name="InactiveAidCount" Type="Integer">0</Item>
<Item Name="TotalAidCount" Type="Integer">0</Item>
<Item Name="InChIKey" Type="String">YIGHIFUVVSYMFG-UHFFFAOYSA-N</Item>
<Item Name="InChI" Type="String">InChI=1S/C15H12O5/c16-11-6-4-9(5-7-11)13(18)8-10-2-1-3-12(17)14(10)15(19)20/h1-7,16-17H,8H2,(H,19,20)</Item>
</DocSum>
<DocSum>
<Id>53346823</Id>
<Item Name="CID" Type="Integer">53346823</Item>
<Item Name="SourceNameList" Type="List"></Item>
<Item Name="SourceIDList" Type="List"></Item>
<Item Name="SourceCategoryList" Type="List">
<Item Name="string" Type="String">Biological Properties</Item>
</Item>
<Item Name="CreateDate" Type="Date">2011/09/01 00:00</Item>
<Item Name="SynonymList" Type="List">
<Item Name="string" Type="String">HMS2478O14</Item>
</Item>
<Item Name="MeSHHeadingList" Type="List"></Item>
<Item Name="MeSHTermList" Type="List"></Item>
<Item Name="PharmActionList" Type="List"></Item>
<Item Name="CommentList" Type="List">
<Item Name="string" Type="String">Asinex Ltd.:BAS 02768155</Item>
</Item>
<Item Name="IUPACName" Type="String">ethyl 3-amino-3-(1,3-benzodioxol-5-yl)propanoate chloride</Item>
<Item Name="CanonicalSmiles" Type="String">CCOC(=O)CC(C1=CC2=C(C=C1)OCO2)N.[Cl-]</Item>
<Item Name="RotatableBondCount" Type="Integer">5</Item>
<Item Name="MolecularFormula" Type="String">C12H15ClNO4-</Item>
<Item Name="MolecularWeight" Type="String">272.704800</Item>
<Item Name="TotalFormalCharge" Type="Integer">-1</Item>
<Item Name="XLogP" Type="String"></Item>
<Item Name="HydrogenBondDonorCount" Type="Integer">1</Item>
<Item Name="HydrogenBondAcceptorCount" Type="Integer">6</Item>
<Item Name="Complexity" Type="String">271.000000</Item>
<Item Name="HeavyAtomCount" Type="Integer">18</Item>
<Item Name="AtomChiralCount" Type="Integer">1</Item>
<Item Name="AtomChiralDefCount" Type="Integer">0</Item>
<Item Name="AtomChiralUndefCount" Type="Integer">1</Item>
<Item Name="BondChiralCount" Type="Integer">0</Item>
<Item Name="BondChiralDefCount" Type="Integer">0</Item>
<Item Name="BondChiralUndefCount" Type="Integer">0</Item>
<Item Name="IsotopeAtomCount" Type="Integer">0</Item>
<Item Name="CovalentUnitCount" Type="Integer">2</Item>
<Item Name="TautomerCount" Type="Integer">1</Item>
<Item Name="SubstanceIDList" Type="List"></Item>
<Item Name="TPSA" Type="String">70.8</Item>
<Item Name="AssaySourceNameList" Type="List"></Item>
<Item Name="MinAC" Type="String"></Item>
<Item Name="MaxAC" Type="String"></Item>
<Item Name="MinTC" Type="String"></Item>
<Item Name="MaxTC" Type="String"></Item>
<Item Name="ActiveAidCount" Type="Integer">0</Item>
<Item Name="InactiveAidCount" Type="Integer">0</Item>
<Item Name="TotalAidCount" Type="Integer">0</Item>
<Item Name="InChIKey" Type="String">NKQHQIJWIYNEIX-UHFFFAOYSA-M</Item>
<Item Name="InChI" Type="String">InChI=1S/C12H15NO4.ClH/c1-2-15-12(14)6-9(13)8-3-4-10-11(5-8)17-7-16-10;/h3-5,9H,2,6-7,13H2,1H3;1H/p-1</Item>
</DocSum>
A: For what you're doing, XPath is likely easier than DOM. See this Java XPath tutorial.
A: XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
XPathExpression xe = xp.compile("//DocSum/Item[@Name='CanonicalSmiles']/text()");
NodeList nodes = (NodeList)xe.evaluate(yourdom, XPathConstants.NODESET);
A: As others have pointed out, XPath is the standard way to go. If you're using a tool like jOOX, writing XPath is even simpler:
String text = $(document).xpath("//DocSum/Item[@Name='CanonicalSmiles']").text();
With jOOX, you don't need to use XPath, however. You could also use jOOX's jQuery-like API directly, for instance using filters:
String text = $(document).find("Item")
.filter(attr("Name", "CanonicalSmiles"))
.text();
Or by using CSS-style selectors:
String text = $(document).find("Item[Name='CanonicalSmiles']").text();
A: As I see, the problem of parser each time reading XML elements in different order remained still unanswered.
XML has not any order of elements. You can't wait that the element read as num. 12 today will be num. 12 tomorrow. The only way to number your elements is go give them numbers explicitely.
<Item Name="TotalFormalCharge" Type="Integer">-1</Item>
will become:
<Item Name="TotalFormalCharge" Num=6 Type="Integer">-1</Item>
And you can get it by the attribute value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it possible to extend the User.Identity structure (ASP.Net/MVC) somehow? Is it possible to store additional data specific to the currently logged on user somehow?
A: Certainly! If you are not familiar with writing an extension, there are the VB.NET and C# guides on the subject.
You will need to extend the System.Security.Principal.IIdentity interface. As an example:
Declaration:
Imports System.Runtime.CompilerServices
Module Extensions
<Extension()>
Function GetMyCustomProperty(anIdentity As System.Security.Principal.IIdentity, myParameter As Integer) As Object
Return New Object()
End Function
End Module
Usage:
User.Identity.GetMyCustomProperty(4)
NOTES:
*
*The C# code is a fair deal different so it's worth looking at the
guides on how extensions are implemented in general. Running this
code through a VB.NET => C# converter is not enough.
*Extensions may only be methods. You may not program custom properties. This will likely mean implementing getter/setter methods if you want property-like behavior.
EDIT:
After seeing your comments, I assume you are doing this to provide a sort of crude functionality similar to a user profile. Consider using a profile provider in concert with any membership you are currently using if you'd like this functionality.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: MVC3, ASP.NET 4 - The resource cannot be found. I have VS2010, MVC3 and ASP.NET 4.0 with a simple test mvc application. The problem is that I am still keep getting error:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Pizzas/Pizza
Here is my simple controller :
public class PizzasController : Controller
{
public ActionResult Pizza()
{
var pizzas = new Pizza();
return View("Pizza", pizza);
}
}
Here is a part of my global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{Scripts}/{*pathInfo}");
routes.MapRoute(
"Pizza_1",
"Pizzas/Pizza",
new { controller = "Pizzas", action = "Pizza"}
);
routes.MapRoute(
"Pizzas_2", // Route name
"{controller}/{action}", // URL with parameters
new { controller = "Pizzas", action = "Pizza" } // Parameter defaults
);
}
I am trying to call this action from a pizza.cshtml by this way:
@Html.ActionLink("Test", "Pizza", "Pizzas");
When the both routes are uncomented, then execution goes to Pizza_2 route and it passes without problems. But if I commented out Pizza_2, then it goes to Pizza_1 and the error occurs without getting to the action method.
The application runs on ASP.NET development server (not IIS).
I noticed that it works with Pizza_2 route only when there is no full url specified:
http://localhost:2893
but if type the full url like this:
http://localhost:2893/Pizzas/Pizza
the error again occurs.
A: Remove
routes.IgnoreRoute("{Scripts}/{*pathInfo}");
According to http://msdn.microsoft.com/en-us/library/cc668201.aspx#url_patterns {Scripts} is parsed as parameter.
If you want to do passthrough for scripts, you should use
routes.IgnoreRoute("Scripts/{*pathInfo}");
A: I had the same issue but when i was looking at the warning list of the project i found out that i had a reference to the OracleDataAcces.dll. When rebuilding the project that dll was not able to be deleted due to the security problem. Then i right clicked the bin folder it was given only read only access then i deselected that and rebuilt again.
After that the page loaded without any issue. Hope this may resolve it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: how to extract rows from matrix based on value in first entry? This is another simple 'matrix' question in Mathematica. I want to show how I did this, and ask if there is a better answer.
I want to select all 'rows' from matrix based on value in the first column (or any column, I used first column here just as an example).
Say, find all rows where the entry in the first position is <=4 in this example:
list = {{1, 2, 3},
{4, 5, 8},
{7 , 8, 9}}
So, the result should be
{{1,2,3},
{4,5,8}}
Well, the problem is I need to use Position, since the result returned by Position can be used directly by Extract. (but can't be used by Part or [[ ]], so that is why I am just looking at Position[] ).
But I do not know how to tell Position to please restrict the 'search' pattern to only the 'first' column so I can do this in one line.
When I type
pos = Position[list, _?(# <= 4 &)]
it returns position of ALL entries which are <=4.
{{1, 1}, {1, 2}, {1, 3}, {2, 1}}
If I first get the first column, then apply Position on it, it works ofcourse
list = {{1, 2, 3},
{4, 5, 8},
{7 , 8, 9}};
pos = Position[list[[All, 1]], _?(# <= 4 &)]
Extract[list, pos]
--> {{1, 2, 3}, {4, 5, 8}}
Also I tried this:
pos = Position[list, _?(# <= 4 &)];
pos = Select[pos, #[[2]] == 1 &] (*only look at ones in the 'first' column*)
{{1, 1}, {2, 1}}--->
and this gives me the correct positions in the first column. To use that to find all rows, I did
pos = pos[[All, 1]] (* to get list of row positions*)
---> {1, 2}
list[[ pos[[1]] ;; pos[[-1]], All]]
{{1, 2, 3},
{4, 5, 8}}
So, to summarize, putting it all together, this is what I did:
method 1
list = {{1, 2, 3},
{4, 5, 8},
{7 , 8, 9}};
pos = Position[list[[All, 1]], _?(# <= 4 &)]
Extract[list, pos]
--> {{1, 2, 3}, {4, 5, 8}}
method 2
list = {{1, 2, 3},
{4, 5, 8},
{7 , 8, 9}}
pos = Position[list, _?(# <= 4 &)];
pos = Select[pos, #[[2]] == 1 &];
pos = pos[[All, 1]];
list[[ pos[[1]] ;; pos[[-1]], All]]
{{1, 2, 3},
{4, 5, 8}}
The above clearly is not too good.
Is method 1 above the 'correct' functional way to do this?
For reference, this is how I do the above in Matlab:
EDU>> A=[1 2 3;4 5 8;7 8 9]
A =
1 2 3
4 5 8
7 8 9
EDU>> A( A(:,1)<=4 , :)
1 2 3
4 5 8
I am trying to improve my 'functional' handling of working with matrices in Mathematica commands, this is an area I feel I am not good at working with lists. I find working with matrices easier for me.
The question is: Is there is a shorter/more functional way to do this in Mathematica?
thanks
A: You could use Pick[] as follows:
Pick[list, list[[All, 1]], _?(# <= 4 &)]
A: How about the following?
In[1]:= list = {{1, 2, 3}, {4, 5, 8}, {7, 8, 9}};
In[2]:= Select[list, First[#] <= 4 &]
Out[2]= {{1, 2, 3}, {4, 5, 8}}
Here's a loose translation of your matlab code:
list[[Flatten[Position[Thread[list[[All, 1]] <= 4], True]]]]
(of course, the Flatten would not be needed if I used Extract instead of Part).
A: There is a faster method than those already presented, using SparseArray. It is:
list ~Extract~
SparseArray[UnitStep[4 - list[[All, 1]]]]["NonzeroPositions"]
Here are speed comparisons with the other methods. I had to modify WReach's method to handle other position specifications.
f1[list_, x_] := Cases[list, {Sequence @@ Table[_, {x - 1}], n_, ___} /; n <= 4]
f2[list_, x_] := Select[list, #[[x]] <= 4 &]
f3[list_, x_] := Pick[list, (#[[x]] <= 4 &) /@ list]
f4[list_, x_] := Pick[list, UnitStep[4 - list[[All, x]]], 1]
f5[list_, x_] := Pick[list, Thread[list[[All, x]] <= 4]]
f6[list_, x_] := list ~Extract~
SparseArray[UnitStep[4 - list[[All, x]]]]["NonzeroPositions"]
For a table with few rows and many columns (comparing position 7):
a = RandomInteger[99, {250, 150000}];
timeAvg[#[a, 7]] & /@ {f1, f2, f3, f4, f5, f6} // Column
0.02248
0.0262
0.312
0.312
0.2808
0.0009728
For a table with few columns and many rows (comparing position 7):
a = RandomInteger[99, {150000, 12}];
timeAvg[#[a, 7]] & /@ {f1, f2, f3, f4, f5, f6} // Column
0.0968
0.1434
0.184
0.0474
0.103
0.002872
A: If you want the rows that meet the criteria, use Cases:
Cases[list, {n_, __} /; n <= 4]
(* {{1, 2, 3}, {4, 5, 8}} *)
If you want the positions within the list rather than the rows themselves, use Position instead of Cases (restricted to the first level only):
Position[list, {n_, __} /; n <= 4, {1}]
(* {{1}, {2}} *)
A: If you want to be very clever:
Pick[list, UnitStep[4 - list[[All, 1]]], 1]
This also avoids unpacking, which means it'll be faster and use less memory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do you remove a button's active state with jQuery Mobile? In my mobile app, using jQuery Mobile...
*
*I would like to make a simple button execute a simple javascript function on click. No page transitions, nothing special like that.
*I understood I can eliminate the page transitions by doing return false or preventDefault()
*But the problem is the button sticks with the "active" state, i.e. highlighted blue if you use the general theme. I'm wondering how I can remove that after click (or tap, etc).
Thanks.
A: Do NOT set the activeBtnClass to '' as suggested, this will cause errors when closing dialogs and the pageLoading function.
The method described does work, but cannot be set to null, the activeBtnClass variable is used as a selector, so set it to a non-existent class to get the same effect without the error.
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).bind('mobileinit', function () {
$.mobile.activeBtnClass = 'aBtnSelector';
});
</script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
</head>
This works well to remove the highlight from the buttons while keeping the active state on other elements.
A: You can disable the 'highlighted blue'-state in the 'mobileinit'-event before loading jQueryMobile-script:
<head>
<script>
$(document).bind('mobileinit', function () {
$.mobile.activeBtnClass = 'unused';
});
</script>
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
</head>
Now, when you click on a link, no class will be added after the click is performed. You will still have the 'hoover' and 'down' classes.
A: Update:
This question and the hacks suggested are now a bit outdated. jQuery mobile handles buttons quite a bit differently than 3 years ago and also, jQuery mobile now has several different definitions of "button". If you want to do what the OP was looking for, you might now be able to avoid the issue by using this:
Step 1:
<button class="ui-btn myButton">Button</button>
Alternatively, you could also use jQuery mobile input buttons:
<form>
<input value="Button One" type="button" class="myButton">
<input value="Button Two" type="button" class="myButton2">
</form>
Step 2:
Then your standard jquery on callback:
$(".myButton").on("tap", function(e) {
// do your thing
});
If you are using a button or a tab, or whatever, that has the "active" class applied to it (the default is ui-btn-active), the old answer may still be useful to someone. Also, here is a fiddle demonstrating the code below.
Selectively removing active state:
As demonstrated in another answer, you can disable the active state for all buttons on all pages. If that is acceptable for the project in question, that is the appropriate (and simpler) solution. However, if you want to disable the active state for some buttons while preserving active states for others, you can use this method.
Step 1:
$(document).bind('mobileinit', function() {
$(document).on('tap', function(e) {
$('.activeOnce').removeClass($.mobile.activeBtnClass);
});
});
Step 2:
Then add the activeOnce class (or whatever you want to call it - it's a custom class) to the buttons that you don't want to highlight when clicking.
And as is usual when binding anything to mobileinit, be sure you place your bindings - and perhaps better, all your javascript code - below the jQuery script and above the jQuery-mobile script.
<script src="js/jquery.js"></script>
<script src="js/my_script.js"></script>
<script src="js/jquery.mobile.js"></script>
A: you can just do it via css instead of java:
eg: (you get the idea)
#cart #item_options .ui-btn-active, #cart #item_options .ui-btn-hover-d, #cart #item_options .ui-btn-up-d, #cart #item_options .ui-link-inherit{
background:inherit;
color:inherit;
text-shadow:inherit;
}
A: What I do is force the buttons to revert to inactive state before a page changes.
//force menu buttons to revert to inactive state
$( '.menu-btn' ).on('touchend', function() {
$(this).removeClass("ui-btn-active");
});
A: If you want to support non touch devices you should add timeout.
$('.btn' ).on('touchend click', function() {
var self = this;
setTimeout(function() {
$(self).removeClass("ui-btn-active");
},
0);
});
A: I have spent the good part of a day and night finding the answer to this problem mainly occurring on an android running phonegap. Instead of the standard JQM buttons I am using custom images with :active state in CSS. After following the link to the next page, then clicking back, the button would just stay in the :active state. I have tried adding classes and removing classes and various other suggestions and nothing has worked.
So I came up with my own little fix which works a treat and may help anyone else that is sitting here stumped. I simply call this snippet of code on 'pagecontainerchange' using data.toPage[0].id to only call it on the page where the active state stuck is occurring. Just make sure to wrap your buttons in a div, in my case called "themenu".
function ResetMenu() {
var menuHtml = $("#themenu").html();
$("#themenu").empty().html(menuHtml).trigger("create");
}
A: This works for a button in the JqueryMobile headerTab
<style>
.Foo {
color: #FFF !important;
background: #347b68 !important;
}
</style>
<div id="headerTab" data-id="headerTab" data-role="navbar">
<ul id="header_tabs">
<li><a href="#" data-transition="none" id="unique-id" class="Foo">name</a>
</li>
</ul>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Emacs yanking (pasting) from website always yields character code 160 instead of SPC When copying code from the web (usually using Chrome in Ubuntu) I am frustrated by the fact that Emacs inserts blank spaces of Char: (160, #o240, #xa0) wherever there should be a space character, Char: SPC (32, #o40, #x20). This appears fine in the editor but as soon as I try to execute the code I get errors. How can I make Emacs convert entities into normal space characters?
A: You can use query-replace (M-%) to convert the characters. Copy-paste can help you enter the non-breaking space.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How does one make jQuery Mobile load pages into the DOM when going through a JSP servlet? jQuery Mobile will background-load additional 'pages' into the DOM, then transition to them. This works well sometimes, but in the example where one uses a JSP servlet, it seems to break. I wondered what the best way to do this would be.
For instance, say we have on our first page this:
<div data-role="page" id="home">
<div data-role="content">
<a href="jqmServlet?value=1.1">1.1</a>
</div>
</div>
Where the 1.1 is something that can be different, and so cause the servlet to do something different.
Now the servlet returns a page containing this:
<div data-role="page" id=${pageThing}>
<div data-role="content">
<a href="#OTHER_1">other 1</a></li>
</div>
</div>
<div data-role="page" id="OTHER_1">
<div data-role="content">
<p>Other 1 Content</p>
</div>
</div>
Starting the first page, I click "1.1", it goes to the servlet, and I see the "other 1" link. So that is all expected. But when I click "other 1", it fails because the underlying link looks like jqmServlet?value=1.1#OTHER_1, which is clearly not what I intended. What I intended was the "Other 1 Content" be displayed just using the content already in the DOM.
I started playing with the "data-url" parameter, but haven't figured out the secret handshake yet.
What's the right way to do this?
EDIT: It seems to me this would be a standard thing that would need to get done. I tried dozens of variations of the data-url, but I could not get it working properly; there was always some problem with the URL or if I got the URL looking pretty good, it still didn't show the 'OTHER_1' page (it just acted as if that page in the DOM didn't exist). I was going to replace the link with a call to JavaScript, but that sort of negates the value of this tool. Anyone have any ideas at all?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Entity Framework - A 'GetAll' function using a View Model I've created the following view model:
public class PropertyViewModel
{
public PropertyViewModel(Property property, IList<PropertyImage> images)
{
this.property = property;
this.images = images;
}
public Property property { get; private set; }
public IList<PropertyImage> images { get; private set; }
}
Now i need to create a function that gets all the properties in the database along with their associated images. Is it possible to do this using the viewmodel above? I have tried the following.
public IList<PropertyViewModel> GetAllPropertyViews()
{
IList<PropertyViewModel> properties = null;
foreach (var property in GetAllProperties().ToList())
{
IList<PropertyImage> images = db.PropertyImages.Where(m => m.Property.PropertyID == property.PropertyID).ToList();
properties.Add(new PropertyViewModel(property, images));
}
return properties;
}
This doesn't work, it gives "Object reference not set to an instance of an object." at properties.Add(new PropertyViewModel(property, images));
For the paginatation method i'm using i need to return an IQueryable variable. Any suggestions would be greatly appreciated.
A: Your properties variable is null, hence you get a NullReferenceException - just initialize it with an instance of a concrete class that implements IList<PropertyViewModel>:
IList<PropertyViewModel> properties = new List<PropertyViewModel>();
A better solution would be to get all the related PropertyImages in one query by using an EF Include() query - your repository layer (that you seem to have on top of EF) must support this though. Currently you are executing N queries on your database, one for each property.
Edit:
This should be the equivalent using EF Include() query, which will grab the related PropertyImages for each property:
var properties = db.Properties
.Include( x=> x.PropertyImages);
.Select( x => new PropertyViewModel(x, x.PropertyImages.ToList())
.ToList();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create plugin for mpg in a digital library using perl? I am looking for creating a plugin for greenstone digital library for extracting metadata from mpg file.Can anyone help me with any documentation?I am totally new in perl,so I am also looking for good reference book for learning perl.
A: Image::ExifTool can be used for parsing MPEG (and many other formats) files. The documentation has many usage examples. For example, to print the BitDepth of a file:
#!/usr/bin/env perl
use strict;
use warnings;
use Image::ExifTool;
my $filename = '/path/to/file';
my $exif_tool = Image::ExifTool->new;
$exif_tool->ExtractInfo($filename);
print $exif_tool->GetValue('BitDepth');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Query on Jython with Web Start I am looking at creating a jython application and deploying it as a java web start.
My query is related to a concern that for web start deployment, we have to distribute the jython standard jar package also along with our application jar.
From all the web resources , this is what I hear. And the concern is that this will make the download time of the application significantly large as jython jar file is nearly 9 Mb.
If anyone of you has deployed a jython app through web start, can you clarify if we need to bundle the jython jar package along with our application files or only the application files in a standalone jar file ( this solves my problem)
Regards
Shyam
A: OK , as I figured out...I have to package the jython jar also along with the application jar to make it work.
The reason is that, the application jar consists of python code which the client JVM has no way to understand unless it uses the jython jar package.
As I hear jython has no support currently to convert python code to java classes. Unless this is possible , the jython jar package has to be included.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Referencing a related object in Pyramids/Python/SQLAlchemy I'm not sure how to title this question. I've also simplified my code so it's easier to ask. Say I have the following code in myproject.models in Pyramid:
class Links(Base):
__tablename__ = 'links'
id = Column(Integer, primary_key=True)
link = Column(Text)
def __init__(self, link):
self.link = link
class Submissions(Base):
__tablename__ = 'submissions'
id = Column(Integer, primary_key=True)
title = Column(Text)
link_id = Column(Integer, ForeignKey('links.id'))
link = relationship(Links)
def __init__(self, title, link):
self.title = title
self.link = link
The view will be very simple:
def my_view(request):
dbsession = DBSession()
submissions = dbsession.query(Submissions)
return {'submissions':submissions}
I want to return this on my page using Chameleon:
<p tal:repeat="thing submissions">
${thing.title} ${thing.link}
</p>
However, ${thing.link} doesn't show the link of the site.
Questions:
*
*How do I reference thing.link's link? Intuitively, I would type ${thing.link.link}, but that doesn't work.
*How do I reference an arbitrary subclass? I want to be able to extract any attribute from an object's subclass, for example, thing.link.link, thing.link.domain, thing.link.created, etc.
BTW, someone please tell me a better title to give this question.
A: In your example, you are missing the .all() after your .query(). You can check in your view if your submissions are really loaded by doing something like
for submission in submissions:
print submission.id, submission.title
and then watch your console when loading the page.
Then, when you confirmed you really have them loaded, you can access the link object with submission.link. In the link object, you can access the link attribute with .link.
for submission in submissions:
print submission.link.link
So in your template, you could write ${thing.link.link}.
A: Assuming you do have the link object attached (given the fact that the link_id column is not nullable), most probably you need to (eager)load the relationship to Links because the session is alread closed when you populate your view.
See Relationship Loading Techniques for more information. The code below should do it:
submissions = dbsession.query(Submissions).options(joinedload('link'))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Global variables vs. passing a value into a function? I'm new to JavaScript, and have a simple (I presume) question regarding best practices for accessing variables in functions:
When should I declare a global variable, as opposed to simple passing a value into a function?
A: Declaring a global variable should only be used as an option of last resort.
Global variables are bad in general and especially so in javascript. There is simply no way to prevent another piece of javascript from clobbering your global. The clobbering will happen silently and lead to runtime errors.
Take the following as an example.
// Your code
myParam = { prop: 42 };
function operateOnMyParam() {
console.log(myParam.prop);
}
Here i've declared 2 global variables
*
*myParam
*operateOnMyParam
This might work fine while testing your javascript in isolation. However what happens if after testing a user combines your javascript library with my javascript library that happens to have the following definitions
// My code
function myParam() {
console.log("...");
}
This also defines a global value named myParam which clashes with your myParam. Which one wins depends on the order in which the scripts were imported. But either way one of us is in trouble because one of our global objects is dead.
A: There are many, many reasons.. but an easy one is.. The argument of a function only exists in the function, while it's running. A global variable exists all the time, which means:
*
*it takes up memory until you manually 'destroy' it
*Every global variable name needs to be unique
*If, within your function.. you call another function.. which ends up calling the first function, all of a sudden you may get unexpected results.
In short: because the function argument only lives for a really short time and does not exist outside the function, it's much easier to understand what's going on, and reduced the risk of bugs greatly.
A: When dealing with framework-less JavaScript I'll store my simple variables and functions in an object literal as to not clutter up the global namespace.
var myObject = {
variableA : "Foo",
variableB : "Bar",
functionA : function(){
//do something
//access local variables
this.variableA
}
}
//call functions and variables
myObject.variableA;
myObject.functionA();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Asp.net HttpCookie Read/Write problem I've been searching a solution for this problem but i couldn't have one. By the way i can't understand the reason of my problem.
The problem is:
My web application has a login page and gets logged user id from cookie. It worked before but 5-6 days ago because of something changed it didn't worked with IE. Now it doesn't work with any browser.
I can see the cookie in Chrome. When looked with Internet Explorer Developer Tool sometimes the cookie written but still can't read by IE
My web app is on Windows Server 2008 R2 BTW
Set my web.config:
<httpCookies domain=".domainname.com" httpOnlyCookies="false" requireSSL="false" />
Here is my SetCookie code
<!-- language: c# -->
string uId = "userID";
DateTime expireDate = DateTime.Now.AddDays(3);
HttpContext.Current.Response.Cookies["cookieName"]["uID"] = uId;
HttpCookie aCookie = new HttpCookie("cookieName");
aCookie.Values["uID"] = uId;
aCookie.Path = "/";
aCookie.Expires = expireDate;
aCookie.HttpOnly = false;
aCookie.Domain = "domainname.com";
aCookie.Name = "cookieName";
HttpContext.Current.Response.Cookies.Add(aCookie);
And this GetCookie code
<!-- language: c# -->
if (HttpContext.Current.Request.Cookies["cookieName"] != null)
{
System.Collections.Specialized.NameValueCollection UserInfoCookieCollection;
UserInfoCookieCollection = HttpContext.Current.Request.Cookies["cookieName"].Values;
userID = HttpContext.Current.Server.HtmlEncode(UserInfoCookieCollection["uID"]);
}
The scenario is:
trying to log in
SetCookie method triggered
End of SetCookie method there are two cookies "cookieName" and
"ASP.NET SessionId"
GetCookie method triggered
There is only "ASP.NET SessionId" and session value still same
Thanks for any help.
A: My problem solved. Changed my code to this
string uId = "userID";
DateTime expireDate = DateTime.Now.AddDays(3);
var httpCookie = HttpContext.Current.Response.Cookies["cookieName"];
if (httpCookie != null)
{
httpCookie["uID"] = uId;
HttpContext.Current.Response.Cookies.Add(httpCookie);
}
else
{
HttpCookie aCookie = new HttpCookie("cookieName");
aCookie.Values["uID"] = uId;
aCookie.Expires = expireDate;
HttpContext.Current.Response.Cookies.Add(aCookie);
}
A: This one had me stumped. But managed to solve it as follows. So basically setting the expiry as part of the initialiser does not work. Setting it after adding the cookie to the response object works!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What would be the right fcntl flags? What would be the right fcntl flags when reading from a disk and writing to a file over the network for best speed?
perhaps the issues is with the fcntl flags set on the file descriptor?
A: I don't think fcntl offers you anything that would affect performance. Perhaps you're looking for posix_fadvise, but I think the main key is just to use reasonably large buffers.
A: I am assuming that you are using NFS (or something like that) to read/write to a file across the network. The best option is to read/write as large as necesssary parts of the file. Then the NFS has more options as to dividing the data up into the larger size packets - hence less overhead in terms of the network stack.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: cannot convert to a pointer type : C error I have a function that I need to call
int (*trytoprint_f)(int val, void *param);
but when I call this function, and put
str name = {"jack", 4};
int age = 2;
client->trytoprint(age, (void *)name));
it gives me an error of "cannot convert to a pointer type : C error"
I know the solution which is basically use a function below
str_dup_ptr(name, ulr->imsi, mem); and it works (I got this function from a framework).
Anyways, I am just confused. So the question is if the function accepts (void *param), and I declare name variable with type str, howso when I cast this "name" variable into void pointer, it returns me this error?
Can anyone help me in understanding why this error happens?
Thank you
A: You have to convert a pointer to structure to void* not a structure itself. Try this way
client->trytoprint(age, (void *) &name));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to separate images out from Resources in iOS I'm displaying a set of images in my app. I've got the code working when I load the image from the Resources folder, like so:
- (void)viewDidLoad
{
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:[NSString stringWithFormat: @"pic_a"]];
[array addObject:[NSString stringWithFormat: @"pic_b"]];
[array addObject:[NSString stringWithFormat: @"pic_c"]];
[array addObject:[NSString stringWithFormat: @"pic_d"]];
int index = arc4random() % [array count];
NSString *pictureName = [array objectAtIndex:index];
NSString* imagePath = [ [ NSBundle mainBundle] pathForResource:pictureName ofType:@"png"];
UIImage *img = [ UIImage imageWithContentsOfFile: imagePath];
if (img != nil) { // Image was loaded successfully.
[imageView setImage:img];
[imageView setUserInteractionEnabled:NO];
[img release]; // Release the image now that we have a UIImageView that contains it.
}
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
However, if I create an "images" group within the "Resources" group, and put try to load the images from there, the image within the view shows up blank.
[array addObject:[NSString stringWithFormat: @"images/pic_a"]];
[array addObject:[NSString stringWithFormat: @"images/pic_b"]];
[array addObject:[NSString stringWithFormat: @"images/pic_c"]];
[array addObject:[NSString stringWithFormat: @"images/pic_d"]];
I'd like to separate the images out from the nib files and all the other cruft. What's the best way to do that?
A: Even if you have the images in a separate group within Resources, you can load them by calling the name, e.g. use this one line
UIImage *img = [UIImage imageNamed:[array objectAtIndex:index]];
in place of these three lines:
NSString *pictureName = [array objectAtIndex:index];
NSString* imagePath = [ [ NSBundle mainBundle] pathForResource:pictureName ofType:@"png"];
UIImage *img = [ UIImage imageWithContentsOfFile: imagePath];
You will still fill the array simply by
[array addObject:[NSString stringWithFormat: @"pic_a"]];
If you have both jpg and png files, then you should append .png to the end of the file names. Otherwise, leaving it off is fine.
A: Try using the imageNamed: method instead of imageWithContentsOfFile:
A: Remember that adding groups inside your project it is simply for organization and look within Xcode. You adding a group will not change the fact that the images will be saved in the main bundle. If you are trying to find them using the images group in the string it will not find them.
There are some things you can do to make this work, but in reality you don't need to.
A: You need to create a physical folder called images (it should have a blue color instead of the usual yellow color)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Efficient way to Handle ResultSet in Java I'm using a ResultSet in Java, and am not sure how to properly close it. I'm considering using the ResultSet to construct a HashMap and then closing the ResultSet after that. Is this HashMap technique efficient, or are there more efficient ways of handling this situation? I need both keys and values, so using a HashMap seemed like a logical choice.
If using a HashMap is the most efficient method, how do I construct and use the HashMap in my code?
Here's what I've tried:
public HashMap resultSetToHashMap(ResultSet rs) throws SQLException {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
HashMap row = new HashMap();
while (rs.next()) {
for (int i = 1; i <= columns; i++) {
row.put(md.getColumnName(i), rs.getObject(i));
}
}
return row;
}
A: *
*Iterate over the ResultSet
*Create a new Object for each row, to store the fields you need
*Add this new object to ArrayList or Hashmap or whatever you fancy
*Close the ResultSet, Statement and the DB connection
Done
EDIT: now that you have posted code, I have made a few changes to it.
public List resultSetToArrayList(ResultSet rs) throws SQLException{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
ArrayList list = new ArrayList(50);
while (rs.next()){
HashMap row = new HashMap(columns);
for(int i=1; i<=columns; ++i){
row.put(md.getColumnName(i),rs.getObject(i));
}
list.add(row);
}
return list;
}
A: this is my alternative solution, instead of a List of Map, i'm using a Map of List.
Tested on tables of 5000 elements, on a remote db, times are around 350ms for eiter method.
private Map<String, List<Object>> resultSetToArrayList(ResultSet rs) throws SQLException {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
Map<String, List<Object>> map = new HashMap<>(columns);
for (int i = 1; i <= columns; ++i) {
map.put(md.getColumnName(i), new ArrayList<>());
}
while (rs.next()) {
for (int i = 1; i <= columns; ++i) {
map.get(md.getColumnName(i)).add(rs.getObject(i));
}
}
return map;
}
A: A couple of things to enhance the other answers. First, you should never return a HashMap, which is a specific implementation. Return instead a plain old java.util.Map. But that's actually not right for this example, anyway. Your code only returns the last row of the ResultSet as a (Hash)Map. You instead want to return a List<Map<String,Object>>. Think about how you should modify your code to do that. (Or you could take Dave Newton's suggestion).
A: I just cleaned up RHT's answer to eliminate some warnings and thought I would share. Eclipse did most of the work:
public List<HashMap<String,Object>> convertResultSetToList(ResultSet rs) throws SQLException {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
while (rs.next()) {
HashMap<String,Object> row = new HashMap<String, Object>(columns);
for(int i=1; i<=columns; ++i) {
row.put(md.getColumnName(i),rs.getObject(i));
}
list.add(row);
}
return list;
}
A: RHT pretty much has it. Or you could use a RowSetDynaClass and let someone else do all the work :)
A: i improved the solutions of RHTs/Brad Ms and of Lestos answer.
i extended both solutions in leaving the state there, where it was found.
So i save the current ResultSet position and restore it after i created the maps.
The rs is the ResultSet, its a field variable and so in my solutions-snippets not visible.
I replaced the specific Map in Brad Ms solution to the gerneric Map.
public List<Map<String, Object>> resultAsListMap() throws SQLException
{
var md = rs.getMetaData();
var columns = md.getColumnCount();
var list = new ArrayList<Map<String, Object>>();
var currRowIndex = rs.getRow();
rs.beforeFirst();
while (rs.next())
{
HashMap<String, Object> row = new HashMap<String, Object>(columns);
for (int i = 1; i <= columns; ++i)
{
row.put(md.getColumnName(i), rs.getObject(i));
}
list.add(row);
}
rs.absolute(currRowIndex);
return list;
}
In Lestos solution, i optimized the code. In his code he have to lookup the Maps each iteration of that for-loop. I reduced that to only one array-acces each for-loop iteration. So the program must not seach each iteration step for that string-key.
public Map<String, List<Object>> resultAsMapList() throws SQLException
{
var md = rs.getMetaData();
var columns = md.getColumnCount();
var tmp = new ArrayList[columns];
var map = new HashMap<String, List<Object>>(columns);
var currRowIndex = rs.getRow();
rs.beforeFirst();
for (int i = 1; i <= columns; ++i)
{
tmp[i - 1] = new ArrayList<>();
map.put(md.getColumnName(i), tmp[i - 1]);
}
while (rs.next())
{
for (int i = 1; i <= columns; ++i)
{
tmp[i - 1].add(rs.getObject(i));
}
}
rs.absolute(currRowIndex);
return map;
}
A: Here is the code little modified that i got it from google -
List data_table = new ArrayList<>();
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(conn_url, user_id, password);
Statement stmt = con.createStatement();
System.out.println("query_string: "+query_string);
ResultSet rs = stmt.executeQuery(query_string);
ResultSetMetaData rsmd = rs.getMetaData();
int row_count = 0;
while (rs.next()) {
HashMap<String, String> data_map = new HashMap<>();
if (row_count == 240001) {
break;
}
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
data_map.put(rsmd.getColumnName(i), rs.getString(i));
}
data_table.add(data_map);
row_count = row_count + 1;
}
rs.close();
stmt.close();
con.close();
A: public static List<HashMap<Object, Object>> GetListOfDataFromResultSet(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int count = metaData.getColumnCount();
String[] columnName = new String[count];
List<HashMap<Object,Object>> lst=new ArrayList<>();
while(rs.next()) {
HashMap<Object,Object> map=new HashMap<>();
for (int i = 1; i <= count; i++){
columnName[i-1] = metaData.getColumnLabel(i);
map.put(columnName[i-1], rs.getObject(i));
}
lst.add(map);
}
return lst;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "62"
} |
Q: Redirecting mysite.com/somepage/thispage.php to www.mysite.com/somepage/thispage.php I tried doing this
RewriteEngine On
rewritecond %{http_host} ^mysite.com
rewriteRule ^(.*) http://www.mysite.com/$1 [R=301,L]
but when i go to mysite.com, it took me to http://www.mysite.com/mysite. So I removed the $1 and that seemed to fix the issue.
But now that when I go to mysite.com/somepage/thispage.php, it does not work and shows the page not found (the www.mysite.com actually points to where the site is hosted, thats why I want mysite.com to go to www.mysite.com). How can I redirect that to mysite.com/somepage/thispage.php and also the other anything appended to mysite.com?
A: RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Redirects all non-www url's to www.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to test tsql variable contents as expression
Possible Duplicate:
How to execute mathematical expression stored in a varchar variable
Using pure TSQL, is it possible to evaluate an expression defined to a variable?
Here is a simple example, its only for proof in concept:
DECLARE @TestValue AS VARCHAR (2) = '7';
DECLARE @myRule AS VARCHAR (100) = 'case when (#val#>0 and #val#<10) then 1 else 0 end';
SET @myRule = replace(@myRule, '#val#', @TestValue);
PRINT @myRule;
-- case when (7>0 and 7<10) then 1 else 0 end
--How to evaluate the expression in @myRule for True/False?
A: --Based on How to execute mathematical expression stored in a varchar variable
DECLARE @out AS BIT, @sql AS NVARCHAR (4000);
SET @sql = N'SELECT @out = ' + @myRule;
EXECUTE sp_executesql @sql, N'@out bit OUTPUT', @out OUTPUT;
PRINT 'sp_executesql=' + CAST (@out AS VARCHAR (10));
--sp_executesql=1
I've tested this approach and it seems to be sound. Not sure if there are performance considerations, but for now I'll mark as answered.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Dynamic size, two column layout with one column vertically and horizontally aligned, legacy browser support I am trying to create a two column layout, with content in column 1 both horizontally and vertically aligned in the middle, whereby the content of column 2 will vary in size. The width of both columns is fixed to 50% of the width of the screen.
In modern CSS complaint browsers I can simply do the following:
CSS:
#wrapper
{
display: table;
width: 100%;
/* for illustration purposes */
background: #ddd;
}
#left-column
{
display: table-cell;
width: 50%;
text-align: center;
vertical-align: middle;
/* for illustration purposes */
background: #fdd;
}
#right-column
{
display: table-cell;
/* for illustration purposes */
background: #ddf;
}
HTML:
<div id="wrapper">
<div id="left-column">
<p>I am both horizontally and vertically centered in column 1</p>
</div>
<div id="right-column">
<p>I am dynamic content in column 2, i.e. my size will vary</p>
<p>I am dynamic content in column 2, i.e. my size will vary</p>
<p>I am dynamic content in column 2, i.e. my size will vary</p>
<p>I am dynamic content in column 2, i.e. my size will vary</p>
<p>I am dynamic content in column 2, i.e. my size will vary</p>
</div>
</div>
However, the bad news is I also need this to work in IE6, and IE7...
The solutions I've seen so far are quite ugly and involve lots of nested divs. What's the cleanest way to achieve this so that it will work in all browsers? I've experimented with float: left, for the two column layout, but my main problem is the vertical alignment in the first column.
PS. I don't want to use tables for the layout, although it does work, it's bad for screen readers and therefore breaks my accessibility guidelines.
Thanks in advance!
A: Unfortunately vertically centering something is either going to take javascript or a few ugly nested divs. If you are a maniacal purist I would recommend a float left, top aligned left column and enhance with javascript to be pushed to center.
That said, a couple wrapper divs never killed anyone.
A: With static content on the left-hand column, your solution is simple: use fixed heights and padding.
CSS
#left-column {
height: 50%; /* adjust height dependent on N&S padding */
padding: 20% 0; /* adds north and south padding to "center" #left-content */
}
#left-content {
height: 10%; /* adjust to exactly fit content */
text-align: center;
/* basically for testing, this will help us find the ideal
* percentage for our #left-content height. */
overflow: hidden;
background-color: red;
}
HTML
<div id="left-column">
<div id="left-content">
your image and text goes here
</div><!-- /left-content -->
</div><!-- /left-column -->
In your CSS, you will need to adjust the heights and paddings to achieve your desired result.
I would suggest ensuring the content in #left-content is 100% responsive. This may not be a 100% solution, but with some work on it (@media queries, etc), you should be able to achieve your goal in every browser and viewport size. The only thing I can think of off the top of my head that might break something like this is user-increased font size.
A: Cracked it, I think... Html as in the original post, and CSS as follows:
#wrapper
{
width: 100%;
overflow: hidden;
position: relative;
/* for illustration purposes */
background: #ddd;
}
#wrapper p { font-size:1em; margin: .5em; }
#right-column
{
margin-left: 50%;
overflow: hidden;
/* for illustration purposes */
background: #ddf;
}
#left-column
{
width: 50%;
height: 2em;
position: absolute;
left: 0;
top: 50%;
margin-top: -1em;
text-align: center;
/* for illustration purposes */
background: #fdd;
}
The margin on the inner <p> tag needs setting so that we know what the height will be (the different browsers seem to default the margin of a <p> differently if you don't explicitly set it), I used em so that it scales nicely on different displays.
It's funny how something this simple can be such a pain to achieve... I'm still not 100% happy with it as if the content of column 1 wraps on a small display (or minimised window), then it won't be vertically aligned properly...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Twitter.com - How is the login screen background image rendered? On the twitter.com login screen, there is a background which features a world map behind the text.
I've had a look and I'm not sure how it's being rendered. I found this one background image (http://a2.twimg.com/a/1316626057/phoenix/img/front/bg.png) which looks more like the color behind the globe overlay.
Any ideas how the map part is being generated?
A: The map is part of the logo image, which is #doc’s background image.
A: The div that takes up the whole page (<div id='doc'>) has this style set on it:
background: url("../img/front/logo-map.png") no-repeat scroll center top transparent
This makes that image the background of the div, and therefore the page.
A: That picture is not the world! that is just the body's background picture. The world, is background of this div:
<div class="route-front" id="doc">
and is in this folder:
../img/front/logo-map.png
related with this stylesheet file:
http://a2.twimg.com/a/1316626057/phoenix/css/phoenix_core_logged_out.bundle.css
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unions between pointers and data, possible pitfalls? I'm programming a system which has a massive amount of redundant data that needs to be kept in memory, and accessible with as little latency as possible. (uncompressed, the data is guaranteed to absorb 1GB of memory, minimum).
One such method I thought of is creating a container class like the following:
class Chunk{
public:
Chunk(){ ... };
~Chunk() { /*carefully delete elements according to mask*/ };
getElement(int index);
setElement(int index);
private:
unsigned char mask; // on bit == data is not-redundant, array is 8x8, 64 elements
union{
Uint32 redundant; // all 8 elements are this value if mask bit == 0
Uint32 * ptr; // pointer to 8 allocated elements if mask bit == 1
}array[8];
};
My question, is that is there any unseen consequences of using a union to shift between a Uint32 primative, and a Uint32* pointer?
A: This approach should be safe on all C++ implementations.
Note, however, that if you know your platform's memory alignment requirements, you may be able to do better than this. In particular, if you know that memory allocations are aligned to 2 bytes or greater (many platforms use 8 or 16 bytes), you can use the lower bit of the pointer as a flag:
class Chunk {
//...
uintptr_t ptr;
};
// In your get function:
if ( (ptr & 1) == 0 ) {
return ((uint32_t *)ptr)[index];
} else {
return *((uint32_t *)(ptr & ~(uintptr_t)0);
}
You can further reduce space usage by using a custom allocation method (with placement new) and placing the pointer immediately after the class, in a single memory allocation (ie, you'll allocate room for Chunk and either the mask or the array, and have ptr point immediately after Chunk). Or, if you know most of your data will have the low bit off, you can use the ptr field directly as the fill-in value:
} else {
return ptr & ~(uintptr_t)0;
}
If it's the high bit that's usually unused, a bit of bit shifting will work:
} else {
return ptr >> 1;
}
Note that this approach of tagging pointers is unportable. It is only safe if you can ensure your memory allocations will be properly aligned. On most desktop OSes, this will not be a problem - malloc already ensures some degree of alignment; on Unixes, you can be absolutely sure by using posix_memalign. If you can obtain such a guarentee for your platform, though, this approach can be quite effective.
A: If space is at a premium you may be wasting memory. It will allocate enough space for the largest element, which in this case could be up to be 64 bits for the pointer.
If you stick to 32-bit architectures you should not have problems with the cast.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Rails 3.1 attr_accessible verification receives an array of roles I would like to use rails new dynamic attr_accessible feature. However each of my user has many roles (i am using declarative authorization). So i have the following in my model:
class Student < ActiveRecord::Base
attr_accessible :first_name, :as=> :admin
end
and i pass this in my controller:
@student.update_attributes(params[:student], :as => user_roles)
user_roles is an array of symbols:
user_roles = [:admin, :employee]
I would like my model to check if one of the symbols in the array matches with the declared attr_accessible. Therefore I avoid any duplication.
For example, given that user_roles =[:admin, :employee]. This works:
@student.update_attributes(params[:student], :as => user_roles.first)
but it is useless if I can only verify one role or symbol because all my users have many roles.
Any help would be greatly appreciated
***************UPDATE************************
You can download an example app here:
https://github.com/jalagrange/roles_test_app
There are 2 examples in this app: Students in which y cannot update any attributes, despite the fact that 'user_roles = [:admin, :student]'; And People in which I can change only the first name because i am using "user_roles.first" in the controller update action. Hope this helps. Im sure somebody else must have this issue.
A: You can monkey-patch ActiveModel's mass assignment module as follows:
# in config/initializers/mass_assignment_security.rb
module ActiveModel::MassAssignmentSecurity::ClassMethods
def accessible_attributes(roles = :default)
whitelist = ActiveModel::MassAssignmentSecurity::WhiteList.new
Array.wrap(roles).inject(whitelist) do |allowed_attrs, role|
allowed_attrs + accessible_attributes_configs[role].to_a
end
end
end
That way, you can pass an array as the :as option to update_attributes
Note that this probably breaks if accessible_attrs_configs contains a BlackList (from using attr_protected)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: No P2P in Windows Metro applications? In the "A .NET developer's view of Windows 8 app development" session at BUILD, the lecturer mentions that only the client-side WCF features are exposed in the Metro profile, we cannot create a server.
( http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-930C?format=progressive @ ~34:00)
Does this mean that direct peer to peer communication is not possible for Metro applications, and any data exchanged between 2 users over the internet will always have to actually travel through a non-metro-style application?
A: Access to sockets is controlled by the "Internet (Client & Server)" capability, if this capability is enabled in your application, you should be able to send and receive data over the internet.
A: Since the Metro style apps can't run on background, and are designed to be used fregmentedly, making it P2P enabled makes little sense.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: java.net.MalformedURLException: unknown protocol: rsrc I get this;
java.net.MalformedURLException: unknown protocol: rsrc
I'm not entirely sure what to do about this unknown protocol. I am using simple RMI to communicate between two JVMs. Is it a jar that I am missing that contains this protocol and, if so, which one? I haven't found Google searches to be all that great for this issue.
Any help would be appreciated. Thanks.
EDIT2: To clarify, my RMI code works when running from Eclipse. It's when I export and use runnable jar files and such that it breaks.
EDIT: Here's a code snippet:
registry=LocateRegistry.getRegistry(
rmiServerAddress,
(new Integer(rmiServerPort)).intValue());
A: I finally figured it out. When using Eclipse and exporting a runnable jar file, make sure to choose under Library Handling:
Extract required libraries into generated JAR
That will fix this particular issue and probably many others.
A: Sorry, it's already too late on this side of the globe and I missed the your phrase! :-)
What about this issue? Basically, is the server running from a path in the filesystem with spaces in the pathname?
A: this option definitely works: Export > Runnable Jar File > Copy required libraries into a sub-folder
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Can I embed a Schema within a Schema in Mongoose? SocialProfileSchema = new mongoose.Schema
source: String
user_id: String
profile_url: String
UserProfileSchema = new mongoose.Schema
socialProfiles: [SocialProfileSchema]
That's my code. Is it valid?
A: Yes! This is valid it turns out!
A: That code will create an embedded documents array of SocialProfiles within UserProfiles -- http://mongoosejs.com/docs/embedded-documents.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Help with building object model Help me with building object model, please.
I need abstract class Unit representing each military unit in a game. There is Soldier, Tank, Jet and Bunker (children of Unit). Each of them has int properties Count and Defense, constructor with single int count parameter and one method GetTotalDefense.
My idea is following.
private abstract class Unit
{
private int Count { get; set; }
private const int Defense = 0;
protected Unit(int count)
{
Count = count;
}
public int GetTotalDefense()
{
return Count * Defense;
}
}
private class Tank : Unit
{
private const int Defense = 5;
}
Each unit has different Count and different Defense. Body of constructor and body of GetTotalDefense is always the same. What I need is in child class override Defense, because each unit has different. This property should be const, all instances of Tank (Soldier, ...) has same defense. Is there a possibility to inherit const property or each child needs its own const Defense property?
And here is an example I'd like to achieve.
Oh, there is also class Troop
public class Troop
{
private Soldier Soldiers { get; set; }
private Tank Tanks { get; set; }
private Jet Jets { get; set; }
private Fort Forts { get; set; }
public Troop(int soldiers, int tanks, int jets, int forts)
{
Soldiers = new Soldier(soldiers);
Tanks = new Tank(tanks);
Jets = new Jet(jets);
Forts = new Fort(forts);
}
public int GetTotalDefense()
{
return Soldiers.GetTotalDefense() + Tanks.GetTotalDefense() + Jets.GetTotalDefense() + Forts.GetTotalDefense();
}
}
Also, feel free to suggest better solution, thanks.
PS: I'm really strict about access modifiers, so be precise in your examples, thank you.
A: You can't really use a const but you can make a readonly property also are you sure you want the classes to be private and not internal or public?
public abstract class Unit {
protected Unit(int count) {
Count=count;
}
protected int Count { get; private set; }
protected abstract int Defense {get;}
public int TotalDefense {
get { return Count*Defense; }
}
}
public class Tank : Unit {
public Tank(int count) : base(count) {}
protected override int Defense {
get { return 5; }
}
}
public class Troop {
private Unit[] Troops;
public Troop(int soldiers, int tanks, int jets, int forts) {
Troops = new Unit[] {
new Soldier(soldiers),
new Tank(tanks),
new Jet(jets),
new Fort(forts)
};
}
// The using System.Linq you can do
public int TotalDefense {
get { return Troops.Sum(x=>x.TotalDefense);}
}
}
A: Although this solution does not use const, it achieves what you want:
internal abstract class Unit
{
private int Count { get; set; }
private int Defense { get; set; }
public int TotalDefense { get { return Count * Defense; } }
protected Unit(int defense, int count)
{
Defense = defense;
Count = count;
}
}
internal class Tank : Unit
{
protected Tank(int count)
: base(5, count) // you can use a const variable instead of 5
{
}
}
Or maybe this is more suitable:
internal abstract class Unit
{
private int Count { get; set; }
public abstract int Defense { get; }
public int TotalDefense { get { return Count * Defense; } }
protected Unit(int count)
{
Count = count;
}
}
internal class Tank : Unit
{
override public int Defense { get { return 5; } }
protected Tank(int count) : base(count)
{
}
}
A: What you're looking for is actually readonly. Also, since Defense is used in subclasses, you need to make it protected.
private abstract class Unit
{
private int _Count;
protected readonly const int Defense;
public int TotalDefense
{ get { return Count * Defense; } }
protected Unit (int count, int defense)
{
Defense = defense;
_Count = count;
}
}
private class Tank : Unit
{
public Tank (int Count)
: base (Count, 5)
{ }
}
public class Troop
{
public IEnumerable<Unit> Units { get; protected set; }
public Troop (int soldiers, int tanks, int jets, int forts)
{
Troops = new Unit[]
{
new Soldier (soldiers),
new Tank (tanks),
new Jet (jets),
new Fort (forts)
}
}
}
A: maybe something like this (but this is in java)
abstract class Unit {
Unit(int defense,int count) {
this.defense = defense;
this.count=count;
}
final int defense;
int count;
}
class Soldier extends Unit {
Soldier(int count) {
super(1,count);
}
}
class Tank extends Unit {
Tank(int count) {
super(5,count);
}
}
public class Main {
public static void main(String[] args) {
Unit[] units = { new Soldier(2), new Tank(3) };
for(Unit unit:units)
System.out.println(unit.count+" "+unit.defense);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JConsole times out when trying to connect I'm trying to use jconsole to connect to jetty. I can see that the relevant port is open with nmap, but when I try to connect to it using jconsole, the connection times out. (When I run jconsole with -debug it shows that the underlying problem is a timeout on read.) It doesn't matter which process I try to connect to. If I try to connect to some other local process that happens to be running on my laptop, it times out too.
A: Have you started your application with java -Dcom.sun.management.jmxremote ... ?
A: Did you solve this problem? I have lately had a similar situation and in my case the problem was that the VM seems to bind to the interface identified by resolving the hostname and in my case the hostname was bound to a "bad" IP address in /etc/hosts. Having the hostname resolve to 127.0.0.1 (for example) fixed it for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# Avoid creation of thread when entering method the second time say we declare and run a thread in a method which has a while(1) loop. How can one avoid to create and run a second thread when the method is called again?
I only want one thread to start in this method and every time the method is called again, there should be no thread creation all over again. Should I check for the thread name or should I declare the thread as a field of the class?
Any ideas how to do this?
Thanks,
Juergen
A: It sounds like the thread should indeed be a field of the class - although you'll have to be careful to access it in a thread-safe way, if there could be several threads calling the method to start with.
What do you want to happen the second time - should the method block, or just finish immediately, or perhaps throw an exception? If you don't need to wait for the thread to finish, you might be able to get away with just a flag instead of keeping a reference to the thread itself.
(Note that I've been assuming this is an instance method and you want one extra thread per instance.) If that's not the case, you'll have to adjust accordingly.
A: Have the method return a singleton, and start the thread in the singleton constructor.
A: Could you save the synchronization context the first time, check on subsequent times to see if it matches, and post back to it if necessary?
SynchronizationContext syncContext = null;
...
// "object state" is required to be a callback for Post
public void HiThar(object state) {
if (syncContext == null) {
syncContext = SynchronizationContext.Current;
} else {
syncContext.Post(HiThar, state);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Unwanted Margin in Layout <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainRlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:src="@drawable/moflow_main_screen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true" />
<TextView
android:id="@+id/txtMoflow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_above="@+id/initCapsText"
android:text="MoFlow"
android:textSize="40sp"
android:textColor="#FA3248"
android:typeface="serif" />
<TextView
android:id="@+id/initCapsText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_above="@+id/startBtn"
android:text="TESTING"
android:textSize="16sp"
android:textColor="#FFFFFF" />
<Button
android:id="@+id/startBtn"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:layout_above="@+id/manageBtn"
android:text="Start Testing" />
<Button
android:id="@+id/manageBtn"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Management" />
<Button
android:id="@+id/optionsBtn"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@+id/manageBtn"
android:text="Options" />
<Button
android:id="@+id/aboutBtn"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@+id/optionsBtn"
android:text="About" />
<Button
android:id="@+id/quitBtn"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@+id/aboutBtn"
android:text="Quit" />
</RelativeLayout>
I want the image view picture to go all the way down to the screen, but there is a margin at the bottom and I don't know where it's coming from. I thought it might be the image dimensions, but even setting to 1000x1000 pixels doesn't do anything to get rid of the margins, neither does setting alignParentBottom.
Here is a screenshot:
A: Does the image you are using match the dimensions of the screen?
If not:
Try setting android:scaleType="fitXY" on the ImageView
- This will scale the image to fit the screen but will not retain the images original aspect ratio.
If you want to maintain the aspect ratio android:scaleType="center" will center the image with no scaling and maintains aspect ratio. However it will crop the image if it is larger than the screen, or it will not fill the screen if it is too small.
For other scale types, check out http://developer.android.com/reference/android/widget/ImageView.ScaleType.html
Hope this helps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: drop down onchange new fields I'm trying to have a dropdown menu that when the user chooses a specific value, it can produce an additional input box or checkbox or any other type of input. each value could can show different results, or none at all. and when the values change, so do the options.
Anyone have a suggestion or link i can read?
EDIT
Here kinda what I mean in case the above made no sense.
<select name="type" onchange="jqueryfunction('pass_selected_option')">
<option value="fooa">Add 2 Texboxes</option>
<option value="foob">Add 3 radios</option>
<option value="fooc">add 2 checkboxes and 2 textboxes</option>
</select>
A: You can do it like this:
$("select#type").change(function(){
var value = $(this).val();
$("div#target").append('<input type="textbox" value='+value+'/>');
});
Take a look at this jsfiddle for working example: http://jsfiddle.net/v7yHU/
Updated to be more elegant and detach your html from logic.
HTML:
<select name="type" id="type" >
<option >Select a value...</option>
<option value="fooa">Add 2 Texboxes</option>
<option value="foob">Add 3 radios</option>
<option value="fooc">add 2 checkboxes and 2 textboxes</option>
</select>
<div id="target">
<div id="fooa">
<input type="textbox" value="tb1"/>
<input type="textbox" value="tb2"/>
</div>
<div id="foob">
<input type="radio" value="rb1"/>
<input type="radio" value="rb2"/>
<input type="radio" value="rb3"/>
</div>
<div id="fooc">
<input type="textbox" value="tb1"/>
<input type="textbox" value="tb2"/>
<input type="checkbox" value="cb1"/>
<input type="checkbox" value="cb2"/>
</div>
</div>
JavaScript:
$(document).ready(function(){
//hide all in target div
$("div", "div#target").hide();
$("select#type").change(function(){
// hide previously shown in target div
$("div", "div#target").hide();
// read id from your select
var value = $(this).val();
// show rlrment with selected id
$("div#"+value).show();
});
});
Working sample: http://jsfiddle.net/v7yHU/3/
With this js you can have n options in select, no need to change script.
A: You can use that code. Example is here jsFiddle
//HTML side
<div>
<select id="mySelect">
<option value="fooa">Add 2 Texboxes</option>
<option value="foob">Add 3 radios</option>
<option value="fooc">add 2 checkboxes and 2 textboxes</option>
</select>
</div>
<div id="divGeneratedElements"></div>
// Javascript side
$("#mySelect").change(function(){
switch($(this).val()){
case "fooa":
$("#divGeneratedElements").html("<input type='text' value='TextField 1' /><input type='text' value='TextField 2' />"); break;
case "foob":
$("#divGeneratedElements").html("<input type='radio' name='a'/> radio 1 <input type='radio'name='a' />radio 2<input type='radio'name='a'/>radio 3 "); break;
case "fooc":
$("#divGeneratedElements").html("<input type='text' value='TextField 1' /><input type='text' value='TextField 2' /> <input type='checkbox' />checkbox 1<input type='checkbox'/>checkbox 2 "); break;
}
})
A: Do you mean something like that?
<script type="text/javascript">
function jqueryfunction(el){
var value = el.value;
//var value = $(el).val();
}
</script>
<select name="type" onchange="jqueryfunction(this)">
<option value="fooa">Add 2 Texboxes</option>
<option value="foob">Add 3 radios</option>
<option value="fooc">add 2 checkboxes and 2 textboxes</option>
</select>
Better way:
<script type="text/javascript">
jQuery(function($){
$('#someselect').change(function(){
var $this = $(this);
switch($this.val()){
case 'fooa':
alert('FooA!');
break;
case 'foob':
alert('something!');
break;
}
});
});
</script>
<select id="someselect" name="type">
<option value="fooa">Add 2 Texboxes</option>
<option value="foob">Add 3 radios</option>
<option value="fooc">add 2 checkboxes and 2 textboxes</option>
</select>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C++ String Compare I have 2 strings: in, which contains a link originally entered by the user (assume it to be "http://google.com/test"), and found, which has already been found by an extraneous part of this program.
The goal of this function is to compare the section of string between http:// and /test, ie: "google.com"
The problem I'm encountering is that the loop is not adding to the compare string, thus the later attempt to compare the 2 strings in the program at runtime.
bool isLinkExternal(string in, string found)
{
string compare = "";
bool isExternal = false;
//Get domain of original link
for (int i = 6; in[i] != '/'; i++)
{
compare += in[i];
}
system("pause");
//Compare domains of original and found links
if (found.compare(7,compare.length(),compare) != 0)
isExternal = true;
return isExternal;
}
The error:
An unhandled exception of type
'System.Runtime.InteropServices.SEHException' occurred in
ParseLinks.exe
The line of code it points to:
if (found.compare(7,compare.length(),compare) == 0)
Fixed code (working):
bool isLinkExternal(string in, string found)
{
const int len = found.length();
int slashcount = 0;
string comp;
//Parse found link
for (int i = 0; i != len; i++)
{
//Increment when slash found
if (found[i] == '/')
{
slashcount++;
}
if (slashcount < 3)
{
comp += found[i];
}
}
//Compare domains of original and found links
if (in.compare(0,comp.length(),comp) == 0)
return false;
else
return true;
}
A: (int i = 6; in[i] != '/'; i++)
{
compare += in[i];
}
Did you mean this?
for (int i = 6; in[i] != '/'; i++)
{
compare += in[i];
}
At present, your string does not have seven characters in it, so your compare is invalid. In fact, you will need to add some bounds checking there in any case.
Also, the exception text implies that you're actually writing C++/CLI, not C++. Am I right?
A: Does this work better:
for (int i = 7; in[i] != '/'; i++)
{
compare += in[i];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Expand Child When Parent IsExpanded in a TreeView I am attempting to expand a Child Node when its parent is expanded.
Otherwise stated: (Child.IsExpanded == Parent.IsExpanded)
This appears right, but does not seem to work:
<TreeView ItemsSource="{Binding}">
<TreeView.ItemContainerStyle>
<Style TargetType="TreeViewItem">
<Style.Triggers>
<DataTrigger Value="True"
Binding="{Binding Path=IsExpanded,
RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type TreeViewItem},
AncestorLevel=2}}">
<Setter Property="IsExpanded" Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
Neither does this:
<TreeView ItemsSource="{Binding}">
<TreeView.ItemContainerStyle>
<Style TargetType="TreeViewItem">
<Setter Property="IsExpanded"
Value="{Binding Path=IsExpanded,
RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type TreeViewItem},
AncestorLevel=2}}" />
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
What's missing here?
Thanks in advance.
A: Both work for me. If you tested it with static TreeViewItems make sure to apply the style via resources, the ItemContainerStyle is only relevant for dynamically created containers. Also note that user-interaction may set a local value, overriding those styles.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Removing last image via jQuery I would like to add an image at the end of each "booklist" within the "genre" div, but remove it for the last "booklist" within each genre. The following code is it adding just fine, but I'm messing something up when it comes to the removal. It's only removing the last image from the last .booklist on the page.
This is my HTML:
<div class="genre">
<div class="booklist">
<!-- stuff -->
</div><!-- .booklist -->
<div class="booklist">
<!-- stuff -->
</div><!-- .booklist -->
</div><!-- .genre -->
<div class="genre">
<div class="booklist">
<!-- stuff -->
</div><!-- .booklist -->
<div class="booklist">
<!-- stuff -->
</div><!-- .booklist -->
</div><!-- .genre -->
And this is my jQuery:
// ADD HEART DIVIDER BETWEEN SERIES ON BOOK PAGE
$(".genre .booklist").append("<img class='hr' src='"+my_home_object.my_stylesheet_path+"/images/heart-hr.png' />");
$(".genre .booklist:last img:last").remove();
Thank you for your help!
A: Try this to remove the last imgs in the last divs with class "booklist" in each "genre":
$(".genre .booklist:last-child > img:last-child").remove();
:last only selects one element, so use :last-child.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iPhone UILocalNotification load specific view I have my local notification working, but when I click View to come back to the app, in the app delegate I am trying to load a specific view, but it wont take. Is this possible or not? It always just comes back to the last view viewed.
A: When you tap "View" on the notification, it takes you back to your application, and your application shows whatever it was showing before (if it was backgrounded) or is launched.
If you need to show a particular UI in response to the notification, consider implementing the <UIApplicationDelegate> method -[<UIApplicationDelegate> application:didReceiveLocalNotification:]. In that method you can inspect the notification and transition to the appropriate interface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: multiple vars via url question I have a method
function checkin($var1){
$newVar1 = $var1;
....
...
}
I am calling it via Restful and I am passing it like this
$url = 'http://mydomain.com/controller/checkin/'.$var1;
Now i want to pass two variables but I am not sure how would it pick the second one
I guess I can do this
$url = 'http://mydomain.com/controller/checkin/'.$var1.'/'.$var2;
not sure what would I do on receiving end to make sure it knows what var to use where.
thanks
A: On the other end, you have to change your action method signature to
function checkin($var1, $var2){
// (...)
}
Another option is using Cake's named parameters. That would require a change in both the url and the action:
URL
$url = 'http://mydomain.com/controller/checkin/var1:'.$var1.'/var2:'.$var2;
Action method
function checkin(){
$var1 = $this->params['named']['var1'];
$var2 = $this->params['named']['var2'];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to establish a secure page transfer using a form? I have index.php and I have a login form:
<form method=post action="login.php" id="login">
<input type="text" size="16" maxlength="30" name="login" id="login_user" />
<input type="password" name="pass" id="login_pass"/>
<input name="msubmit" type="submit" value="Login" />
</form>
How can I make sure that the form gets processed through a secure line?
Do I have to add https://?
<form method=post action="https://test.com/login.php" id="login"
Any ideas?
Thanks.
A: Yes, the best way is to specify https:
<form method="post" action="https://domain.com/login.php" id="login">
<input type="text" size="16" maxlength="30" name="login" id="login_user" />
<input type="password" name="pass" id="login_pass" />
<input name="msubmit" type="submit" value="Login" />
</form>
Even if index.php was served through a secure channel, it is good practice to explicitly specify https on the post action because this is the request which sends sensitive data over the wire. But it is also recommended to have index.php served through https only.
A: Use https protocol. Also treat all the parameters as tainted - and get the PHP script to process them in a responsible fashion.
*I.e. parse (regular expressions) them and escape them if necessary when using a database/command line *
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Only the text in a ListBox item is selectable, the space outside of the text is not selectable I have a WPF ListBox whose items are TextBlocks. When I click on the text the SelectionChanged handler is called as expected. However, if I click inside the item, but not directly over the text the handler is not called. This is more apparent when the text items are of widely varying lengths. If I have two items:
foo
exclamation
The "foo" item has a lot of space to the right which doesn't respond to the click
<DataTemplate x:Key="NameTemplate">
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
...
<ListBox SelectionChanged="ListItemSelected" ItemTemplate="{StaticResource NameTemplate}"/>
A: I found that the following works, but it seems rather verbose...
<ListBox SelectionChanged="ListItemSelected" ItemTemplate="{StaticResource NameTemplate}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
Any ideas on how to do this more concisely? Or a way to put this in the ItemTemplate? I couldn't find a way to do the same in the template.
The orig without that was just:
<ListBox SelectionChanged="ListItemSelected" ItemTemplate="{StaticResource NameTemplate}"/>
A: Try. You can take away the background color but that will show you how big the TextBlock is.
Background="Beige" HorizontalAlignment="Stretch"
A: Are you sure the extra white space you are clickin on is "inside" your ListBox. Are you sure your ListBox is spanned across that much width?
Coz it doesnt seem to happen in my case.... (following ListBox is a child of a Window)
<Window x:Class="WpfApplicationPathToImage.Window4"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window4" Height="100" Width="100">
<ListBox SelectionChanged="ListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Text}"/>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsSource>
<x:Array Type="{x:Type TextBlock}">
<TextBlock Text="Text1"/>
<TextBlock Text="Text2"/>
<TextBlock Text="Text3"/>
<TextBlock Text="Text4"/>
<TextBlock Text="Text5"/>
<TextBlock Text="Text6"/>
</x:Array>
</ListBox.ItemsSource>
</ListBox>
</Window>
My ListBox_SelectionChanged is correctly called even if I click the white space outside the item level TextBlock boundaries (provided that I am actually clicking somewhere inside the ListBox).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Open URL Into a View(MVC 3) Hi I have a problem with my Application I am using the MVC 3 with C# and VS 2010.
I have a old desktop application where in one form I added a control browser_Navigated for show one page where the user could add the credentials of yahoo for use one API.
Now my problem is that I don't know a lot of MVC3 then I am not sure how I can open one URL into a div
I try to use Ajax.ActionLink
public ActionResult GetAuthorizationLink()
{
string s = "$('#divResultText').load('http:\\google.com')";
return JavaScript(s);
}
I would like comment that where I will show the information is a pop up then I think that I can't open a popup inside another popup.
Thanks for any help, for obtain some idea for fix this problem
A: You could use an <iframe> to achieve that, especially if you are trying to load some external domain:
<iframe id="result"></iframe>
<a href="#" id="load">Load data</a>
and then:
$(function() {
$('#load').click(function() {
$('#result').attr('src', 'http://www.google.com');
return false;
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: trying to curl get image, but i get weird results this is my curl function:
function curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'picturecookies.txt');
curl_setopt($ch, CURLOPT_REFERER, "http://www.google.com/");
curl_setopt($ch, CURLOPT_URL, $url);
$return = curl_exec($ch);
return $return;
}
an example image im trying to get:
http://static.fjcdn.com/large/pictures/39/29/3929d8_2637027.jpg
when i try getting the image with curl, i only get a file with random filesizes each time.
heres a list of bytes returned 6 times in a row;
12 654
12 627
12 632
12 632
12 583
12 627
the example image is 655kB
what am i doing wrong here?
EDIT:
I found why :>
The images are hotlink protected.
It was simply solved by changing the referer to the url the image was presented on.
A: You are probably getting redirecteed to the funnyjunk index page without noticing ;-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: mp3 uploaded to Facebook isn't showing in Facebook app on iPhone or Android I'm developing an app that allows the user to upload an mp3 file to a facebook friend's wall. It's all working well. If I look at the friend's profile page in facebook using IE or Safari, I can see the expected text and the play icon for the mp3 is there. I can click the play button and hear the audio. But, if I view the friend's profile through the facebook iPhone or Android app, the text appears but the mp3 isn't there.
I've searched high and low for a solution to this and am now stumped! Any help or guidance would be greatly appreciated.
dialog.attachment = [NSString stringWithFormat:@"{\"name\":\"blah:\",\"caption\":\"%@\",\"description\":\"link text\",\"media\":[{\"type\":\"mp3\",\"src\":\"http://www.blah.com/audio.mp3\",\"title\":\"song name\",\"artist\":\"singer\",\"href\":\"http://www.blah.com/\"}]}", friendsTableView.chosenName, @" "];
A: Turned out the problem was down to facebook itself rather than my code. My uploaded files are now showing and playing as expected.
A: Worth noting that for the last day or so, the embedded mp3 audio player in facebook is broken again so uploaded MP3 files are not playing correctly. This has been logged with fb: http://developers.facebook.com/bugs/163200820438523
It's a mis-leading problem as it's easy to think the bug is in your own code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sort HashTable according to values(numeric) preferably descending order and maintain the key-value I have the following key-value pairs in my HashTable.
KEY : VALUES
12345:45;
23456:23;
23445:34;
12367:101;
Output should be:
12367:101;
12345:45;
23445:34;
23456:23;
i.e. the output is in the descending order of the values.
ht_sort is my Hash table containing the key-value pairs.
//get the values from the hashtable as array objects.
Object[] arytf= ht_sort.values().toArray();
//Sort the array objects.
Arrays.sort(arytf);
But the problem is that I am unable to link back these sorted values to the hash to get the keys.
I am not exactly sure how to go about doing this, I have checked the previous threads but couldnot make anything out of them. Looking for help on this.
Thanks.
A: You could sort the entries in the hash table instead, with a custom implementation of Comparator<Map.Entry<...>> which just compared the values. Then you'd have a sorted array of entries, and you can just iterate over them picking out both keys and values as you go.
EDIT: As noted, the Map.Entry values are somewhat transient - so you probably want to create a pair to collect the two. (If you're dealing with non-generic types, you could always create an Object[2] to store the key in index 0 and the value in index 1...) Copy the entries as you iterate and then sort the resulting array.
A: Once your array is sorted, iterate through it and call _yourHash.get(arytf[n])
A: EDIT:
Duplicated values allowance solution:
List<Map.Entry<Integer, Integer>> sortMapValues2(Map<Integer, Integer> map){
//Sort Map.Entry by value
List<Map.Entry<Integer, Integer>> result = new ArrayList(map.entrySet());
Collections.sort(result, new Comparator<Map.Entry<Integer, Integer>>(){
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
return o2.getValue() - o1.getValue();
}});
return result;
}
You could get lots of articles by google "java collections framework".
A: If you just want to store sorted key/value pairs, you can take a look at LinkedHashMap:
http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html
My solution would be to sort an Entry array (for example, using a custom Comparator) and then insert them in proper order into a LinkedHashMap.
A: http://www.xinotes.org/notes/note/306/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it possible to change the UI at runtime and save changes in android application? It is possible to bind android UI dynamically at run-time and keep the changes saved to be visible in the next time I have run the application on the device !?
A: You can change the UI diagrammatically. Save the chances (there is no standar way) to Shared Preferences and then onCreate check is there are any changed need to be mabe (by looking at SharedPreferences) and perform them before you draw the UI
A: Not that I know of. Any changes made while your app is running should be saved/reloaded using the Activity life cycle functions as described in this question: Saving Android Activity state using Save Instance State
If there is something specific you are trying to do that won't work with that design pattern, please give more details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Binding WPF TextBlock to custom object in application In MainWindow.xaml I have
...
<TextBlock x:Name="tbCpu" Text="{Binding Path=activeTower.cpuTotal}" />
...
and in MainWindow.xaml.cs I have
public partial class MainWindow : Window
{
Tower activeTower
public MainWindow()
{
activeTower = Tower();
activeTower.cpuTotal = 500;
tbCpu.DataContext = this;
}
}
The code compiles and runs fine, without any errors. However, tbCpu stays empty. Tower is a custom class that has a property cpuTotal that returns a double, but I have tried other properties in the same class that return a string and it still doesn't work. What am I doing wrong here?
A: activeTower needs to be a public property for the binding to work:
public Tower activeTower{get;set;}
If you want changes of activeTower to be reflected in the View then you need to implement the INotifyPropertyChanged interface in your class
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can't get access token for a facebook page for an application that has all the right permissions SO community,
I am stuck in my attempt to have an application post automatically to my Facebook page.
These are the steps I took:
A) I authorized my application for all my facebook pages and granted permissions offline_access, publish_stream and manage_pages using
https://www.facebook.com/dialog/oauth?client_id=<app_id>&redirect_uri=<url>&scope=read_stream,publish_stream,manage_pages,offline_access,publish_actions
B) I requested the access token for the application with those permissions
https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=<app_id>&client_secret=<app_secure_key>&scope=manage_pages,offline_access,publish_stream
C) I now want to get the access token for the page to be able to do the final post using
https://graph.facebook.com/feed?<page_access_token>&message=test&id=<page_id>&method=post
however getting the page_access_token is where I am failing
This is the call I am trying
https://graph.facebook.com/<page_id>?fields=access_token&access_token=<app_access_token>
but instead of the page's access token I just get this back:
{
"id": "<page_id>"
}
Anyone has any insight what I am missing to get the .
/Thomas
A: We just managed to get this working in this past couple of days. Here's a summary. I apologize if I am detailing it beyond necessary but a couple of things you have done seem a bit wrong. To sum up your steps:
If you are doing step_A correct, which by the looks of the URL seems all right, then at the end of it you will receive a CODE (not the final access token). This will be a redirection using the redirect URL you sent in step A, so make sure your server is accepting a request for that redirectURL specified there. It will be in the form http://redirectURL?code=A_CODE_GENERATED_BY_SERVER so doing params[code] should get you the CODE.
Step_B might be where you are slightly off. You have send the CODE from step_A back to the server. I see that you have set a scope parameter again which is now not necessary (it was done in step_A). Step_B your request URL should look like
https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE
This time Facebook sends back a Response not using the redirectURL though. If you have the correct Step_B request URI you can paste it in your browser location bar and the response will render in your browser itself. You can use an HTTPBuilder (that's what I am using) and capture this Response body. It is of the form access_token=<really_big_string>&expires=<time_to_live>. Parse this response whichever way you prefer.
This is also an access_token (let's call it access_token_uno) and I suppose there is some amount of things you can do using this. I haven't tried it myself though and so we proceed to Step_C. I suppose you already know your PageID. You have to send back access_token_uno to Facebook in a URL of the form
https://graph.facebook.com/<PageID>?fields=access_token&access_token=<access_token_uno>
The response will be a JSON block of the form:
{
"access_token": <required_page_access_token>,
"id": <PageID>
}
Parse the JSON block and you are done.
The one minor detail to remember: The redirectURL has to remain the same in Step_A and Step_B else the thing fails. Also, I haven't yet tried with the offline_access permission but I don't think the steps above will change even if that is the case.
A: You need to get https://graph.facebook.com/{userid}/accounts for a user with administrative rights to the page. Inside that you should find the access_token for the page.
http://developers.facebook.com/docs/authentication/#app-login
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Bufferedimage bitmask operations - apply a color to an image using another image as a mask I have two BufferedImage objects, src and dest. Both are grayscale, src is 1bpc (B&W basically), and dest could really be any sort of color space/bpc/etc.
I need to be able to draw some color onto dest using src as a bitmask. Basically, if the pixel in src is black, then dest should be changed to the draw color. But if the pixel in src is white, the dest should be left alone.
If it matters, I am also applying an affine transform during the draw operation.
Graphics2D g = dest.createGraphics();
// do something here???
g.drawImage(src, transform, null);
g.dispose();
In a pure B&W world this would involve a simple | of the pixel values together - but it seems like there's probably a correct way to do this using image operations.
Gut instinct says that this is a matter of setting the Composite and some sort of alpha - but I'm at a total loss as to what values to use. I have very little experience with the more advanced aspects of graphics 2d - any pointers would be greatly appreciated.
A: I think that I've come up with an effective solution using this article
This is certainly efficient, although I'm not sure if follows best practices or not:
BufferedImage dest; // input
BufferedImage src; // input
...
byte[] r = new byte[]{(byte)0,(byte)255}; // 255=black, we could set it to some other gray component as desired
byte[] g = new byte[]{(byte)0,(byte)255};
byte[] b = new byte[]{(byte)0,(byte)255};
byte[] a = new byte[]{(byte)255,(byte)0};
IndexColorModel bitmaskColorModel = new IndexColorModel(1, 2, r, g, b, a);
BufferedImage masked = new BufferedImage(bitmaskColorModel, src.getRaster(), false, null);
Graphics2D g = dest.createGraphics();
g.drawImage(masked, transform, null);
g.dispose();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How ConcurrentDictionary is accessed and how to serialize it? I've never used the ConcurrentDictionary object before and have a couple questions about it:
*
*Am I correct that multiple threads can read from the dictionary at the same time, but if it's being written to, no other thread can access it?
*Can this object be serialized to disk?
Thanks.
A:
*
*Am I correct that multiple threads can read from the dictionary at the same time, but if it's being written to, no other thread can access it?
This is not observable, you can read and write from multiple threads and let the class worry about the synchronization.
*Can this object be serialized to disk?
Yes, it is marked with [Serializable]. And you can always extract the <K,V> pairs and use any Serializer you like.
A:
Am I correct that multiple threads can read from the dictionary at the same time, but if it's being written to, no other thread can access it?
No, you can safely read and write from multiple threads. Of course internally I suppose that there is some synchronization happening but the performance penalty should be small and you shouldn't be worried about it and do any additional synchronization.
Can this object be serialized to disk?
Depends on what serializer you use.
*
*JavaScriptSerializer: yes
*Json.NET: yes
*DataContractSerializer: yes
*BinaryFormatter: yes
*XmlSerializer: no (well, you could do some hacking to make it work but it will be a PITA => XmlSerializer is allergic to the IDictionary<TKey, TValue> interface)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Applications that use Node.js Does someone knows several apps that currently use Node.js?,
I'm trying to create a Node.js community with some friends at my campus but I need some good real life examples to show and attract more people.
A: A lot.
http://techcrunch.com/2010/09/01/nodejs-knockout/
https://github.com/joyent/node/wiki/Projects,-Applications,-and-Companies-Using-Node
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cross Browser check mobile devices Short of buying the full compliment of: iPad, iPhone, android tablet and android phone(s) .... and the rest ... is there any reliable way to browser test some of these for how a website looks, particularly the ipad? I read somewhere, csstricks I think, that the ipad doesnt generally need any special treatment; is this the case.
A: There is a service that does this very thing:
http://crossbrowsertesting.com/
A: well This wont show you how the page is rendered. But it will let you determine how a page is downloaded when a certain device browses to it.
User Agent Switcher (Firefox Plugin)
You will need the user agent that you are trying to handle for. But this is how the servers tell what device they are dealing with. This way you can customize your code to handle for certain scenarios and verify that the html is correct on the client end.
Again this will likely not display how the browser would see it. But will give you the knowledge that it did what you intended it to do. (Custom CSS or custom layout or whatever else)
As for testing on the devices, since they may all have their own little quirks the closest thing you can hope for is finding emulators for the devices you want to find out about. (and hope they accurately emulate the quirks)
A: The iPad and stock Android browsers are fairly smart about displaying content. It's not a huge deal if you can't get your hands on a device to test how it looks.
If you are trying to test a site that's specifically targets mobile devices (if it uses touch events, for example), you should probably invest in or borrow a device.
An emulator is better than nothing, however. Try the following:
*
*Android's SDK includes a browser
*Opera Mobile has an emulator
*Mobile Firefox also has an emulator
*To test in Opera Mini either install it on a Android virtual machine or use MicroEmulator and download the .jad file (this will also work for UCWeb).
A: you can try http://www.testize.com service that provides cross-devices testing for about 10 devices, iPhone 3, 4, 5; iPads and Android
They also provide you a report with discovered site issues
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Horizontal columns chart (bars chart) using Chart Tools API Library for GWT I need to draw an horizontal bar chart using GWT. The ColumnChart class from the Chart Tools API Library for GWT supports only vertical bars. Any suggestions?
A: BarChart is the horizontal counterpart of ColumnChart. Their configurations are nearly identical.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is the DotNetOpenAuth in-memory store sufficient for web farms with a load balancer that has sticky sessions? I am implementing DoNetOpenAuth as an Relying Party in an web farm environment. Is the default in-memory store sufficient for environments with sticky sessions? I have read a few post alluding that it does work here and here, but I don't have enough knowledge of load balancing and OpenID to know for sure.
I understand it may not be ideal and that I should either run in "dumb" mode or implement my own store.
Thanks,
A: No, sticky sessions are not enough to permit the use of the in-memory store, because the store has data that must be available to multiple client parties (nonces, most particularly, in order to mitigate replay attacks).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting 405 Method Not Allowed on a GET Clicking the following link in my webapp produces a 405:
<a href="/unsubscribe/confirm?emailUid=<%= ViewData["emailUid"] %>&hash=<%= ViewData["hash"] %>" class="button">Yes, unsubscribe me.</a>
Here's the Confirm Action being called from the Unsubscribe Controller:
[HttpGet]
public ActionResult Confirm( string emailUid, string hash)
{
using ( UnsubscribeClient client = new UnsubscribeClient() )
{
UnsubscribeResponse response = client.Unsubscribe( emailUid, hash );
return View( response );
}
}
Simple stuff. It works when I F5 it, but when I host it in IIS (both 7.5 and 6), I get the error.
I'm pretty lost with this. I've scoured the net, but can't seem to find any reason as to why this is happening.
A:
<%= Html.ActionLink(
"Yes, unsubscribe me.",
"Confirm",
"Unsubscribe",
new { emailUid = ViewData["emailUid"], hash = ViewData["hash"] },
new { @class = "button" }
) %>
Also ViewData?! Please, remove this as well in favor of strongly typed views and view models. Everytime I see someone using ViewData I feel obliged to say that.
A: What is the actual rendered HTML href in the anchor? Is the generated URI valid?
Does changing it to this work:
<%= Html.ActionLink("Yes, unsubscribe me.", "Confirm", "Unsubscribe", new { emailUid= ViewData["emailUid"], hash = ViewData["hash"]})%>
A: Make sure the outputted URL is valid and any invalid character is escaped properly, for exaple make sure & are escaped as &
A: If there is a period in your emailUid or hash, it needs to be encoded. That's not the only problematic character, but I suspect it is the case here. Use HttpUtility.UrlEncode on these values before concatenating them into the URL.
Why the 405? Likely because there is no script mappings in IIS6 for the presumed "file extension". It's not a file extension at all, but without encoding the period in the URL it doesn't know any better.
A: Well, I found my issue. It turns out to be a problem with my IIS configuration. In IIS 6, I didn't allow scripts to be executed in the directory, so my .svc would never run for my service host. Once I changed that setting, I no longer received the 405 error...
Many thanks to the other answers. I'll be sure to use the Html helper.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Understanding Chrome's basic call stack structure The following code reveals some of Chrome's internal call stack workings:
(function revealCallStack() {
var fn = arguments.callee;
console.log('**Bottom of stack**:\n\n', fn);
while (fn = fn.caller) console.log('**Next on stack**:\n\n', fn);
})();
Please see http://jsfiddle.net/fW5Ag/. The piece of code reveals four functions on the stack. The first two are somewhat predictable. What about the last two (pasted below)?
function (event){
if (custom.condition.call(this, event, type)) return fn.call(this, event);
return true;
}
and
function (event){
event = new DOMEvent(event, self.getWindow());
if (condition.call(self, event) === false) event.stop();
}
What exactly is happening here?
A: These are the Mootools and jsFiddle functions for onload execution of Javascript, not browser functions.
Try noWrap and no library: http://jsfiddle.net/fW5Ag/1/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery Dropdown Scrollbar? So I'm trying to change the scrollbar when I click on a link. First, let me show you my current code.
jQuery:
$(document).ready(function() {
$("div.panel_button").click(function(){
$("div#panel").animate({
height: "100%"
})
});
$("div#hide_button").click(function(){
$("div#panel").animate({
height: "0px"
}, "fast");
});
});
Implementation:
<div id="panel">
<div class="panel_button1" id="hide_button" style="display: visible;"><a href="#">X</a></div>
<div id="panel_contents">
There was a really long bit of text here. This will eventually overflow.
</div>
</div></div>
Activation Link:
<div class="panel_button" style="display: visible;"><a href="#panel">ABOUT<br>THE<br>BLOGGER</a></div>
CSS:
#panel {
margin-top: 0px;
margin-left: 48%;
width: 48%;
z-index: 25;
text-align: center;
background-color: #efefef;
position: relative;
height: 0px;
z-index: 10;
overflow: hidden;
text-align: left;
position: fixed; } /* drop down color */
#panel_contents {
font: normal 80%/190% arial;
line-height: 190%;
padding: 5%;
height: 100%;
width: 80%;
padding-top: 1% !important;
position: absolute;
padding-left: 12% !important;
z-index: -1; } /* drop down color */
.panel_button1 a { /* About the Blogger */
text-decoration: none;
color: #888;
font-size: 240%;
font-family: arial;
padding: 1%;
-webkit-transition: all .9s ease;
-moz-transition: all .9s ease;
transition: all .9s ease; } /* for the exit button */
.panel_button1 a:hover {
color: #F58932; } /* for the exit button */
.panel_button {
list-style-type: none;
list-style-image: none;
list-style: none;
width: 50%;
position: relative;
top: -160px; } /* for the nav styling */
.panel_button a {
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
transition: all 1s ease;
background: #F5A564;
color: #F5CBAF;
display: block;
font-size: 255%;
height: 160px;
text-decoration: none; }
/* nav styling */
.panel_button a:hover {
background: #808080;
color: #FFFFFF; }
So when I click on "About the Blogger" I want to write a bit more so that the text will eventually overflow, but I can't seem to think of a way to do that. IF possible, I'd like to change the main content that the default scrollbar scrolls to the "About the Blogger" content. If that's not possible, I was thinking of an internal scrollbar.
I can't think of a way to execute either.
If you wish to see this, go to Niu-Niu.org.
Please keep in mind that I'm a complete newb in jQuery. I know my way around CSS well.
Thank you for looking!
A: The panel_contents is absolute, not static. This looks like a CSS problem and not a jQuery problem. Unless you want to use jQuery to dynmically adjust the panel's height based on screen size. Why not use this css for panel instead?
position: fixed;
top: 0px;
right: 30px;
width: 400px;
height: 100%;
overflow: scroll;
Now panel is full height of window. If content is larger than panel it scrolls. I suppose you could still use position absolute with 100%, but you need to set its parent to relative so that it doesn't grow too big (which is your current problem, plus the fact that you don't have overflow scroll.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: what happends with the memory of the objects used in NSMutableDictionary when releasing the array? I'm curious what happens with the memory of the objects that I push with [array addObject:object] when I use [array release]
*
*does addObject copy the pointers?
*do I have to retain the objects ?
*do I have to make a for and release each object then the array?
A: When you call
[array addObject:object]
array retains object, thereby incrementing its retain count.
Later, when array is sent the message dealloc, it calls release on object.
To avoid memory leaks, you may have to release object after you add it to the array, e.g.
NSObject *object = [[NSObject] alloc] init];
[array addObject:object];
[object release];
Make sure you review the Memory Management Programming Guide to be certain that you are not over or under releasing object.
A: addObject does a retain on that object you add. And when you release the array it automatically calls release on all objects it holds.
A: When you do [array addObject: object], the array is retaining the object that is inserted into the array. To avoid memory leaks, don't forget to release the original object that was inserted, or else the object being inserted into the array will have a retain count of 2 instead of 1:
SomeClassObject *obj = [[SomeClassObject alloc] init];
[array addObject:obj];
[obj release];
Since the array owns the objects that are inside of the array (holds a pointer to that object and did a retain as explained previously), when you release the array, the array knows to release any objects that are inside of it. The work is done for you!
A: NSArrays retain added objects, so you don't have to add extra retains yourself, and can just release the array when done.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mercurial - why doesn't diff work? I have just started to use mercurial (for windows). According to the tutorial http://hginit.com/01.html I made repository, etc. But diff command doesn't show any changes that I made in files. Do you have any ideas what is wrong?
Thanks in advance!
A: Basic steps are as follows:
hg init . ---- This make the current directory as blank hg repository
echo "XYZ" > test.txt --- This creates a new file which is not added to version control yet.
hg add test.txt --- The file is added to repo for commit
hg commit test.txt -m "added file test.txt" --- Now you can commit the file
hg log ----- to see the log
hg diff test.txt ----- will show no diff as the latest file committed is same
echo "TTTT" >> test.txt ----- make some changes
hg diff test.txt -------- should show the difference of current file to latest in commit
hg commit test.txt -m "second commit" ----- now once you have committed, latest in repo and working directory is same
hg diff test.txt ------ this diff should again be blank
A: By default, if the command hg diff will show differences between the working directory, and its parent. As nye17 suggested, if you have committed some changes just prior to running hg diff then the working directory will be the same as its parent, and show no output. In these instances, you can see what changes were made in by running hg diff -c -1. This will run the hg diff command on the previous (-1) changeset.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Detecting if code is being run as a Chrome Extension I am working with some code that needs to be run as a page, and if it's being run as a Chrome Extension, I want to be able to do additional things. What I'm using is:
<script>
if (chrome && chrome.extension) {
// extension stuff
}
</script>
This seems like a good capability detection. Using user agent string causes me trouble because it's the same no matter the context (web page vs. extension).
Question: are there other more reliable techniques for detecting if a piece of code is running inside a Chrome extension?
Update: I'm wondering if there's something I can put into my manifest.json file that I can then read back. Note, that the extension I'm working on is not intended as a persistent thing that runs all the time, it's a content application that runs in a single window or browser tab and has no need to interact with other windows or tabs or anything else.
A: I had the need for something similar.
But I didn't need to care about sites attempting to trick the code.
const SCRIPT_TYPE = (() => {
if (chrome && chrome.extension && chrome.extension.getBackgroundPage && chrome.extension.getBackgroundPage() === window) {
return 'BACKGROUND';
} else if (chrome && chrome.extension && chrome.extension.getBackgroundPage && chrome.extension.getBackgroundPage() !== window) {
return 'POPUP';
} else if (!chrome || !chrome.runtime || !chrome.runtime.onMessage) {
return 'WEB';
} else {
return 'CONTENT';
}
})();
The above should detect the 4 scenarios
*
*javascript is run in a background page
*javascript is run in a popup page / iframe
*javascript is run in a context script
*javascript is run in a directly on a website
A: So many complicated answers here, while you can easily detect whether you're running in a Chrome extension by checking for existence and non-emptiness of chrome.runtime.id:
if (window.chrome && chrome.runtime && chrome.runtime.id) {
// Code running in a Chrome extension (content script, background page, etc.)
}
A: Pragmatically that's a good approach. Theoretically (not sure if this is relevant or not, e.g. may provide vulnerabilities) it can be spoofed very easily. I suppose it depends on your context how relevant that is.
Here's a slightly stronger idea:
if (chrome &&
chrome.windows &&
chrome.windows.get &&
typeof chrome.windows.get === 'function' &&
chrome.windows.get.toString() === 'function get() { [native code] }')
The idea is the same as yours, although it's slightly stronger, since AFAIK having an object be a function and having it's toString() value have that value is impossible since it's not valid syntax, so even trying to spoof that value wouldn't work unless you altered the native code (which requires a whole different level of hacker).
Don't offhand remember if checking things like this requires permissions or not, but the idea is clear I hope.
UPDATE
I just realised that the "native code" syntax idea can be fooled, by aliasing an existing function. E.g.
var FakeFn = Object.create;
FakeFn.toString(); // "function create() { [native code] }"
But that can be taken care of by careful selection of which function we use, since the name appears in the string. get is probably too common, but if we take an obscure function name (like captureVisibleTab of chrome.tabs.captureVisibleTab) that is implemented only in chrome extensions, it is still a very portable solution, because unlike the basic check where code can be fooled by other local user code, it is known in advance that the browsers don't implement any native functions with this name, so it's still safe in all browsers and with all user code.
UPDATE
As @Mathew pointed out, this idea is foolable (although seemingly only maliciously). I thought I could patch the problem by comparing to Function.prototype.toString but figured that even that can be fooled by aliasing the original toString method and creating a new one that for certain functions returns false strings and for others returns the original string.
In conclusion, my idea is slightly stronger than the original, in that it will rule out practically all chance of unintentional collision (slightly more than the OP's idea), but is certainly no defence against a malicious attack as I first thought it might be.
A: I know this is old, but just thought I'd offer an alternative. You can add another javascript file to the chrome extension, so it contains two .js files. manifest.json would have:
"js": ["additionalscript.js", "yourscript.js"]
The additionalscript.js could simply declare a variable var isextension = true. yourscript.js can check typeof isextension != 'undefined'.
But perhaps a more interesting example, it could declare
var adminpassword='letmein'
Now yourscript.js only has access to adminpassword when running in the extension.
(Of course you would not embed a password in a script file if the plugin were on a machine that could be compromised)
A: I noticed that in Chrome, the chrome object, that is property of the global window object, could not be deleted. If it is user-defined property delete operation is successful. So you could test in this way:
var isRunningInExtension = (!(delete window.chrome) && chrome.extension) ?
true : false;
UPDATE:
Line above does not really guarantee that code is running in chrome extension. Everyone can create an object called 'chrome' with an 'extension' property and then freeze/seal that object - doing this will be enough to pass the check and have an incorrect result that your code is running inside a chrome extension.
The ensure you are running your code in an extension, you have to test the global chrome object before any javascript to be run - that way you will have guarantee that no fake chrome object is created before testing.
One possible solution is to use an iframe - in my example below i use iframe's sandbox property to instruct the iframe not to execute any scripts(even scripts included with script tag) - in that way i can ensure no script will be able to modify the global window.chrome object.
(function() {
var isChromeExtension = (function () {
var contentWindow,
iframe = document.createElement("iframe"),
isChromeExtension;
// test for sandbox support. It is supported in most recent version of Chrome
if ("sandbox" in iframe) {
try {
iframe.sandbox = "allow-same-origin";
iframe.src=location.href;
iframe.style="display: none";
document.body.appendChild(iframe);
contentWindow = iframe.contentWindow;
isChromeExtension = !!(contentWindow.chrome && contentWindow.chrome.extension);
document.body.removeChild(iframe);
} catch(e) {}
}
return isChromeExtension;
}());
}());
result could be:
*
*true - if code is running inside an extension of Chrome
*false - if code is not running inside an extension of Chrome
*undefined - if browser does not support sandbox for iframes or some error happened during test
A: Chrome does not provide any direct API to check the running status of the application that is it running in extension popup or in chrome page view. however, One indirect trick can work is we can match the extension body resolution that is equal or less than as specified in CSS (in this case, extension popup will be open) or greater than that (in this case, web page view will be open).
A: Credit to Chad Scira for the original answer mine is based of.
I grabbed Chad's answer and I compacted it to ES2021 standards. Removed a lot of repeated content required for previous versions too.
const runningAt = (() => {
let getBackgroundPage = chrome?.extension?.getBackgroundPage;
if (getBackgroundPage){
return getBackgroundPage() === window ? 'BACKGROUND' : 'POPUP';
}
return chrome?.runtime?.onMessage ? 'CONTENT' : 'WEB';
})();
The above should detect the 4 scenarios
*
*javascript is run in a background page
*javascript is run in a popup page / iframe
*javascript is run in a context script
*javascript is run in a directly on a website
A: To detect chrome apps and extensions use:
chrome.app.getDetails()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Convert string to hebrew I have the following string:
המרכז ×”×‘×™× ×ª×—×•×ž×™ הרצליה
How can I convert it to Hebrew using PHP? I try ut8_decode and utf8_encode and it doesn't work.
A: You have a UTF-8 byte sequence that you are displaying using the Windows code page 1252 (Western European) encoding instead of UTF-8.
Ensure that your output page is served as UTF-8 using a Content-Type: text/html;charset=utf-8 header and/or <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> tag, and the sequence should be interpreted correct by the browser as UTF-8, giving ‘המרכז הבינתחומי הרצליה’.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP + SQL Query: Selecting Enum Values I'm running into a weird situation with a PHP execution of a SQL query that maybe someone can shed a little light on:
I have a query that says:
"SELECT COLUMN_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = $table
AND COLUMN_NAME = $column"
The query should return a string: enum('A','B'[,'C'...]) when executed (as it does when running the query from the command line. $table and $column are passed to the function making the query, and in my test case are proper – both exist as a table and column respectively. In this case, let's set $table = 'profile' and $column = 'gender', to which the above SQL statement is returning the following error:
Unknown column 'profile' in 'where clause' in /registry/mysqldb.class.php on line 31
Line 31 is a caching function to cache queries until required, or triggering an error when the query fails. This works fine in every other case. I'm connected to the correct DB when the request is made.
My question is this: Why is 'profile' being interpreted as a column and causing the error?
A: Maybe it's because you are missing quotes around the variables. Try:
"SELECT COLUMN_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '$table'
AND COLUMN_NAME = '$column'"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unexpected Behavior of Extend with a list in Python I am trying to understand how extend works in Python and it is not quite doing what I would expect. For instance:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6].extend(a)
>>> b
>>>
But I would have expected:
[4, 5, 6, 1, 2, 3]
Why is that returning a None instead of extending the list?
A: Others have pointed out many list methods, particularly those that mutate the list, return None rather than a reference to the list. The reason they do this is so that you don't get confused about whether a copy of the list is made. If you could write a = b.extend([4, 5, 6]) then is a a reference to the same list as b? Was b modified by the statement? By returning None instead of the mutated list, such a statement is made useless, you figure out quickly that a doesn't have in it what you thought it did, and you learn to just write b.extend(...) instead. Thus the lack of clarity is removed.
A: The extend() method appends to the existing array and returns None. In your case, you are creating an array — [4, 5, 6] — on the fly, extending it and then discarding it. The variable b ends up with the return value of None.
A: extend extends its operand, but doesn't return a value. If you had done:
b = [4, 5, 6]
b.extend(a)
Then you would get the expected result.
A: I had this problem and while the other answers provide correct explanations, the solution/workaround I liked isn't here. Using the addition operator will concatenate lists together and return the result. In my case I was bookkeeping color as a 3-digit list and opacity as a float, but the library needed color as a 4 digit list with opacity as the 4th digit. I didn't want to name a throwaway variable, so this syntax suited my needs:
color = [1, 1, 0]
opacity = 0.75
plot.setColor(color + [opacity])
This creates a new list for opacity on the fly and a new list after the concatenation, but that's fine for my purposes. I just wanted compact syntax for extending a list with a float and returning the resulting list without affecting the original list or float.
A: list methods operate in-place for the most part, and return None.
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> b.extend(a)
>>> b
[4, 5, 6, 1, 2, 3]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: Which element do I change so as to add a border image between posts? The template I am using for my site (under development) is identical to this one.
I'd like to add a border image between posts (In this case between "Let You Know Music video" and "Land of Hope") but not after the last post.
Which element do I edit (css source) to make this happen?
Do I edit the containsArticles class? dt containsArticles?
I've tried adding a background: url(/path/to/border-image.gif) no-repeat center bottom; to either element and cannot make it work. Ideas or suggestions?
A: There's a rule already in there actually:
line: 1449
.containsArticles dd, #containsTwoosers, #screen > header, #screen > footer > nav > ul, .archives #content fieldset, .index #content .G6, .single #comments form {
background-image: url(data:image/png;base64,R0lGODlhSAABAIAAAP///2ZmZiH5BAEHAAAALAAAAABIAAEAAAINDG54kLwNn1TU1XhXAQA7);
}
The reason why it's not on the last child is because of this rule:
line: 682
.containsArticles dd:last-child {
background: transparent !important;
margin-bottom: 0;
padding-bottom: 0;
}
The rule preventing this default behavior is
line:1418
.index .containsArticles dd {
background: transparent !important;
margin-bottom: 1.5em;
padding-bottom: 0;
}
all in style.css
completely removing that last rule will get you what you need.
A: You should use the .index .containsArticles dd selector, which already exists on the demo site you linked.
Also if your using a background image, make sure you give that same element some bottom padding for the background image to appear in.
.index .containsArticles dd {
background: url("path/to/image.png") no-repeat center bottom transparent;
margin-bottom: 0;
padding-bottom: 25px;
}
A: .containsArticles>dd{yourStyleHere}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery: how to get file name from fileupload control? What I want to implement is by clicking "attach a file", a file browser will be open to let user choose a file. I use jQuery to set onclick function of "attach a file", and set the opacity of a fileuload control to be 0. So it is like display:none. But I don't know how to get the file that user selected from fileupload control. Even don't know what event should be capture in the process. I want to save the file in a hidden div, so I can use it in backend code. Any method?
UPDATE: OK, I think it's better to describe my question more clearly. That is, how to get selected filename when you click open button in browser window? If in backend it is as easy as
string fileName=FileUpload1.PostedFile.FileName;
I want to get the fileName in client using jQuery. Since I will use same fileUpload control to select multiple files, I need to add the filename into a hidden div when the browser window closed. Any idea?
A: The file upload control renders as an INPUT of type file. If you retrieve its Value after change, it will hold the name of the file.
A: As I said in my comments if you have the ID you will have the value.
Place a file upload control on your form, then place an asp.net button or any button for that matter.
Then its a matter of:
$(document).ready(function () {
$("#btnUpload").click(function () {
var FileUpload = $("#MyFileUploadControl").val();
... }
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Improvements for a Map merge function I'm writing a function to merge two Map's together. This is what I have so far:
def merge[K, V1, V2, V3](left: Map[K, V1], right: Map[K, V2])
(fn: (Option[V1], Option[V2]) => V3): Map[K, V3] = {
val r = (left.keySet ++ right.keySet) map {
key =>
(key -> fn(left.get(key), right.get(key)))
}
r.toMap
}
The function itself works. You use the function as so:
val m1 = Map(1 -> "one", 3 -> "three", 5 -> "five")
val m2 = Map(1 -> "I", 5 -> "V", 10 -> "X")
merge(m1, m2) { (_, _) }
// returns:
// Map(1 -> (Some(one),Some(I)),
// 3 -> (Some(three),None),
// 5 -> (Some(five),Some(V)),
// 10 -> (None,Some(X)))
I have two questions:
*
*I'm worried about the performance computational complexity of the .get and .toMap calls. Can anyone improve the implementation?
*I'd like the default function to make a pair of the values ({ (_, _) }). I can't quite get the syntax to do so properly.
Edit:
While I originally said performance, I meant computational complexity. My guess is that this function performs in O(n•ln(n)) time. Looks like my function performs roughly in O(n). Can it be done in O(ln(n))?
A: For the default function literal use:
(fn: (Option[V1], Option[V2]) => V3 =
(x: Option[V1], y: Option[V2]) => Tuple2(x,y))
You'll have to use merge like this: merge(m1,m2)()
I would say don't be worried about performance until you perform some measurements on actual data.
Edit: about performance, by providing a view instead of constructing a map you can get quick "construction" at the expense of lookup - assuming we are dealing with immutable maps. So depending on actual data and use case, you can get better performance for certain operations, but it has a trade-off.
class MergedView[K, V1, V2, V3](
left: Map[K, V1], right: Map[K, V2]
)(fn: (Option[V1], Option[V2]) => V3 = (x: Option[V1], y: Option[V2]) => Tuple2(x,y)
) extends collection.DefaultMap[K, V3] {
def get(key: K): Option[V3] = (left.get(key), right.get(key)) match {
case (None, None) => None
case t => Some(fn(t._1, t._2))
}
lazy val tuples = (left.keys ++ right.keys).map(key => key -> get(key).get)
def iterator: Iterator[(K, V3)] = tuples.iterator
}
val r1 = new MergedView(m1, m2)() // use parens here for second param list.
A: You shouldn't worry about get -- yes, it will create a wrapper object, but doing anything else will be awkward enough that you shouldn't try unless a profiler shows that to be a problem.
As for toMap, yes, that might well slow you down. You may try using breakOut.
Regarding complexity of get and toMap, lookup and add are effective constant time for immutable HashMap, which is the default Map. See Performance Characteristics of Scala Collections.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Function composition failure I'm working on the solution to this koan. I'm stumped as to why my solution does not work, but using the definition of comp does work. When I look at the definition of comp, I see:
(defn comp
"Takes a set of functions and returns a fn that is the composition
of those fns. The returned fn takes a variable number of args,
applies the rightmost of fns to the args, the next
fn (right-to-left) to the result, etc."
{:added "1.0"}
([f] f)
([f g]
(fn
([] (f (g)))
([x] (f (g x)))
([x y] (f (g x y)))
([x y z] (f (g x y z)))
([x y z & args] (f (apply g x y z args)))))
([f g h]
(fn
([] (f (g (h))))
([x] (f (g (h x))))
([x y] (f (g (h x y))))
([x y z] (f (g (h x y z))))
([x y z & args] (f (g (apply h x y z args))))))
([f1 f2 f3 & fs]
(let [fs (reverse (list* f1 f2 f3 fs))]
(fn [& args]
(loop [ret (apply (first fs) args) fs (next fs)]
(if fs
(recur ((first fs) ret) (next fs))
ret))))))
Whereas my solution is very similar:
(defn mycomp
([f] f)
([f1 f2]
(fn
([] (f1 (f2)))
([a] (f1 (f2 a)))
([a & more] (f1 (apply f2 a more)))
)
)
([f1 f2 & fs]
(let [fxns (reverse (list f1 f2 fs))]
(fn [& args]
(loop [ret (apply (first fxns) args) fxns (next fxns)]
(if fxns
(recur ((first fxns) ret) (next fxns))
ret))))))
The big difference between the two, from what I can tell, is that the first definition composes three or more functions, whereas the second definition composes two or more functions.
Please point out what is incorrect about my definition.
A: (list f1 f2 fs) looks a likely suspect - the first two are functions, and the last is a list of functions, so you're creating a list containing multiple object types and then treating them uniformly. You could fix that by using list* instead.
But as a broader point: holy jeez, don't try to do "two or more" functions, just do zero or more! No special cases means much less code; clojure.core only has a bunch of unrolled cases for speed. If your skeleton is (fn [& fs] (fn [& args] ...)), your life is much easier.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Producing a read-only copy of a class, howto Given the following UML representation, how can i get an instance of a BullDog , that only has getter methods exposed?
*
*Instance of the BullDog should not have any of the setter methods available.
*Instance of the BullDog should only have getter methods (3 of them) available
Basically the question is .. what do i cast new BullDog to?
A: Since HealthyPet and Pet are unrelated there's nothing you can cast to that will give you all 3 getter methods(getMetabolism(),getName() and getAge()). Now if HealthyPet extended Pet (and I'm really not sure why it doesn't) you'd be in business. Because then you could cast to HealthyPet, return that interface, and a caller would only see the 3 getter methods (of course I'm talking without fancy introspection which should allow them to discover everything).
A: You need HealthyPet to extend Pet. Then you cast your BullDog instance to HealthyPet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: do PHPUnit tests need to be inside a "/test" directory? when using PHPUnit, is it required for tests to be inside of a /tests directory? How does PHPUnit know that a test is a "test"? Does it parse the file and look for method names, or use some sort of naming convention of files?
A:
it required for tests to be inside of a /tests directory?
No.
How does PHPUnit know that a test is a "test"?
Via reflection (and by the user specifying a directory to look into).
A:
Does it parse the file and look for method names, or use some sort of naming convention of files?
*
*If first checks if the passed argument is a file so you could call phpunit myTestStuff.php
*Since it's not in your case It recursively scans the directory by calling File_Iterator and adding all files that end in "Test.php" and ".phpt" to your testsuite.
*It then goes through all those files and adds all the classes that extend from PHPUnit_Framework_Test
*Then the tests are run
So in short:
Filename needs to end in Test.php, class needs to extends from PHPUnit_Framework_TestCase (some point down the inheritance tree).
It is good practice to seperate your test code from your production code though. Usually it mirrors the folder structure. But there is nothing stopping you from doing it differently. Just consider that it's easier to generate statistics (metrics) for your production code.
Maybe you want to have some automatically checked coding rules for your production code and others for your tests.
You want to generate code coverage for your code and have it include all the production code but not all the tests. (PHPUnit will not show your test classes in the coverage anyways but base and helper classes)
A: Convention is to name the test classes and files by appending Test to those of the classes you're testing. For example My_Cool_User in My/Cool/User.php would be tested with My_Cool_UserTest in My/Cool/UserTest.php.
I prefer to separate the tests in their own directory, but this isn't required. By using a naming convention you can tell PHPUnit how to find all the tests mixed in with your regular code. By default PHPUnit follows the above, so if you point it to a folder called myproject it will look for all files ending in Test.php within it.
A: Go into your settings and directories, and select and verify your test and source locations are added.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: One time salts and server password comparison I've read that one of the more secure ways to authenticate a user is to use one time salts when hashing the password. What I don't get is:
If the client generates a new salt every session, won't the resulting salt+password hash be different every session? If so, how will the server be able to compare the sent password with it's stored password? Is there a way for servers to compare different hashes and still be able to discern that the same password was used?
(Disclaimer: I'm not trying to reinvent the wheel/write a login protocol (I know, I know: use SSL/TLS). I'm just curious as to the high level functioning of login protocols)
A: you only generate a new salt when the user sets the password initially. Then you save the salt along with the password hash.
A: You only need to generate the salt only once and may every time the password been changed.
The client needs not to store the salt anywhere or even been aware of that. The salt will be stored by the server - along with the hash.
Its recommended that you store the hash and the salt in two different databases..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Crashes normally, but not with GDB? My program crashes with a segmentation fault when ran normally. So I run it with gdb, but it won't crash when I do that. Does anyone know why this might occur? I know that Valgrind's faq mentions this (not crashing under valgrind), but I couldn't really find anything about this related to gdb in google. If someone could tell me why, or recommend something to look for when this happens I would be very grateful.
A: Sounds like a Heisenbug you have there :-)
If the platform you're working with is able to produce core files it should be possible to use the core file and gdb to pinpoint the location where the program crashes - short explanation can be found here.
Let it crash a couple of times though, when the crash is caused by stack smashing or variable overwriting the bug may seem to "walk around".
A: Try attaching to the running process within gdb, continuing, and then reproducing the crash. In other words, don't start the program within gdb; instead, start the program normally and then attach <pid>.
Sometimes when stepping through lines individually, a race condition that causes the program to crash will not manifest, as the race hazard has been eliminated or made exceedingly improbable by the "lengthy" pauses between steps.
A: Well I tracked it down to a pthread_detach call. I was doing pthread_detach(&thethread). I just took away the reference and changed it to pthread_detach(thethread) and it worked fine. I'm not positive, but maybe it was a double free by detaching the reference then destroying it again when it went out of scope?
A: I've had this happen to me before (you're not alone), but I can't remember what I did to fix things (I think it was a double free).
My suggestion would be to set up your environment to create core dumps, then use GDB to investigate the core dump after the program crashes. In bash, this is done with ulimit -c size, where size can be anything; I personally use 50000 for 25MB max size; the unit is in 512-byte increments.
You can use GDB to investigate a core dump by using gdb program core.
A: If bug depends on timing the gdb could prevent it from repeating.
A: Check for return value of pthread_detach call. According to your answer, you are probably passing invalid thread handle to pthread_detach.
A: I also had this happen to me some times.
My solution: clean & rebuild everything.
Not saying that this always solves all problems (and in the OP case the problem was something really wrong), but you can save yourself some trouble and time if you do this first when encountering such really weird "meta" bugs. At least in my experience, such things more often than not come from old object files that should have been rebuilt but were not. In both MinGW and regular GCC.
A: I just had a similar problem, in my case, it was connected to pointers in my linked list data structure. When I dynamically created a new list without initializing all the pointers inside the structure my program crashes outside GDB
Here are my original data structures:
typedef struct linked_list {
node *head;
node *tail;
} list;
typedef struct list_node {
char *string;
struct list_node *next;
} node;
When I created a new "instance" of a list specifying its head and tail the program crashed outside DGB:
list *createList(void) {
list *newList = (list *) malloc(sizeof(list));
if (newList == NULL) return;
return newList;
}
Everything started to work normally after I changed my createList function to this:
list *createList(void) {
list *newList = (list *) malloc(sizeof(list));
if (newList == NULL) return;
newList->head = (node *) 0;
newList->tail = (node *) 0;
return newList;
}
Hope it might help to someone in case of something similar to my example with non-initialized pointers.
A: I faced a similar issue, where a thread was killed randomly, and no coredump was created. When I attached gdb, the issue wouldn't reproduce.
To answer your question of why this is happening, I think this is timing issue, since gdb will collect some data related to thread execution it might slow down the process execution speed. If thread execution is slow issue isn't reproducing.
A: When you run your code with gdb, it gets moved around. Now the illegal address you tried to reference before -- the one that caused the segfault -- is legal all of a sudden. It's a pain, for sure. But the best way I know of to track down this kind of error is to start putting in printf( )s all over the place, gradually narrowing it down.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: Ming SWF markup and swfrender not giving correct output I'm working on an application that uses Ming through the PHP extension to generate SWF files. This works great until someone needs to print something, so we create a PDF that uses a static image instead of flash. Currently we're using a custom solution that turns Flash into another format via Quicktime, but we want to get rid of needing a special box just for conversion.
I found SWFTools which looks like the perfect solution. I installed it on the web server and can call it from my app, but it's not generating the exact same output as the Flash version. I'm getting 33 errors with my test file, with two errors that repeat quite a bit:
array
0 => string 'Error: ID 5 unknown' (length=19)
...
3 => string 'Warning: Shape doesn't start with a moveTo' (length=42)
...
33 => string 'Error: ID 133 unknown' (length=21)
The resulting file ends up with a few missing shapes if I run swfrender with -l (but overall not bad), but without -l I seem to get the correct number of shapes but rendered incorrectly (for example, a square might have 3 sides correct, and then fill from the 4th side to a random corner of the image).
Is there a known incompatibility between ming and SWFTools or is there something I can do to clear up these errors?
I'm using ming 0.4.4 and swftools-2011-01-23-1815 on CentOS 5.5, and PHP 5.3.6 (custom compiled).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.