text stringlengths 8 267k | meta dict |
|---|---|
Q: Base64 - Exif metadata Is it possible to add EXIF metadata for "ImageDescription" to a base64 JPG image string?
Could this one have a EXIF data "ImageDescription" that claims it's the Stack Overflow logo? http://pastebin.com/0vUsybJQ
Thanks.
A: You could add EXIF metadata by reading the text format jpg image, adding the metadata to the image in memory, then saving it again in the base 64 text format.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ActionScript 3.0 How to Save Data to Server When User Navigates New Page I have a Flash AS 3.0 swf-based browser game. It's hosted on my site and communicates with a MySQL database via PHP using Flash's URLVariables. Everything works fine. The problem is, I want to be able to save the player's game after he leaves the webpage or closes his browser. How is this usually handled?
Is there a reliable event that fires when a swf is terminated? Is so, what is it? If not, what's the solution? Should I simply save the player's data every x seconds? That seems like it will bog down my server. I could have 10,000 people playing and I don't want to save each of their games every x seconds.
A: There is no such event and you should solve this problem with clever UI and in-game tutorial which includes manual saving instructions. You can also try to automatically save the game only after the critical game moments.
The actual solution depends on the type of the game you make. For usual solutions take a look at the games matching the genre of your game on the http://kongregate.com
A: Save your game after your player has done something.
Did the player upgrade their tower to level 2? Save data.
Did the player attack a boat? Save data.
If you do that, you have nothing to worry about when the user exits the page.
Your SWF should just be a client that displays that and allows players to select choices - do not put any game play logic* inside it unless you want it to get hacked with cheat engine in 3 seconds.
By that, I mean, don't go
if(playerResources > 500){
build();
}
Rather
if(server.build() == 1){
server.getUpdatedBuildings();
} else {
notifyUser("Not enough resources!");
}
Never ever trust the client.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I find the maximum stack size? I am working on Ubuntu 11.04. How do I find out the maximum call stack size of a process and also the size of each frame of the stack?
A: You can use getrlimit to see the stack size and setrlimit to change it.
There's an example in the Increase stack size in Linux with setrlimit post.
A: getrlimit() and setrlimit() are not Linux commands. They are system calls.
So in order to get the result of them, you need something like a bash script or any other executable script that returns the result of the system call.
A: You can query the maximum process and stack sizes using getrlimit. Stack frames don't have a fixed size; it depends on how much local data (i.e., local variables) each frame needs.
To do this on the command-line, you can use ulimit.
If you want to read these values for a running process, I don't know of any tool that does this, but it's easy enough to query the /proc filesystem:
cat /proc/<pid>/limits
A: A quick Google search should reveal some information on this subject.
> ulimit -a # shows the current stack size
A: The following call to ulimit returns the maximum stack size in kibibytes (210 = 1024 bytes):
ulimit -s
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
} |
Q: Chrome Extension: Message passing confusion I'm trying to send the number of checked items on a page over to a popup. The add input button on the popup alerts or sends to the console the amount of checkboxes checked on the webpage.
My script is not doing this and I thought there may be a confusion on how message passing works. Here is what I have:
Manifest:
{
"name": "A plugin for...",
"version": "1.0",
"background_page": "background.html",
"permissions": [
"tabs", "http://*/*", "https://", "*"
],
"content_scripts": [
{
"matches": ["http://*/*","https://*/*"],
"js": ["main_content_script", jquery.min.js", "json.js"]
}
],
"browser_action": {
"name": "Plugin",
"default_icon": "icon.png",
"popup": "popup.html"
}
}
Popup.html
<html>
<script src="jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#add').click(function(){
add();
alert("add clicked");
});
$('#save').click(function(){
alert("save clicked");
});
$('#delete').click(function(){
alert("delete clicked");
});
});
</script>
<script>
//chrome.tabs.sendRequest(integer tabId, any request, function responseCallback)
//chrome.extension.onRequest.addListener(function(any request, MessageSender sender, function sendResponse) {...}));
function add(){
chrome.extension.onRequest.addListener(function(request, sender, sendResponse)
console.log(request.count); //? nothing in console
});
</script>
<form action="http://www.xxxxx.com/xxxxx/xxxx/session.php" method="post" enctype="text/plain">
<input type="submit" value="Add" name="add" id="add"/>
<input type="submit" value="Save" name="save" id="save"/>
<input type="submit" value="Delete" name="delete" id="delete"/>
</form>
</html>
main_content_script.js
$(document).ready(function() {
//var location = window.location.href;
var checked = $('input:checkbox:checked').length;
if(checked > 0){
var values = $('input:checkbox:checked').map(function () {
//return $(this).parent().next().html(); --> returns the name
var strong_tag = $(this).parent().next().html();
var link_tag = $(strong_tag + 'a').html();
return $(link_tag).attr('href');
}).get();
} else {
return false;
}
if(values){
var count = values.length;
alert(count + " values selected: " + values);
chrome.extension.sendRequest({count:count}, function(response) {
console.log('count sent');
});
});
A: chrome.extension.onRequest is not to be used in popup. It is to be used in the background page.
Background page
var count=0; //"count" is outside of any function
chrome.extension.onRequest(function(request, sender, sendResponse){
count=request.count;
console.log(request.count);
});
Popup - use chrome.extension.getBackgroundPage() to get back the variable.
var count = chrome.extension.getBackgroundPage().count; //get it back
alert("There are "+count+" checkboxes checked."); //Voilà!
A: The problem here is that your content script is sending messages, but there is no active listener. The lifetime of the popup.html page is from when the browser action is clicked until it disappears. Unless the page happens to exist when you send your request, there's nothing listening to your requests.
To fix the problem, you should setup your listener (chrome.extension.onRequest.addListener) in the background page (which persists for the lifetime of your extension).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7535997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Using OpenCV in Xcode project gives linker errors After building and installing opencv via their cmake process, I took some suggested steps to integrate the libraries into an Xcode project.
*
*I use "Link Binary With Libraries" in Build Phases for both libopencv_core.dylib and libopencv_highgui.dylib
*"Header Search Paths" contains /usr/local/include/ and /usr/include/ (the opencv headers themselves are in /usr/local/include/opencv2, which I have tried to include)
*"Library Search Paths" contains /usr/local/lib and /usr/lib (the opencv dylib files are in /usr/local/lib/)
And then I added a bit of demo opencv code. When I run this project, I get errors you'd expect from a linking problem:
Apple Mach-O Linker Error:
Undefined symbols for architecture x86_64:
"_cvCvtColor", referenced from:
Using file on the dylibs I include shows what I expect:
file /usr/local/lib/libopencv_core.dylib
/usr/local/lib/libopencv_core.dylib: Mach-O 64-bit dynamically linked shared library x86_64
file /usr/local/lib/libopencv_highgui.dylib
/usr/local/lib/libopencv_highgui.dylib: Mach-O 64-bit dynamically linked shared library x86_64
Both of these files are built for the proper architecture and (I think) properly added to the project. How can I debug other linker issues that I might be having? Where do I go from here?
A: cvtColor is in libopencv_imgproc.dylib. Add that to the "Link Binary with Libraries" phase and you should be good.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: transactional open/write/replace in .NET? I am thinking maybe i should restrict it to 8k. I'd like to open a file and write from start to end everytime. However if for some reason (say power outage) it doesnt complete i do not want corrupt data. Is there a way i can do a transactional file open/write/close so it doesnt replace the previous file unless its a success?
When i google i get many results on database transactions and ado instead of files
A: *
*Write to a temporary file,
*Delete the old file
*Rename the remporary file only if the write succeeds.
To prevent data loss if you lose power after step two but before step three, you need one more step:
*
*At program startup, check for temporary files that have their main files deleted but have not yet been renamed. If you find any, perform step three again for those files.
A: NTFS in Windows Vista and later is transactional.
I do not believe that you can access it from the pure managed code - you'll need to P/Invoke into Win32 API.
A good place to start would be CreateTransaction, CommitTransaction, RollbackTransaction, CreateFileTransacted (and other *Transacted) Win32 API functions.
A: Slight variation on Mark Byer's solution which I use all the time:
*
*Write new contents to a temp file IN THE SAME DIRECTORY as the file you want to replace.
*If the write is successful, rename[1] it to the desired file.
Rename is atomic so if it succeeds, then the system is not left in an undefined state. If it fails, then, again, the system is still in a pristine state AND you have a backup of the content you wanted to replace it with (in the temp file) on system restart.
My typical naming convention is along the lines of:
/path/to/original/content.data
/path/to/original/.#content.data
If the system shuts down somewhere in that process, on restart of your app, you can scan for .#content.data and either present that to the user as what they had been entering when the system went down or use some custom magic to decide whether or not it is "complete" to decide whether or not to rename it over content.data.
I don't know what kind of data you are writing so I can't help you decide what that "magic" would be, but if it's an xml file, for example, you could parse it for correctness and if you don't get an unexpected end-of-file, then you probably have a complete file.
FWIW, restricting yourself to 8k writes isn't going to save you because you are now depending on implementation details in the underlying OS and FS which could change in the next version or be different in a previous version.
Links:
*
*http://83.139.107.116:8080/1.1/handlers/monodoc.ashx?link=M%3aMono.Unix.Native.Stdlib.rename(System.String%2cSystem.String)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Problem having SQL statements that contain " or ' I am storing HTML in an SQLite3 database using python. When I go to insert some HTML into an SQL table I get an error/problem when I have '"' characters.
The following example of my problem creates the incorrect SQL statement:
INSERT INTO mytable(id, html, other) VALUE(1, " <img src="images/1.png" alt=""/> ", "some other info")
# it should be something like
INSERT INTO mytable(id, html, other) VALUE(1, " <img src=\"images/1.png\" alt=\"\"/> ", "some other info")
How can I have an SQL statement with " characters in it?
import sqlite3
HTML = """ <img src="images/1.png" alt=""/> """ # NOTE the " characters in it
insert_qry = """ INSERT INTO mytable(id, html, other) VALUE(%s, "%s", "%s")"""
conn = sqlite3.connect( GlobalVars.db_path )
cur = conn.cursor()
res = cur.execute( insert_qry % (1, HTML, "some other info") )
# THESE FUNCTIONS DONT SOLVE MY PROBLEM:
def format_for_DB( src_code ):
""" Post: """
src_code = src_code.replace( '"', '\"' )
src_code = src_code.replace( "'", "\'" )
return src_code
def format_for_display( src_code ):
""" Post: """
src_code = src_code.replace( '\"', '"' )
src_code = src_code.replace( "\'", "'" )
return src_code
def format_for_DB( src_code ):
""" Post: """
src_code = src_code.replace( '"', '""' )
src_code = src_code.replace( "'", "''" )
return src_code
def format_for_display( src_code ):
""" Post: """
src_code = src_code.replace( '""', '"' )
src_code = src_code.replace( "''", "'" )
return src_code
A: Use a parameterized query:
query = """ INSERT INTO mytable(id, html, other) VALUES(?, ?, ?) """
# ...
cur.execute(query, (1, HTML, "some other info"))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using RubyMine receiving errors I am trying to learn Ruby on Rails. I purchased Ruby Mine and installed it on Ubuntu. I followed the installation instructions and when I tried to debug my first project in RubyMine, I get this:
Error running Development: test001: Failed to install gems.
Following gems were not installed: linecache19 (0.5.12): Error
installing linecache19: ERROR: Failed to build gem native extension.
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/bin/ruby extconf.rb *
extconf.rb failed * Could not create Makefile due to some reason,
probably lack of necessary libraries and/or headers. Check the
mkmf.log file for more details. You may need configuration options.
Provided configuration options: --with-opt-dir --without-opt-dir
--with-opt-include --without-opt-include=${opt-dir}/include
--with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog
--without-make-prog --srcdir=. --curdir
--ruby=/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
require': no such file to load -- openssl (LoadError) from
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
require' from
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/net/https.rb:92:in
' from
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
require' from
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
require' from
/home/stormkiernan/.rvm/gems/ruby-1.9.2-p290@global/gems/ruby_core_source-0.1.5/lib/contrib/uri_ext.rb:11:in
' from
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
require' from
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
require' from
/home/stormkiernan/.rvm/gems/ruby-1.9.2-p290@global/gems/ruby_core_source-0.1.5/lib/ruby_core_source.rb:6:in
' from rubygems/custom_require>:33:inrequire' from
rubygems/custom_require>:33:in rescue in require' from
rubygems/custom_require>:29:inrequire' from extconf.rb:2:in ' Gem
files will remain installed in
/home/stormkiernan/.rvm/gems/ruby-1.9.2-p290@global/gems/linecache19-0.5.12
for inspection. Results logged to
/home/stormkiernan/.rvm/gems/ruby-1.9.2-p290@global/gems/linecache19-0.5.12/ext/trace_nums/gem_make.out
/home/stormkiernan/Downloads/RubyMine-3.2.4/rb/gems/ruby-debug-base19x-0.11.30.pre2.gem:
Error installing ruby-debug-base19x-0.11.30.pre2.gem: ERROR: Failed to
build gem native extension.
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/bin/ruby extconf.rb ***
extconf.rb failed *** Could not create Makefile due to some reason,
probably lack of necessary libraries and/or headers. Check the
mkmf.log file for more details. You may need configuration options.
Provided configuration options: --with-opt-dir --without-opt-dir
--with-opt-include --without-opt-include=${opt-dir}/include
--with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog
--without-make-prog --srcdir=. --curdir
--ruby=/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
require': no such file to load -- openssl (LoadError) from
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
require' from
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/net/https.rb:92:in
' from
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
require' from
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
require' from
/home/stormkiernan/.rvm/gems/ruby-1.9.2-p290@global/gems/ruby_core_source-0.1.5/lib/contrib/uri_ext.rb:11:in
' from
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
require' from
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
require' from
/home/stormkiernan/.rvm/gems/ruby-1.9.2-p290@global/gems/ruby_core_source-0.1.5/lib/ruby_core_source.rb:6:in
' from rubygems/custom_require>:33:in require' from
rubygems/custom_require>:33:inrescue in require' from
rubygems/custom_require>:29:in require' from extconf.rb:2:in ' Gem
files will remain installed in
/home/stormkiernan/.rvm/gems/ruby-1.9.2-p290@global/gems/linecache19-0.5.12
for inspection. Results logged to
/home/stormkiernan/.rvm/gems/ruby-1.9.2-p290@global/gems/linecache19-0.5.12/ext/trace_nums/gem_make.out
Now, just prior to this error, I was prompted with:
The gem ruby-debug-base19x required by the debugger is not currently
installed. Would you like to install it?
I responded "Yes", and it attempted (and I assume failed) to download whatever necessary dependencies the software needed. The window title was "Installing Gems". It was immediately after this window closed that I received the above error.
What do I need to do?
edit: Ruby Env
RubyGems Environment:
- RUBYGEMS VERSION: 1.8.10
- RUBY VERSION: 1.9.2 (2011-07-09 patchlevel 290) [x86_64-linux]
- INSTALLATION DIRECTORY: /home/stormkiernan/.rvm/gems/ruby-1.9.2-p290
- RUBY EXECUTABLE: /home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
- EXECUTABLE DIRECTORY: /home/stormkiernan/.rvm/gems/ruby-1.9.2-p290/bin
- RUBYGEMS PLATFORMS:
- ruby
- x86_64-linux
- GEM PATHS:
- /home/stormkiernan/.rvm/gems/ruby-1.9.2-p290
- /home/stormkiernan/.rvm/gems/ruby-1.9.2-p290@global
- GEM CONFIGURATION:
- :update_sources => true
- :verbose => true
- :benchmark => false
- :backtrace => false
- :bulk_threshold => 1000
- REMOTE SOURCES:
- http://rubygems.org/
edit #2 showing errors:
$ gem install ruby-debug-base19x Fetching: linecache19-0.5.12.gem
(100%) Building native extensions. This could take a while... ERROR:
Error installing ruby-debug-base19x: ERROR: Failed to build gem
native extension.
/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
extconf.rb
* extconf.rb failed * Could not create Makefile due to some
reason, probably lack of necessary libraries and/or headers. Check
the mkmf.log file for more details. You may need configuration
options.
Provided configuration options: --with-opt-dir --without-opt-dir
--with-opt-include --without-opt-include=${opt-dir}/include
--with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog
--without-make-prog --srcdir=. --curdir
--ruby=/home/stormkiernan/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
:29:in require': no such file
to load -- ruby_core_source (LoadError) from
<internal:lib/rubygems/custom_require>:29:inrequire' from
extconf.rb:2:in `'
Gem files will remain installed in
/home/stormkiernan/.rvm/gems/ruby-1.9.2-p290/gems/linecache19-0.5.12
for inspection. Results logged to
/home/stormkiernan/.rvm/gems/ruby-1.9.2-p290/gems/linecache19-0.5.12/ext/trace_nums/gem_make.out
A: I had the same problems and tried so many options before I came across this:
http://beginrescueend.com/packages/openssl/
$ rvm pkg install openssl
$ rvm remove 1.9.2m
$ rvm install 1.9.2 --with-openssl-dir=$rvm_path/usr
This resolves the issue with linecache19 rubydebug-19 and openssl:
*** extconf.rb failed ***
custom_require.rb:36:in `require': no such file to load -- openssl (LoadError)
A: Do the following from a command prompt instead:
sudo gem install ruby-debug-base19x
of if you're using rvm (recommended):
gem install ruby-debug-base19x
EDITED: type this first: rvm --default use 1.9.2
A: I've solved this error running the following command in ubuntu:
$ sudo apt-get install ruby-dev
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: search and replace string on multiple files from unix terminal We are converting all the static html pages in our codebase into php pages. The first step would be to change all the .html file extension to .php (which I already did). The second step would be to update all the links within each of those html pages to point to new php pages.
(for instance, inside index.php i have links to both contact.html and about-us.html. Now since we have replaced every .html file extension to .php, we need to change contact.html to contact.php, and likewise, about-us.html to about-us.php).
what i want to do now is to search for a particular string across multiple files. (search for "contact.html" inside many files, such as index.php, index2.php, index3.php, etc etc..) after that, replace all "contact.html" in all those files with "contact.php".
I am not familiar with unix command line, and i so far have seen other people's similar questions here in the forum but not quite understand which one could help me achieve what i want. I'm using cygwin and if possible i need to solve this without perl script since i dont have it installed. i need to try using either sed, grep, find, or anything else.
So, if any of you think that this is a duplicate please point me to a relevant post out there. thanks for your time.
A: Try this:
find . -name '*.html' -exec sed -i 's/\.html/\.php/g' "{}" \;
It will find all files in the current and subdirectories that end in .html, and run sed on each of them to replace .html with .php anywhere it appears within them.
See http://content.hccfl.edu/pollock/unix/findcmd.htm for more details.
A: On my Mac, I had to add a parameter to the -i option: the extension to add to the name (in this case, nothing, so the file is stored in-place).
find . -name '*.html' -exec sed -i '' 's/\.html/\.php/g' "{}" \;
A: You can certainly use ack to select your files to update. For example,
to change all "foo" to "bar" in all PHP files, you can do this from
the Unix shell:
perl -i -p -e's/foo/bar/g' $(ack -f --php)
Source: man ack
A: This should work (found here: http://www.mehtanirav.com/search-and-replace-recursively-using-sed-and-grep/):
for i in `find . -type f` ; do sed "s/html/php/g" "$i" >> "$i.xx"; mv "$i.xx" "$i"; done
A: This worked for me :
find . -type f -print0 | xargs -0 sed -i 's/str1/str2/g'
A: Below script can help in replacing the string in files:
#!/bin/bash
echo -e "please specify the folder where string has need to be replaced: \c"
read a
echo -e "please specify the string to be replaced: \c"
read b
echo -e "please specify the string: \c"
read c
find $a -type f -exec sed -i 's/'"$b"'/'"$c"'/g' {} \; > /dev/null 2>&1
if [ $? -eq 0 ]
then
echo "string has been replaced..."
else echo "String replacement has been failed"
exit0
fi
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: IntelliJ IDEA forward-engineering with UML? From IntelliJ IDEA Help System on UML:
Forward engineering, which enables you to design and create a visual
model, and populate it with node elements, members and relationships.
IntelliJ IDEA automatically generates source code and keeps it
synchronized with the model.
...but it does not tell you how to do that. I know how to show the UML Diagram for existing classes (Right click on a class file from Project window, select Diagrams > Show Diagram.
What I want to do is the other way around: Create UML Class Diagrams, and generate method stubs from those diagrams.
A: If you want to do this, i think you have to click show diagram in a certain source folder or package and then right click in the diagram and you will have the option to create classes or interfaces. When right-clicking on a class there will also be an option to create methods and fields in this class.
So folow the show diagram, then right click and use the context menu to create classes/methods etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Problems with pointers I have a Binary Search Tree that I'm making and I implemented the Insert node code as follows:
BSTNode * BST::Insert(const std::string & v){
BSTNode * node = new BSTNode(v);
if (root == NULL){
root = node;
} else if (root->value.compare(v) > 0) {
Insert(root->left, node);
//recursive insert the method
} else if (root->value.compare(v) < 0) {
Insert(root->right, node);
} else {
delete node;
return NULL;
}
size++;
return node;
}
Followed by the recursive insert method in my header file (it has private access):
void Insert(BSTNode* current, BSTNode* node){
if (current == NULL){
current = node;
} else if (current->value == node->value){
delete node;
} else if (current->value < node->value) {
Insert(current->left, node);
} else if (current->value > node->value){//if (parent->value < node->value) {
Insert(current->right, node);
}
}
When the recursive function sets the pointer and then returns, the changes I made to the pointer DON'T stay.
A: The problem here is that current is a local variable with a copy of the value of the pointer. It's not the same variable that you pass in. If you want to modify the pointer in place, your method should accept either a pointer to the pointer or a reference to the pointer. The easiest way to do this would be to just modify current to be a reference to a pointer. The resultant code would look like this:
void Insert(BSTNode* ¤t, BSTNode* node){
if (current == NULL){
current = node;
} else if (current->value == node->value){
delete node;
} else if (current->value < node->value) {
Insert(current->left, node);
} else if (current->value > node->value){//if (parent->value < node->value) {
Insert(current->right, node);
}
}
In general, you should keep in mind that pointers are just values which tell you the memory location of something. So they're really just numbers. And when they're passed into a function, unless there's a reference, they're passed by the value. So your function just sees the number, not the variable which contained the number.
A: void Insert(BSTNode*& current, BSTNode* node)
is the correct prototype for the function given. Nothing else need be changed. The reason why this is necessary is described well by Keith.
I would also add that in general you should be wary of conditionally deleting pointers passed as arguments to a function -- you're placing a burden on the code outside that function to determine whether the memory address it refers to is still valid or not. Consider use of boost's shared_ptr instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JSplitPane divider color affected by contents I'm working on an application that displays two JScrollPanes within a JSplitPane. Each of the JScrollPanes contains a JPanel that I'm drawing the content onto. The problem is that when I adjust the divider of the JScrollPane, the color of the divider is affected. It seems to take on the appearance of the JPanel inside of it - that is, the background of the divider has snippets of the words and colors I'm displaying in the JPanel.
It seems like I'm missing a revalidate() or something here, but I can't get to the bottom of it.
A: Sounds to me you you might be forgetting:
super.paintComponent(g)
in the custom painting of the panel.
If you need more help then you need to post your SSCCE demonstrating the problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Requesting HTTPS and submitting forms in Java I got the following scenario:
On my webserver I have a .do file with HTML code like this:
<form name="login" action="someAction" method="post">
//some textboxes
</form>
<input type="submit" value="Submit" />
Now I'm trying to make an application, which connects to the webserver - https - fills out the form and get the HTML from the next site (the site, when you're logged in).
After that I have to do several JavaScript submits to get the data I want to display it in my desktop application.
I somehow managed to build a connection and get the HTML from the login site, but since I'm new to HttpRequests and stuff like that, I have no idea how to go on.
Help would be appreciated.
Edit: I get the following in my Console:
Sep 24, 2011 2:23:28 PM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Obsolete content type encountered: 'text/javascript'.
Sep 24, 2011 2:23:30 PM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Obsolete content type encountered: 'text/javascript'.
Wrapped com.gargoylesoftware.htmlunit.ScriptException: Error: ERROR: No matching script interactive for function () {
var result = bootstrapDojo();
result.dojo._dijit = result.dijit;
result.dojo._dojox = result.dojox;
return result.dojo;
}
A: I suggest you to use htmlunit:
HtmlUnit is a "GUI-Less browser for Java programs". It models HTML
documents and provides an API that allows you to invoke pages, fill
out forms, click links, etc... just like you do in your "normal"
browser.
It has fairly good JavaScript support (which is constantly improving)
and is able to work even with quite complex AJAX libraries, simulating
either Firefox or Internet Explorer depending on the configuration you
want to use.
It is typically used for testing purposes or to retrieve information
from web sites.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Question about syntax where in the define of a class I started to implement a repository pattern following this tutorial. Now In the definition of the class which implements the interface of Repository. The defines of the classes are made like this.
public class Repository<E,C> : IRepository<E,C>, IDisposable
where E : EntityObject
where C : ObjectContext
{
}
Can someone explain me if I defined a class with generics why do i need to type where to explain which are the objects that are expected??. I'm really confused with this topic
A: The where specifies what can be used - in your example, E must be an EntityObject (or something that derives from EntityObject) and C must be an ObjectContext (or something that derives from ObjectContext). This is a set of constraints, that's all. Typically this is done because the class (in this case Repository) has some expectations that need to be met, at least that is how I've personally used it.
A: What is going on is that the generics are constrained to be that type or any type derived from that type. This is done so that certain methods, properties, events, fields, etc. become available to the generics and prevents types that don't match these constraints form being used.
You can find more information on MSDN about Generic Constraints.
A: Constraining the types with where is a deliberate choice, which has two consequences:
*
*The compiler will not allow you to write code that instantiates the generic if the type parameters do not satisfy these constraints, and in return
*It will allow you to use objects of class E and C as EntityObject and ObjectContext within the definition of Repository<,>; otherwise, it would not let you access members (methods, properties, etc) of those classes because it wouldn't be able to guarantee that those members exist on the types used to specify the generic.
A:
why do i need to type where to explain which are the objects that are expected?
You're not saying what objects are expected. You're constraining the types to be some type that derives from that object type. However, it can be a specific subclass of that object.
A: You're defining a generic type constraint there - not which types are expected.
In this same way, you can require a specific type, an interface that must be implemented by your expected type, a base class, an abstract class or you can constrain the type parameter(s) as a reference type too (where T : class).
This link may be of use: Constraints on type parameters
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JQuery - Find value of a dynamic ID OK so I'm using a CRM on demand system, and a URL needs to be updated when a form is updated. The form cannot be referenced by ID for some reason so I need another way of getting the value="THIS" out of it.
No Ids allowed! (Unless you know why) Thanks :)
The HTML concerned:
<input id="ServiceRequestEditForm.CustomObject6 Id" class="inputControlFlexWidth" type="text" value="THIS CHANGES AFTER UPDATE" tabindex="9" size="25" name="ServiceRequestEditForm.CustomObject6 Name">
Thanks for the quick answers. The reason I couldn't select an ID was because it contained a fullstop.
E.g. EditForm.CustomObject6 needs to become EditForm\.CustomObject6
The answers are still very useful however.
A: <input id="blah" onchange="javascript: MyOnChange(this);">
<script>
function MyOnChange(myControl)
{
alert(myControl.id);
}
</script>
A: You can use custom attributes.
<script>
var value = $("input[custom=custom]").attr("value");
</script>
<input custom="CUSTOM" id="your thing" class"blah blah" type="text" value="VALUE" tabindex="9" size="25" name="blah blah">
A:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be
followed by any number of letters, digits ([0-9]), hyphens ("-"),
underscores ("_"), colons (":"), and periods (".").
No spaces allowed, your ID is not valid.
A: If the only problem is the . in the ID, then you can do something like:
var field = $("input[id='full.ID.here']");
.
If the ID contains some dynamic parts that always changes, but one part of it is constant:
var field = $("input[id*='ID part here']");
Note the *=.
.
If the known part of the ID is particularly at the end of it, you can use:
var field = $("input[id$='ID part here']");
Note the $=.
.
For a full reference of jQuery selectors, check:
http://api.jquery.com/category/selectors/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How does Entity Framework track updates? Inserts and Deletes are easy - they have dedicated methods. But what does it do to detect changes to loaded records?
A: There are many articles describing the change tracking mechanism.
Tracking Changes in POCO Entities
Identity Resolution, State Management, and Change Tracking
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is Bitnami Lampstack ebs eligible for AWS free tier? I am considering installing the Bitnami Lampstack ebs on AWS, but I wanted to make sure that it is still free of charge to use if I don't go over the limits. There was no clear documentation of this online. If anyone knows please let me know.
Thank you.
A: Yes, if your Amazon account qualifies for the free tier (was created after October 2010) you should be able to run any of the available BitNami images for free. We do it all the time (I am one of the BitNami developers :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Should I also assure undefined in a jQuery plugin closure? I often see this described as the way to assure a safe environment for a jQuery plugin:
(function($){
$.fn.myPlugin = function() {
...
};
})(jQuery);
Wouldn't it be better to also safeguard undefined, like so:
(function($, undefined){
$.fn.myPlugin = function() {
...
};
})(jQuery);
Or does it not matter? and if so, why?
A: It is probably not necessary. If you test whether a variable is undefined, you should prefer using
typeof variable === 'undefined'
anyway.
"Safeguarding" jQuery on the other hand is something you definitely should do, otherwise your plugin will not work if jQuery is used in noConflict mode.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to make Linux kernel I navigated to the directory usr/src/linuex-headers-2.6.38-8 and type make.
I got the following error message.
No rule to make target `kernel/bounds.c', needed by `kernel/bounds.s'
How do I solve this problem? I am using ubuntu...
A: This is copied from an answer on the Ubuntu forums:
Installing the kernel sources using apt / aptitude / synaptic / whatsoever only puts the compressed source code into /usr/src. You need to uncompress the sources:
$ cd /usr/src
$ sudo tar -xvjf linux-source-$YOUR_VERSION_HERE.tar.bz2
Then just change into the new /usr/src/linux-source-$YOUR_VERSION_HERE directory and built your kernel like you used to
You'll often find if you paste the exact error message into Google the answer just pops right up :)
A: Did you run
make config
before typing make^? Do you have permissions to create files in the directory? Did you look on Canonical's site for instructions on building a kernel?
If you do not want to use the source code given, you can fetch the latest kernel from GitHub. Ordinarily, there would be copies on kernel.org, but the site was compromised recently and taken down for re-installation.
^ - If you do not want to answer a thousand questions, there are alternate commands such as
make menuconfig
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need help with .htaccess redirect I need to redirect all image requests from site.com/folder1/folder2/images/name.jpg to site.com/folder3/folder4/folder5/images/name.jpg
Where name is dynamic
A: This is pretty straightforward.
RewriteEngine On
RewriteRule folder1/folder2/images/(.*)\.(jpg|gif|png|jpeg)$ /folder3/folder4/folder5/images/$1.$2 [L,QSA]
# If you only have jpg
RewriteRule ^folder1/folder2/images/(.*)\.jpg$ http://site.com/folder3/folder4/folder5/images/$1.jpg [L,QSA]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Considerations when using more threads than hardware threads? I have a brand new laptop with a i7 2630qm CPU (4 cores, 8 threads) and I'm excited about tapping into the power of a multi-core processors.
After reading about threads, I realized I had a few areas of confusion in regards to how one writes the most efficient code.
I have about 200 tables, each with about 40,000 records. I plan on pulling each table in its entirety into a multidimensional array inside the java program, and running simulations against the array.
Obviously, it would be one array per thread, but what I’m wondering is: Would I receive any benefits from creating all the (200) threads simultaneously, RAM permitting, or writing code that just switches out arrays between 8 threads?
I mean, from what I understand, my i7 only has 8 hardware threads.
A: I would look into Thread Pools as they might help address the basic desire to limit the number of concurrent threads.
In my experience (in Windows) more threads (about 2x the core threads) allows code with independent CPU-bound threads to run faster: that is, the program can steal more priority that the Operating System might give to other processes ;-) Setting the thread priority can help as well and, of course, IO-bound threads are an entirely different story.
Remember your code does not run in isolation and the operating system is ultimately responsible for the thread scheduling:
The only way to know "for certain" is to try different things and run performance tests.
The results may be surprising and are influenced by many factors including, but not limited to, JVM/OS, algorithm, thread contention, and user-space duty cycle (IO operations end up in kernel-land). Also keep in mind that different parts of the program may react entirely differently and it might not even make sense to thread some parts (such as reading in the initial data), depending on where the bottleneck(s) materialize(s) and -- not to be disregarded -- program complexity.
(Using a thread pool can easily allow adjusting of the number of concurrent threads allowed, which is one reason why I suggested it.)
Happy mutli-threaded coding.
A: What are you planning to do in each thread -- query the database, or process data? If it's the former, multiple threads won't help as you'll be I/O bound. If it's the latter, careful design could indeed give you substantial speedup using multiple threads.
A: The answer is a definitive "it depends". Having more threads then your hardware supports may speed up your program. For example, imagine you have 1 thread holding a lock for I/O to the database, while 7 other threads wait for it to finish. Having more threads doing other work in the meantime would certainly speed up this program.
Since your program appears to do a lot of I/O with database interactions, as well as a lot of CPU intensive work once the data has been collected, you may well find that having more then 8 threads makes your program run faster.
As others have suggested, a little trial-and-error is probably in order. Good luck.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do you get an object from a string in Objective C? How can I get an object based from a string in Objective C?
For example
int carNumber=5;
[@"car%i",carNumber].speed=10;
//should be same as typing car5.speed=10;
Oh course, those are just made up objects, but how could I get an object based on what is in a variable.
A: If you follow Key-Value Coding then this is as easy as:
NSString *myValue = [NSString stringWithFormat:@"car%@", carNumber];
id myValue = [myClass valueForKey:myValue];
A: You cannot. When your code is compiled, the names of variables will no longer be what you've specified. car5 is not and has never been a string.
The better strategy would be to have an array of car objects and then specify the index. In C style (where carType is the type of each car):
carType carArray[5];
//! (Initialize your cars)
int carNumber= 5;
carArray[carNumber].speed= 10;
In Objective-C, if your cars are objects:
NSMutableArray* carArray= [[NSMutableArray alloc] init];
//! (Initialize your cars and add them to the array)
int carNumber= 5;
carType car= [carArray objectAtIndex:carNumber];
car.speed= 10;
A: int carNumber = 5;
NSString *className = [NSString stringWithFormat:@"car%d", carNumber];
Class carClass = [[NSBundle mainBundle] classNamed:className];
if (carClass) {
id car = [[carClass alloc] init];
[car setValue:[NSNumber numberWithInt:10] forKey:@"speed"];
}
But there are issues such as saving try car class instance for later access, perhaps adding it to an NSMutableArray.
A: Why not just store the car objects in an NSArray?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SQlite3 to MySQL I am running Ubuntu 10.04, Rails 3.0.7, Ruby 1.9.2
I started with this link: Convert a Ruby on Rails app from sqlite to MySQL?
I successfully installed 'mysql2'
database.yml :
# SQLite version 3.x
# gem install sqlite3
development:
adapter: mysql2
database: db/development.mysql2
pool: 5
timeout: 5000
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: mysql2
database: db/test.mysql2
pool: 5
timeout: 5000
production:
adapter: mysql2
database: db/production.mysql2
pool: 5
timeout: 5000
When i get to step 5 :
rake db:create
I get this error (with trace):
** Invoke db:create (first_time)
** Invoke db:load_config (first_time)
** Invoke rails_env (first_time)
** Execute rails_env
** Execute db:load_config
** Execute db:create
Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
Couldn't create database for {"adapter"=>"mysql2", "database"=>"db/test.mysql2",
"pool"=>5, "timeout"=>5000}, charset: utf8, collation: utf8_unicode_ci
Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
Couldn't create database for {"adapter"=>"mysql2", "database"=>"db/development.mysql2",
"pool"=>5, "timeout"=>5000}, charset: utf8, collation: utf8_unicode_ci
Any suggestions?
A: The problem is that you haven't started your MySQL server yet, so it's failing to create the database because the server is having the common mysqld.sock error.
Here's a fantastic resource for this: http://matthom.com/archive/2009/06/14/installing-mysql-mac-os-x
On my machine, it works when I start at 'Connecting to MySQL', but there are a couple of other sections explaining alternative resolutions to the socket error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Closing TabItem by clicking middle button I have a problem.
In my WPF application, if i press a tabItem with middle mouse button, this tabItem should close. Just like in FireFox.
But I try to do this using MVVM, and i need to use commands. Also my tabItems are created dynamically.
Help me plz!
Thank you!
A: Create a DataTemplate for your tab items like this:
<DataTemplate x:Key="ClosableTabTemplate">
<Border>
<Grid>
<Grid.InputBindings>
<MouseBinding Command="ApplicationCommands.Close" Gesture="MiddleClick" />
</Grid.InputBindings>
<!-- the actual contents of your tab item -->
</Grid>
</Border>
</DataTemplate>
In your application window, add a the close command
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Close" Executed="CloseCommandExecuted" CanExecute="CloseCommandCanExecute" />
</Window.CommandBindings>
and finally assign the data template as item template to your tab control.
A: You could add a MouseBinding to some InputBindings perhaps?
A: Closing a TabItem (Not Selected) - TabControl
<TabControl x:Name="TabControlUser" ItemsSource="{Binding Tabs}" Grid.RowSpan="3">
<TabControl.Resources>
<Style TargetType="TabItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TabItem">
<Border Name="Border" BorderThickness="1,1,1,0" BorderBrush="Gainsboro" CornerRadius="4,4,0,0" Margin="2,0">
<ContentPresenter x:Name="ContentSite"
VerticalAlignment="Center"
HorizontalAlignment="Center"
ContentSource="Header"
Margin="10,2"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="Border" Property="Background" Value="LightSkyBlue" />
</Trigger>
<Trigger Property="IsSelected" Value="False">
<Setter TargetName="Border" Property="Background" Value="GhostWhite" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.Resources>
<TabControl.ItemTemplate>
<!-- this is the header template-->
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Header}" FontWeight="ExtraBold" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<Image Source="/Images/RedClose.png" Width="22" Height="22" MouseDown="Image_MouseDown" HorizontalAlignment="Right" Margin="10 0 0 0"/>
</StackPanel>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<!-- this is the body of the TabItem template-->
<DataTemplate>
<UserControl Content="{Binding UserControl, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
C# Code - Image MouseDown Click Event
try
{
int matches = 0;
DependencyObject dependency = (DependencyObject)e.OriginalSource;
// Traverse the visual tree looking for TabItem
while ((dependency != null) && !(dependency is TabItem))
dependency = VisualTreeHelper.GetParent(dependency);
if (dependency == null)
{
// Didn't find TabItem
return;
}
TabItem selectedTabItem = dependency as TabItem;
var selectedTabContent = selectedTabItem.Content as MainWindowViewModel.TabItem;
foreach (var item in MainWindowViewModel.Tabs)
{
if (item.Header == selectedTabContent.Header)
{
matches = MainWindowViewModel.Tabs.IndexOf(item);
}
}
MainWindowViewModel.Tabs.RemoveAt(matches);
}
catch (Exception ex)
{
System.Windows.Application.Current.Dispatcher.Invoke((System.Action)(() => new View.MessageBox(ex.Message).ShowDialog()));
}
This event finds with the exact Mouse clicked position (as TabItem)and this will remove
MainWindowViewModel.Tabs.RemoveAt(matches); the TabItem(even if it is not selected).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Forcing JavaScript return false to persist through functions Thanks for taking time to review this question. I've been trying to fix a problem for one or two hours with no success...
I have a web page that sets a JavaScript variable based on the response from a function:
grade = getScore(questionAnswer, userAnswer, questionType);
(userAnswer is the user's answer to a question and is retrieved from a textarea)
Here is getScore:
function getScore(questionAnswer, userAnswer, questionType) {
switch(questionType) {
case 'multiplechoice':
return scoreMC(questionAnswer, userAnswer);
break;
case 'usertypesanswer':
return scoreTA(questionAnswer, userAnswer);
break;
default:
return 0
}
}
The functions for scoreMC and scoreTA have been tested thoroughly and work great. The issue is that if a user's answer is not formatted correctly, scoreMC or scoreTA will return false. Otherwise it returns the values score and msg. However, instead of getting a "false" value for "grade" when I set the value of the grade variable based on the getScore function, I get "undefined". (We have no problems when the user response validates properly.)
After setting "grade", I have tried to check if any part of it is undefined:
if(typeof(grade.score) !== undefined)
I do not understand why, but even when I see "undefined" in my Firebug console, grade.score passes this check...
Does anyone see what I am doing wrong? Thank you very much for your assistance. I have a lot to learn about JavaScript.
A: if(typeof(grade.score) !== undefined)
can be
if(grade.score && grade.score !== false) // if I understand your question
or
if(typeof(grade.score) !== "undefined")
typeof returns a string
A: If no return statement is used (or an empty return with no value), JavaScript returns undefined.
It is almost certain that one of your score functions (scoreMC, scoreTA, whose code you should have included in the question) does not return a value i.e.
return;
Or just reaches the end of the function code block without encountering a return.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is this usage of condition variables ALWAYS subject to a lost-signal race? Suppose a condition variable is used in a situation where the signaling thread modifies the state affecting the truth value of the predicate and calls pthread_cond_signal without holding the mutex associated with the condition variable? Is it true that this type of usage is always subject to race conditions where the signal may be missed?
To me, there seems to always be an obvious race:
*
*Waiter evaluates the predicate as false, but before it can begin waiting...
*Another thread changes state in a way that makes the predicate true.
*That other thread calls pthread_cond_signal, which does nothing because there are no waiters yet.
*The waiter thread enters pthread_cond_wait, unaware that the predicate is now true, and waits indefinitely.
But does this same kind of race condition always exist if the situation is changed so that either (A) the mutex is held while calling pthread_cond_signal, just not while changing the state, or (B) so that the mutex is held while changing the state, just not while calling pthread_cond_signal?
I'm asking from a standpoint of wanting to know if there are any valid uses of the above not-best-practices usages, i.e. whether a correct condition-variable implementation needs to account for such usages in avoiding race conditions itself, or whether it can ignore them because they're already inherently racy.
A: The state must be modified inside a mutex, if for no other reason than the possibility of spurious wake-ups, which would lead to the reader reading the state while the writer is in the middle of writing it.
You can call pthread_cond_signal anytime after the state is changed. It doesn't have to be inside the mutex. POSIX guarantees that at least one waiter will awaken to check the new state. More to the point:
*
*Calling pthread_cond_signal doesn't guarantee that a reader will acquire the mutex first. Another writer might get in before a reader gets a chance to check the new status. Condition variables don't guarantee that readers immediately follow writers (After all, what if there are no readers?)
*Calling it after releasing the lock is actually better, since you don't risk having the just-awoken reader immediately going back to sleep trying to acquire the lock that the writer is still holding.
EDIT: @DietrichEpp makes a good point in the comments. The writer must change the state in such a way that the reader can never access an inconsistent state. It can do so either by acquiring the mutex used in the condition-variable, as I indicate above, or by ensuring that all state-changes are atomic.
A: The fundamental race here looks like this:
THREAD A THREAD B
Mutex lock
Check state
Change state
Signal
cvar wait
(never awakens)
If we take a lock EITHER on the state change OR the signal, OR both, then we avoid this; it's not possible for both the state-change and the signal to occur while thread A is in its critical section and holding the lock.
If we consider the reverse case, where thread A interleaves into thread B, there's no problem:
THREAD A THREAD B
Change state
Mutex lock
Check state
( no need to wait )
Mutex unlock
Signal (nobody cares)
So there's no particular need for thread B to hold a mutex over the entire operation; it just need to hold the mutex for some, possible infinitesimally small interval, between the state change and signal. Of course, if the state itself requires locking for safe manipulation, then the lock must be held over the state change as well.
Finally, note that dropping the mutex early is unlikely to be a performance improvement in most cases. Requiring the mutex to be held reduces contention over the internal locks in the condition variable, and in modern pthreads implementations, the system can 'move' the waiting thread from waiting on the cvar to waiting on the mutex without waking it up (thus avoiding it waking up only to immediately block on the mutex).
As pointed out in the comments, dropping the mutex may improve performance in some cases, by reducing the number of syscalls needed. Then again it could also lead to extra contention on the condition variable's internal mutex. Hard to say. It's probably not worth worrying about in any case.
Note that the applicable standards require that pthread_cond_signal be safely callable without holding the mutex:
The pthread_cond_signal() or pthread_cond_broadcast() functions may be called by a thread whether or not it currently owns the mutex that threads calling pthread_cond_wait() or pthread_cond_timedwait() have associated with the condition variable during their waits [...]
This usually means that condition variables have an internal lock over their internal data structures, or otherwise use some very careful lock-free algorithm.
A: The answer is, there is a race, and to eliminate that race, you must do this:
/* atomic op outside of mutex, and then: */
pthread_mutex_lock(&m);
pthread_mutex_unlock(&m);
pthread_cond_signal(&c);
The protection of the data doesn't matter, because you don't hold the mutex when calling pthread_cond_signal anyway.
See, by locking and unlocking the mutex, you have created a barrier. During that brief moment when the signaler has the mutex, there is a certainty: no other thread has the mutex. This means no other thread is executing any critical regions.
This means that all threads are either about to get the mutex to discover the change you have posted, or else they have already found that change and ran off with it (releasing the mutex), or else have not found they are looking for and have atomically given up the mutex to gone to sleep (and are guaranteed to be waiting nicely on the condition).
Without the mutex lock/unlock, you have no synchronization. The signal will sometimes fire as threads which didn't see the changed atomic value are transitioning to their atomic sleep to wait for it.
So this is what the mutex does from the point of view of a thread which is signaling. You can get the atomicity of access from something else, but not the synchronization.
P.S. I have implemented this logic before. The situation was in the Linux kernel (using my own mutexes and condition variables).
In my situation, it was impossible for the signaler to hold the mutex for the atomic operation on shared data. Why? Because the signaler did the operation in user space, inside a buffer shared between the kernel and user, and then (in some situations) made a system call into the kernel to wake up a thread. User space simply made some modifications to the buffer, and then if some conditions were satisfied, it would perform an ioctl.
So in the ioctl call I did the mutex lock/unlock thing, and then hit the condition variable. This ensured that the thread would not miss the wake up related to that latest modification posted by user space.
At first I just had the condition variable signal, but it looked wrong without the involvement of the mutex, so I reasoned about the situation a little bit and realized that the mutex must simply be locked and unlocked to conform to the synchronization ritual which eliminates the lost wakeup.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Factory Girl + Mongoid embedded documents in fixtures Let’s say you have the following mongoid documents:
class User
include Mongoid::Document
embeds_one :name
end
class UserName
include Mongoid::Document
field :first
field :last_initial
embedded_in :user
end
How do you create a factory girl factory which initializes the embedded first name and last initial? Also how would you do it with an embeds_many relationship?
A: I was also looking for this one and as I was researching I've stumbled on a lot of code and did pieced them all together (I wish there were better documents though) but here's my part of the code. Address is a 1..1 relationship and Phones is a 1..n relationship to events.
factory :event do
title 'Example Event'
address { FactoryGirl.build(:address) }
phones { [FactoryGirl.build(:phone1), FactoryGirl.build(:phone2)] }
end
factory :address do
place 'foobar tower'
street 'foobar st.'
city 'foobar city'
end
factory :phone1, :class => :phone do
code '432'
number '1234567890'
end
factory :phone2, :class => :phone do
code '432'
number '0987654321'
end
(And sorry if I can't provide my links, they were kinda messed up)
A: Here is a solution that allows you to dynamically define the number of embedded objects:
FactoryGirl.define do
factory :profile do
name 'John Doe'
email 'john@bigcorp.com'
user
factory :profile_with_notes do
ignore do
notes_count 2
end
after(:build) do |profile, evaluator|
evaluator.notes_count.times do
profile.notes.build(FactoryGirl.attributes_for(:note))
end
end
end
end
end
This allows you to call FactoryGirl.create(:profile_with_notes) and get two embedded notes, or call FactoryGirl.create(:profile_with_notes, notes_count: 5) and get five embedded notes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
} |
Q: Jquery load() and ui-widget I am using load() to grab a section of a .php page and replace content in a div dynamically.
The index page has a jquery-ui tab widget on it that works fine upon initial load. When I use load() to change out the content, and then go back to the original home page with the ui-tabs on it (via AJAX), there is no onclick functionality (ie. they take me to the #tabs-1-fragment instead of updating the tabs dynamically).
I have researched it a bit and have found that once a section is destroyed via AJAX, when it loads again it will not have the event handlers bound to it. The recommended course of action is to attach the "live()" handler instead of "bind()", but since I am calling upon a Jquery UI widget, I can't think of a way (besides editing the source code or building my own tabs) that I could do that.
I have been searching for a few hours but have no really found an answer to this question.
Am I missing something basic?
Here is the code used on the navigation links to call the page content:
$(document).ready(function(){
$('#studioNav').click(function() {
$('#mainContent').animate({opacity:0}, 1000, function(){
$('#mainContent').load('studio.php #studio');
});
$('#mainContent').animate({opacity:1}, 1000);
$('#nav li').removeClass('current');
$(this).addClass("current");
return false;
});
$('#contactNav').click(function() {
$('#mainContent').animate({opacity:0}, 1000, function(){
$('#mainContent').load('contact.php #contact');
});
$('#mainContent').animate({opacity:1}, 1000);
$('#nav li').removeClass('current');
$(this).addClass("current");
return false;
});
$('#calendarNav').click(function() {
$('#mainContent').animate({opacity:0}, 1000, function(){
$('#mainContent').load('calendar.php #calendar');
});
$('#mainContent').animate({opacity:1}, 1000);
$('#nav li').removeClass('current');
$(this).addClass("current");
return false;
});
$('#homeNav').click(function() {
$('#mainContent').animate({opacity:0}, 1000, function(){
$('#mainContent').load('index.php #featured');
});
$('#mainContent').animate({opacity:1}, 1000);
$('#nav li').removeClass('current');
$(this).addClass("current");
return false;
});
})
It's not pretty code (I am a beginner to javascript and jquery).
The tabs section is:
<div id="mainContent">
<ul class="ui-tabs-nav">
<li class="ui-tabs-nav-item ui-tabs-selected" id="nav-fragment-1">
<a href="#fragment-1"><span>Friday, August 26th</span>Digit Dealer EP Release w/ Lionshare, Wolf Couture, Sludgehammer</a>
</li>
<li class="ui-tabs-nav-item" id="nav-fragment-2">
<a href="#fragment-2"><span>Friday, August 26th</span>Digit Dealer EP Release w/ Lionshare, Wolf Couture, Sludgehammer</a>
</li>
<li class="ui-tabs-nav-item" id="nav-fragment-3">
<a href="#fragment-3"><span>Friday, August 26th</span>Digit Dealer EP Release w/ Lionshare, Wolf Couture, Sludgehammer</a>
</li>
<li class="ui-tabs-nav-item" id="nav-fragment-4">
<a href="#fragment-4"><span>Friday, August 26th</span>Digit Dealer EP Release w/ Lionshare, Wolf Couture, Sludgehammer</a>
</li>
</ul>
<!-- First Content ---------------->
<div id="fragment-1" class="ui-tabs-panel" style="">
<img class="featured_img" src="http://placehold.it/315x275" alt="Balls" />
<ul class="featured_meta">
<li><a href=" ">Link to their music in the archives</a></li>
<li><a href="http://blogspot.sheastadium.com/ ">Link to full blog Post</a></li>
</ul>
<div class="socialMedia">
<div class="facebook">
<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="" send="false" layout="button_count" width="120" show_faces="false" action="like" font=""></fb:like>
</div>
<div class="twitter">
<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
</div>
</div>
<div class="info" >
<h2>Friday, August 26th</h2>
<p>Digit Dealer EP Release w/ Lionshare, Wolf Couture, Sludgehammer, Glowing Pains & Tape Recorder</p>
<h3>Doors at 8pm</h3>
<h3>Cover: $8</h3>
</div><!--END INFO-->
</div><!--END FRAG 1-->
<!-- Second Content -->
<div id="fragment-2" class="ui-tabs-panel ui-tabs-hide" style="">
<img class="featured_img" src="http://placehold.it/315x275" alt="" />
<ul class="featured_meta">
<li><a>Link to their music in the archives</a></li>
<li><a>Link to full blog Post</a></li>
</ul>
<div class="socialMedia">
<div class="facebook">
<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="" send="false" layout="button_count" width="120" show_faces="false" action="like" font=""></fb:like>
</div>
<div class="twitter">
<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
</div>
</div>
<div class="info" >
<h2>Friday, August 26th</h2>
<p>Digit Dealer EP Release w/ Lionshare, Wolf Couture, Sludgehammer, Glowing Pains & Tape Recorder</p>
<h3>Doors at 8pm</h3>
<h3>Cover: $8</h3>
</div><!--END INFO-->
</div><!--End second fragment-->
<!-- Third Content -->
<div id="fragment-3" class="ui-tabs-panel ui-tabs-hide" style="">
<img class="featured_img" src="http://placehold.it/315x275" alt="" />
<ul class="featured_meta">
<li><a>Link to their music in the archives</a></li>
<li><a>Link to full blog Post</a></li>
</ul>
<div class="socialMedia">
<div class="facebook">
<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="" send="false" layout="button_count" width="120" show_faces="false" action="like" font=""></fb:like>
</div>
<div class="twitter">
<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
</div>
</div>
<div class="info" >
<h2>Friday, August 26th</h2>
<p>Digit Dealer EP Release w/ Lionshare, Wolf Couture, Sludgehammer, Glowing Pains & Tape Recorder</p>
<h3>Doors at 8pm</h3>
<h3>Cover: $8</h3>
</div><!--END INFO-->
</div><!--End third fragment-->
<!-- Fourth Content -->
<div id="fragment-4" class="ui-tabs-panel ui-tabs-hide" style="">
<img class="featured_img" src="http://placehold.it/315x275" alt="" />
<ul class="featured_meta">
<li><a>Link to their music in the archives</a></li>
<li><a>Link to full blog Post</a></li>
</ul>
<div class="socialMedia">
<div class="facebook">
<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="" send="false" layout="button_count" width="120" show_faces="false" action="like" font=""></fb:like>
</div>
<div class="twitter">
<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
</div>
</div>
<div class="info" >
<h2>Friday, August 26th</h2>
<p>Digit Dealer EP Release w/ Lionshare, Wolf Couture, Sludgehammer, Glowing Pains & Tape Recorder</p>
<h3>Doors at 8pm</h3>
<h3>Cover: $8</h3>
</div><!--END INFO-->
</div><!--End fragment 4-->
</div><!--End slider-->
</div><!--End Main Content-->
A: You could just re-attach the events in the complete callback of the load() function:
$('#div').load('my.php', function(responseText, textStatus, XMLHttpRequest) {
$('#tabs').tabs();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I find a Java Web Start app's cookies? I'm lost in redirection I'm fairly new to HTTP processing and I would like to retrieve cookies in a Java Web Start application using the CookieHandler class with cookieHandler.get(...).
However, due to our authentication process, there are multiple redirects and I'm not even sure which URI I should be looking at! The request flow is detailed below.
Note: to work around a bug, I have two http servers running so you see two different ports used for 'product.company.com' -- this is only temporary. I'm using httpfox to dump the headers and I have verified that the cookie is there for each of the requests.
Here's the flow:
Browse to alias: http://product.company.com:7890/
Redirects (302) to: https://login.company.com:443/path/login?Token=<long string>
Redirects (302) to: http://product.company.com:80/success?urlc=<long string>
Redirects (301) to: http://product.company.com/success/?urlc=<long string>
application/x-java-jnlp-file (200): http://product.company.com/success/?urlc=<long string>
The application jnlp is located at /success/product.jnlp and the jars are in /success/lib. Codebase="http://product.company.com/success/".
I've tried each of the 'http://product.company.com/' and 'http://product.company.com:port/' variations for the URI, but all my calls return no cookies.
So far, I have omitted the '?fragment' portion of the URL when testing, could that be my error?
If you have any experience, could you suggest how I should be generating the URI that I need? Does anyone have any examples I can test against?
Note: I am using Java 1.6, but I want to be compatible with Java 1.5 clients, if possible.
A: Can you check the cookies using another technology you are more familiar with, like JavaScript?
You can use the java Preferences API to save user preferences and configuration data for your program. Can you use that instead of cookies?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Django template for loop iterating two item I try to implement a forloop in Django tempalte iterating two items per cycle such that
{% for c in cList%}
<ul class="ListTable">
<li>
{{ c1.name }}
</li>
<li>
{{ c2.name }}
</li>
</ul>
{% endfor %}
I know my code is not a proper way to do that but I couldn't find anyway.
I really appreciate for any suggestion
Thanks
A: If you can control the list structure that is cList, why don't you just make it a list of tuples of 2 elements or a list of list of 2 elements, like
#in the view
cList = [(ob1, ob2),
(ob3, ob4)]
and the in the template
{% for c1, c2 in cList %}
<ul class="ListTable">
<li>
{{ c1.name }}
</li>
<li>
{{ c2.name }}
</li>
</ul>
{% endfor %}
Also you can use the zip function to facilitate the creation of cList, or define a
function which create that kind of structure from a list of objects, like
def pack(_list):
new_list = zip(_list[::2], _list[1::2])
if len(_list) % 2:
new_list.append((_list[-1], None))
return new_list
A: One option is to use the the built-in template tag cycle
and do something like:
{% for c in c_list %}
{% cycle True False as row silent %}
{% if row %}
<ul class="ListTable">
{% endif %}
<li>
{{ c.name }}
</li>
{% if not row or forloop.last %}
</ul>
{% endif %}
{% endfor %}
Note: if you have odd number of element on the list the last table will have only one element with this option, sice we are checking for forloop.last
A: I tried to implement cyraxjoe solution which does work, but theres only one problem with it...
a = [1,2,3] will return [(1,2)] but will remove the 3.
So i was asking around in irc freenode #python for a solution and i got this:
it = iter(a); nested = [list(b) for b in itertools.izip_longest(it, it)]
print nested
[[1, 2], [3, None]]
I was also told to look up the documentation for the itertools module, and search for the "grouper" recipe. which does something similar but i havent tried it yet.
I hope this helps :)
*Credits to except and lvh from the #python channel
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why does WebBrowser.Navigate returns null HttpDocument? I have tried:
var browser1 = new WebBrowser();
browser1.Navigate("https://zikiti.co.il/");
HtmlDocument document = browser1.Document;
But browser.Document is null.
Why?
What am I doing wrong ?
public static void FillForm()
{
browser1 = new WebBrowser();
browser1.Navigate(new Uri("https://zikiti.co.il/"));
browser1.Navigated += webBrowser1_Navigated;
Thread.CurrentThread.Join();
}
private static void webBrowser1_Navigated(object sender,
WebBrowserNavigatedEventArgs e)
{
HtmlDocument document = browser1.Document;
System.Console.WriteLine();
}
The application is stuck.
Btw, is there any easier way to fill and submit this form? (I cannot see the request header in Fiddler as the page is always blocked by JS).
A: Because it takes time to download the html. The amount of time nobody ever wants to wait for, especially a user interface thread, the hourglass won't do these day.
It tells you explicitly when it is available. DocumentCompleted event.
You have to pump a message loop to get that event.
A: Because Navigate is asynchronous, and the navigation has not even started by the time you read the Document property's value.
If you look at the example on that page, you will see that to read the "current" URL it needs to subscribe to the Navigated event; same applies to reading Document. The documentation for this event states:
Handle the Navigated event to receive notification when the WebBrowser
control has navigated to a new document. When the Navigated event
occurs, the new document has begun loading, which means you can access
the loaded content through the Document, DocumentText, and
DocumentStream properties.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Tracking full browser activity in VB.Net There's a website that contains some real time information. I want to have a VB.Net windows application that monitors the page, and when it detects certain events it triggers some actions based on the data in the page.
I've been searching like crazy for some mechanism to "hook" into the browser and hopefully inspect the messages transmitted for the application to know how to react.
I've seen the SHDocVw COM object, which comes very close. But when I use the BeforeNavigate2 event, it only seems to fire for GETs, and once I'm on the page where the information is displayed/refreshed the event is not raised.
Short of reverse engineering the page, or having to write some kind of proxy...is there a good way to do this in VB.Net?
A: Here's a method you can try:
*
*Create a GreaseMonkey script embedded on the page to hook up events.
*When changes occur, collect the changes in an array or display them on the screen.
*Create a VB.Net webpage service to listen for POST requests.
*Post using AJAX from your GreaseMonkey script to the webpage service, which then writes to a log file/database on your server.
Otherwise the proxy would probably be the next best method, providing the server isn't HTTPS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails 3 Action Mailer Gmail I am trying to understand how to properly configure Action Mailer for Rails 3 to work with Gmail. Read the article by Ryan Bates and also read the edge Rails page article. Ryan's article said to put the config details in /config/initializers/setup_mail.rb initializer file
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "asciicasts.com",
:user_name => "asciicasts",
:password => "secret",
:authentication => "plain",
:enable_starttls_auto => true
}
But the edge Rails article said put it in the config/environments/$RAILS_ENV.rb, anyone know which is the preferred way of doing it?
A: Put it wherever it makes sense for your particular project. If you need different settings for different environments then do that, otherwise you can put it into an initializer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: deactivate class with another event I'm trying to make a individual dropdown container like of that on the nopnav of the google, well everything runs ok, exept the fact that i would like to deactivate the activated class of the trigger event when i click on to hide the container!
Inserted the page where are the links where will be triggered to push up the container, and the second page is the content of the container, where i put in one script to hide the container and the second one to "tabfy" the menu with the jquery tools tabs.
Here's the code:
$(function () {
"use strict";
$(".user-link").click(function (e) {
e.preventDefault();
if ($(".user-link").hasClass("#buser-box")) {
$(".user-link").removeClass("#buser-box");
} else {
$('#buser-box').show('fast');
$(".user-link").addClass("active");
}
$.ajax({
url: "conta-box/conta-home.html",
cache: false,
dataType: "html",
success: function (data) {
$("#buser-box").html(data);
if (!$(this).hasClass("#buser-box")) {
$("#buser-box").removeClass("#buser-box");
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
});
});
HTML of the Index:
<div class="tabs-global">
<ul id="nav">
<li class="user-link" title="Conta"><a class="user-box"></a></li>
<li class="loja-link" title="Loja"><a class="loja-box"></a></li>
<li class="ava-link" title="Avaliação"><a class="ava-box"></a></li>
</ul>
</div>
<div id="buser-box"></div>
<div id="loja-box"></div>
<div id="ava-box"></div>
HTML of the container-content:
<div class="topbar">
<span class="box-close" onclick="box.close();"></span>
</div>
<div id="menu-box">
<h2>
<span class="icones-conta"></span><span class="texto">Conta</span></h2>
<ul id="conta-tabs">
<li class="current"><a href="box/conta-box/conf.html">Configuração</a></li>
<li><a href="box/conta-box/conf-end.html">Localização</a></li>
<li><a href="box/conta-box/compras.html">Compras</a></li>
</ul>
</div>
<div id="conta-container"></div>
<script type="text/javascript" src="./js/jquery.tools.min.js"></script>
<script type="text/javascript">
$(".box-close").click(function () {
$("#buser-box").hide("fast");
});
</script>
A:
If you use any Jquery property that refers to class, you then need to use a class.
For example:
if ($(".user-link").hasClass("#buser-box")) {
$(".user-link").removeClass("#buser-box");
}
Should Be:
if ($(".user-link").hasClass("buser-box")) {
$(".user-link").removeClass("buser-box");
}
Also you could try a click function for showing and a click function
for hiding:
// hide your dropdown menu by default
$('#myMenuContainer').addClass('closed').hide();
$('.mylink').click(function(showMenu){
//display your drop down menu
if($('#myMenuContainer').hasClass('closed')) {
$('#myMenuContainer').show().addClass('open').removeClass('closed');
}
});
$('.mylink').click(function(showMenu){
//hide your drop down menu
if($('#myMenuContainer').hasClass('open')) {
$('#myMenuContainer').removeClass('open').addClass('closed').hide();
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Display list of times from 12PM to 5AM (Loop) What is good way display a list of times from 12PM to 5AM using Loop (PHP)?
I don't think storing times in the array is good idea, there must be a better way.
Like this as example:
<select id="closetime">
<option value="12:00:00"> 12:00 PM</option>
<option value="12:30:00"> 12:30 PM</option>
<option value="13:00:00"> 13:00 PM</option>
<option value="13:30:00"> 13:30 PM</option>
<option value="14:00:00"> 14:00 PM</option>
<option value="14:30:00"> 14:30 PM</option>
<option value="15:00:00"> 15:00 PM</option>
<option value="15:30:00"> 15:30 PM</option>
<option value="16:00:00"> 16:00 PM</option>
<option value="16:30:00"> 16:30 PM</option>
<option value="17:00:00"> 17:00 PM</option>
<option value="17:30:00"> 17:30 PM</option>
<option value="18:00:00"> 18:00 PM</option>
<option value="18:30:00"> 18:30 PM</option>
<option value="19:00:00"> 19:00 PM</option>
<option value="19:30:00"> 19:30 PM</option>
<option value="20:00:00"> 20:00 PM</option>
<option value="20:30:00"> 20:30 PM</option>
<option value="21:00:00"> 21:00 PM</option>
<option value="21:30:00"> 21:30 PM</option>
<option value="22:00:00"> 22:00 PM</option>
<option value="22:30:00"> 22:30 PM</option>
<option value="23:00:00"> 23:00 PM</option>
<option value="23:30:00"> 23:30 PM</option>
<option value="00:00:00"> 00:00 AM</option>
<option value="00:30:00"> 00:30 AM</option>
<option value="01:00:00"> 01:00 AM</option>
<option value="01:30:00"> 01:30 AM</option>
<option value="02:00:00"> 02:00 AM</option>
<option value="02:30:00"> 02:30 AM</option>
<option value="03:00:00"> 03:00 AM</option>
<option value="03:30:00"> 03:30 AM</option>
<option value="04:00:00"> 04:00 AM</option>
<option value="04:30:00"> 04:30 AM</option>
<option value="05:00:00"> 05:00 AM</option>
</select>
00:00:00 mean midnight in MySQL right?
A: I believe this is the easiest... and shortest way :: only 6 lines of code ;)
$start_time = "13:00:00";
$end_time = "05:00:00";
while(strtotime($start_time) >= strtotime($end_time)){?>
<option value="<?=date("H:i:s", strtotime($start_time))?>"> <?=date("H:i A", strtotime($start_time))?></option>
<? $start_time = date("H:i:s", strtotime("$start_time -30 minutes"));
}//end while
A: <select id="closetime">
<?php
for ($i = 12; $i < 30; $i++) {
$num = $i > 23 ? $i - 24 : $i;
$num = $num < 10 ? "0$num" : $num;
$ampm = $num > 11 && $num < 24 ? 'PM' : 'AM';
echo "<option value=\"$num:00:00\"> $num:00 $ampm</option>\n";
if ($num != 5)
echo "<option value=\"$num:30:00\"> $num:30 $ampm</option>\n";
}
?>
</select>
http://codepad.org/fCXU1Goh
OUTPUT
<select id="closetime">
<option value="12:00:00"> 12:00 PM</option>
<option value="12:30:00"> 12:30 PM</option>
<option value="13:00:00"> 13:00 PM</option>
<option value="13:30:00"> 13:30 PM</option>
<option value="14:00:00"> 14:00 PM</option>
<option value="14:30:00"> 14:30 PM</option>
<option value="15:00:00"> 15:00 PM</option>
<option value="15:30:00"> 15:30 PM</option>
<option value="16:00:00"> 16:00 PM</option>
<option value="16:30:00"> 16:30 PM</option>
<option value="17:00:00"> 17:00 PM</option>
<option value="17:30:00"> 17:30 PM</option>
<option value="18:00:00"> 18:00 PM</option>
<option value="18:30:00"> 18:30 PM</option>
<option value="19:00:00"> 19:00 PM</option>
<option value="19:30:00"> 19:30 PM</option>
<option value="20:00:00"> 20:00 PM</option>
<option value="20:30:00"> 20:30 PM</option>
<option value="21:00:00"> 21:00 PM</option>
<option value="21:30:00"> 21:30 PM</option>
<option value="22:00:00"> 22:00 PM</option>
<option value="22:30:00"> 22:30 PM</option>
<option value="23:00:00"> 23:00 PM</option>
<option value="23:30:00"> 23:30 PM</option>
<option value="00:00:00"> 00:00 AM</option>
<option value="00:30:00"> 00:30 AM</option>
<option value="01:00:00"> 01:00 AM</option>
<option value="01:30:00"> 01:30 AM</option>
<option value="02:00:00"> 02:00 AM</option>
<option value="02:30:00"> 02:30 AM</option>
<option value="03:00:00"> 03:00 AM</option>
<option value="03:30:00"> 03:30 AM</option>
<option value="04:00:00"> 04:00 AM</option>
<option value="04:30:00"> 04:30 AM</option>
<option value="05:00:00"> 05:00 AM</option>
</select>
A: I think the easiest method is:
for ($x = 12; $x <= 29; $x++) {
$H = $x % 24;
$ap = ($H < 12)? "AM" : "PM";
$h = $H % 12;
echo "<option value='".str_pad($H, 2, "0", STR_PAD_LEFT).":00:00'> "
.str_pad($h, 2, "0", STR_PAD_LEFT).":00 $ap</option>\n";
echo "<option value='".str_pad($H, 2, "0", STR_PAD_LEFT).":30:00'> "
.str_pad($h, 2, "0", STR_PAD_LEFT).":30 $ap</option>\n";
}
A: Not trying to initiate a 'lines war' but this is just 2 or 3 lines of code and works just fine as well.
for($hour=12; $hour < 30; $hour++)
{
echo"<option value=\'".($hour >= 24 ? ($hour-23).":00:00": ($hour-11).":00:00")."\'>".($hour >= 24 ? ($hour-23).":00:00 AM": ($hour-11).":00:00 PM")."</option>";
echo"<option value=\'".($hour >= 24 ? ($hour-23).":30:00": ($hour-11).":30:00")."\'>".($hour >= 24 ? ($hour-23).":30:00 AM": ($hour-11).":30:00 PM")."</option>";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Find elements with given class and multiple attribute Jquery How do we do a each() with multiple attributes?
Working:
$(".divReplies[userId="+userIdTemp+"] ").each(function(index, element) {
});
Not working:
$(".divReplies[userId="+userIdTemp+" replyId="+replyId+"]").each(function(index, element) {
});
Thanks
A: You have use separate brackets for each attribute:
$(".divReplies[userId="+userIdTemp+"][replyId="+replyId+"]").each
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Data type conversion of column in numpy record array I have a numpy recarray with several integer columns and some string columns. The data in the string columns is composed 99% of integers, but numpy things it's a string because "NA" is in the column.
So I have two questions:
*
*How do I remove the NA's and change them to 0s?
*How can I convert the string columns to integers so that I can have a record array with many integer columns?
Thanks.
A: Use where and astype:
>>> x = np.array([123, 456, "789", "NA", "0", 0])
>>> x
array(['123', '456', '789', 'NA', '0', '0'], dtype='|S8')
>>> np.where(x != 'NA', x, 0).astype(int)
array([123, 456, 789, 0, 0, 0])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Directory naming using Process ID and Thread ID I have an application with a few threads that manipulate data and save the output in different temporary files on a particular directory, in a Linux or a Windows machine. These files eventually need to be erased.
What I want to do is to be able to better separate the files, so I am thinking of doing this by Process ID and Thread ID. This will help the application save disk space because, upon termination of a thread, the whole directory with that thread's files can be erased and leave the rest of the application reuse the corresponding disk space.
Since the application runs on a single instance of the JVM, I assume it will have a single Process ID, which will be that of the JVM, right?
That being the case, the only way to discriminate among these files is to save them in a folder, the name of which will be related to the Thread ID.
Is this approach reasonable, or should I be doing something else?
A: java.io.File can create temporary files for you. As long as you keep a list of those files associated with each thread, you can delete them when the thread exits. You can also mark the files to delete on exit in case a thread does not complete.
A: You're correct, the JVM has one process ID, and all threads in that JVM will share the process id. (It is possible for a JVM to use multiple processes, but AFAIK, no JVM does that.)
A JVM may very well re-use underlying OS threads for multiple Java threads, so there is no guaranteed correlation between a thread exiting in Java and anything similar happening at the OS level.
If you just need to cleanup stale files, sorting the files by their creation timestamp should do the job sufficiently? No need to encode anything special at all in the temporary file names.
Note that PIDs and TIDs are neither guaranteed to be increasing, no guaranteed to be unique across exits. The OS is free to recycle an ID. (In practice the IDs have to wrap around before re-use, but on some machines that can happen after only 32k or 64k processes have been created.
A: It seems the simplest solution for this approach is really to extend Thread - never thought I'd see that day.
As P.T. already said Thread IDs are only unique as long as the thread is alive, they can and most certainly will be reused by the OS.
So instead of doing it this way, you use the Thread name that can be specified at construction and to make it simple, just write a small class:
public class MyThread extends Thread {
private static long ID = 0;
public MyThread(Runnable r) {
super(r, getNextName());
}
private static synchronized String getNextName() {
// We can get rid of synchronized with some AtomicLong and so on,
// doubt that's necessary though
return "MyThread " + ID++;
}
}
Then you can do something like this:
public static void main(String[] args) throws InterruptedException {
Thread t = new MyThread(new Runnable() {
@Override
public void run() {
System.out.println("Name: " + Thread.currentThread().getName());
}
});
t.start();
}
You have to overwrite all constructors you want to use and always use the MyThread class, but this way you can guarantee a unique mapping - well at least 2^64-1 (negative values are fine too after all) which should be more than enough.
Though I still don't think that's the best approach, possibly better to create some "job" class that contains all necessary information and can clean up its files as soon as it's no longer needed - that way you also can easily use ThreadPools and co where one thread will do more than one job. At the moment you have business logic in a thread - that doesn't strike me as especially good design.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: White pure CSS triangle bug on Firefox 6 Windows http://jsfiddle.net/pixelfreak/Eq246/
Notice the gray border on the white triangle. This only happens on FF 6 Windows (I did not test on older FF version)
Is there a fix to this? It looks like bad anti-aliasing or something.
A: Give it a try with this:
border-style: outset;
http://jsfiddle.net/KDREU/
edit
Looks like if you put outset on one of the 4 border styles you can use colors other than white and not have them lightened.
/* This works for an orange down arrow that I'm using. */
border-style: solid outset solid solid;
http://jsfiddle.net/fEKrE/1/
A: It happens on FF6 on Linux too. It's going to be an artifact from antialiasing the diagonal line. AFAIK, there isn't a way around this other than to use an image.
A: fixed with
border-style: solid dashed solid solid;
tested on firefox 19.0.2, opera 12.04, chromium 25.0.1359.0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Kohana 3 pagination renders incorrectly Edit
I've added a github repostitory of my /application directory.
https://github.com/ashleyconnor/Egotist
I'm working through "Kohana 3: Beginner's Guide" from Packt Publishing and have just completed the 7th chapter.
The problem I am having is on my homepage I render paginated urls from a message model but the second url points to a route that doesn't exist.
I've highlighted where the View is rendering a 1 before the correct URL.
Another issue I am having is random 1s printed throughout the screen. Is this due to me coding in Development mode?
Controller:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Welcome extends Controller_Application {
public function action_index()
{
$content = View::factory('welcome')
->bind('messages', $messages)
->bind('pager_links', $pager_links);
$message = new Model_Message;
$message_count = $message->count_all();
$pagination = Pagination::factory(array(
'total_items' => $message_count,
'items_per_page' => 3,
));
$pager_links = $pagination->render();
$messages = $message->get_all($pagination->items_per_page, $pagination->offset);
$this->template->content = $content;
}
}
View:
<h1>Recent Messages on Egotist</h1>
<?php foreach ($messages as $message) : ?>
<p class="message">
<?php echo $message->content; ?>
<br />
<span class="published">
<?php echo Date::fuzzy_span($message->date_published); ?>
</span>
</p>
<hr />
<?php endforeach; ?>
<?php echo $pager_links; ?>
Snippet of the output:
<p class="pagination">
First
Previous
<strong>1</strong>
<a href="1/?page=2">2</a> <--misbehaving
<a href="/?page=3">3</a>
<a href="/?page=4">4</a>
<a href="/?page=5">5</a>
<a href="/?page=6">6</a>
<a href="/?page=7">7</a>
<a href="/?page=8">8</a>
<a href="/?page=2" rel="next">Next</a>
<a href="/?page=8" rel="last">Last</a>
</p><!-- .pagination -->
A: In your Controller_User_Account and HTML class:
replace
<?php echo defined('SYSPATH') or die('No direct access allowed.');
with
<?php defined('SYSPATH') or die('No direct access allowed.');
A: I can't see anything wrong with the 3.0/master version of the pagination module.
Anything that could be adding a '1' at that point during the output would be something called during the execution of HTML::chars($page->url($i)).
I suggest you check your codebase and system libraries for out of place calls to 'echo'.
If you've cloned from git you should be able to check for changes, if not, compare it to a fresh copy.
Also, in your bootstrap file, you should set your index_file option to FALSE instead of the empty string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Cannot get info from error when trying to get JSON data via JQuery, For the life of me i can't figure out why i keep getting an error when making an AJAX request using the bit of bode below. When the page load, and the alerts pop up absolutely no useful information as to why the request failed, the response code is 200 in firebug, readyState, and status are both 0 when the pop up, and responseText is empty. I can access the request using the browser just fine. I just goes to the error callback function:
<script src="/static/js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
function loadData(url, container) {
var data =[];
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(data) {
var obj = jQuery.parseJSON(data,container);
alert(container);
},
error: function(xhr,err) {
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
};
loadData( 'http://api.giantbomb.com/genres/?api_key=####&format=json', '#genres-pane');
});
</script>
thank you in advance
A: It looks like you are trying to do a cross-domain request as JSON, which means using XmlHttpRequest in the backend. This is disallowed due to the same origin policy. Try changing your data type to "jsonp". You'll also need to change your url's format argument from "json" to "jsonp".
A: FireBug for firefox will show you all requests, posts, responses, etc. Very useful for this kind of stuff.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Communicating between SERVICE and web/desktop application Whats the recommended way to communicate between a service and a desktop app or webpage ?
I want the service to do all the work, but admin/management/reporting to be possible via
web or desktop. (It will be written in C# with .Net 4.0)
Is it named pipes ? sockets ? wcf ? rest ? soap ? other ? What is best practice ?
Any info would be greatly appreciated.
The service needs to be effectively real time so any comms need to be async.
Thanks
Andrew
UPDATE 1 - The service monitors network traffic REALTIME as a service. The client could be local or could be remote (using ASP.NET/MVC or even silverlight). The client doesn't need realtime data, but should be abe to query SETTINGS, Statistics, Logs, etc..
A: If both ends of the code are controlled then, barring any specific requirements, I'd opt for WCF because "it's so darn simple".
See Choosing a (WCF) Transport: it's
easy to go from HTTP to TCP to Named Pipes (ooo la la!):
A named pipe is an object in the Windows operating system kernel, such as a section of shared memory that processes can use for communication [read: very fast]. A named pipe has a name, and can be used for one-way or duplex communication between processes on a single machine.
Of course, if the same machine requirement is violated, then HTTP/TCP can be used instead depending upon network configuration, etc -- difference to code? A configuration setting :)
Happy coding.
A: The question is asked as WCF or HTTP or TCP. WCF is an extremely flexible communications foundation. You can write your code once and decorate your data classes and on the fly switch via configuration and code between HTTP JSON/POX, TCP, Binary, Binary over HTTP, custom serialization etc... The question as to which transport mechanism you choose is based on routing/firewall limitations, clients etc... Personally, I like diagnosable transports like HTTP and JSON/XML just because how universal, routable, and diagnosable they are (checkout fiddler2).
From your description, it seems like the tough part of the problem is REALTIME network traffic monitoring which the service performs. The channel between the client and that service seems like the simpler part of the problem.
Also from the description, the client doesn't need to be REAL TIME and is simply querying statistics, settings and logs. Because the client can be local or remote (remote implying possibly outside the intranet? routing externally).
Because of that, I would decouple the REALTIME network statistics gathering process from the querying portion which makes it async as you mentioned. At that point, the service is simply opening a channel to the clients to query simple stats, settings and logs ... choose the most routable and diagnosable channel like HTP, REST JSON|XML. If that's a problem, keep your WCF server code intact and change the WCF bindings configuration.
The question is a bit open ended and ambiguous but hopefully that helps a bit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: php null is undefined value?
Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”
I got error:
Notice: Undefined variable: null
Line in code is:
$input = new $class($company, null, $sablonas, $null, $value);
Class constructor is:
public function __construct($company, $document, $sablonas, $options, $value = null) {
How I can pass a null value?
A: $input = new $class($company, null, $sablonas, $null, $value);
// ^ ^
// (1) (2)
It's talking about (2), not (1). You have a typo with $null.
The notice message "Undefined variable: null" is a little misleading here, but consider the following case:
<?php
error_reporting(E_ALL | E_NOTICE);
echo $lol;
// Output: "Notice: Undefined variable: lol in /t.php on line 3"
?>
You can see that the $ isn't included in the name that the notice message gives you, so if you follow this logic back you arrive at the conclusion I made at the top of this answer.
A: You have $null as a variable:
$input = new $class($company, null, $sablonas, $null, $value);
//------------------------------------------^^^^^^^^^^
// Guessing that's supposed to be
$input = new $class($company, null, $sablonas, null, $value);
//-------------------------------------------^^^^^^^^
A: $null = NULL;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: When putting an Outlet in Xcode into a variable, don't know what kind of pointer to use? So I was going through Cocoa Programming for Mac OS X for Dummies by Erick Tejkowski. After doing the calculator example, I got the basics of Objective-C in Xcode, since I know basic stuff. I got that to put what's in a text field into a variable, you first have to put the text field as an outlet in the header file like this:
#import <Cocoa/Cocoa.h>
@interface Mah_Application__It_is_awesomeAppDelegate : NSObject <NSApplicationDelegate>
{
NSWindow *window;
IBOutlet id hi;
}
- (IBAction)Calculate:(id)sender;
@property (assign) IBOutlet NSWindow *window;
@end
And then you put it in a variable like so:
- (IBAction)Calculate:(id)sender
{
int something;
hi = [hi intValue];
}
However, when I want a Boolean value, like a checkbox or something, or perhaps even a radio group, I don't know what pointer to use in place of intValue. For a moment, assume the variable hi is now a boolean. I tried this:
- (IBAction)Calcluate:(id)sender
{
BOOL something;
something = [hi BOOL];
}
but it says that's not a valid pointer. What should I use, then?
A: boolValue is defined for NSString and NSNumber, so it depends on what type hi is
- (IBAction)Calcluate:(id)sender
{
BOOL something = [hi boolValue];
}
A: Edit (I re-read the question and you might want what the other answer from Stew suggested):
BOOL myBool = [@"1" boolValue];
myBool = [someObject boolValue];
These are some of the conversion methods for NSString - Also see the NSString Reference Here:
- (double)doubleValue;
- (float)floatValue;
- (int)intValue;
- (NSInteger)integerValue;
- (long long)longLongValue;
// (boolValue) Skips initial space characters (whitespaceSet),
// or optional -/+ sign followed by zeroes.
// Returns YES on encountering one of "Y", "y", "T", "t", or a digit 1-9.
// It ignores any trailing characters.
- (BOOL)boolValue;
Also, from NSNumber Class Reference:
boolValue Returns the receiver’s value as a BOOL.
- (BOOL)boolValue
Return Value The receiver’s value as a BOOL,
converting it as necessary.
Special Considerations Prior to Mac OS X v10.3, the value returned
isn’t guaranteed to be one of YES or NO. A 0 value always means NO or
false, but any nonzero value should be interpreted as YES or true.
Try this:
[NSNumber numberWithBool:YES]
[NSNumber numberWithBool:NO]
[NSNumber numberWithInt:1]
[NSNumber numberWithFloat:0.25]
// etc...
- (IBAction)Calcluate:(id)sender
{
BOOL something;
something = [hi [NSNumber numberWithBool:BOOL]];
}
NSNumber reference
Since things like BOOL, NSInteger, NSUInteger, etc are not pointers, they cannot do certain things like be values for a dictionary, etc. For this purpose, NSNumber was created. It wraps these types in a class so they can be used as arguments for passing to selectors, or stored in NSDictionary's.
Here is a common thing I do:
[self.myLoadingView performSelectorOnMainThread:@selector(setHidden:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Model Real-World Relationships in a Graph Database (like Neo4j)? I have a general question about modeling in a graph database that I just can't seem to wrap my head around.
How do you model this type of relationship: "Newton invented Calculus"?
In a simple graph, you could model it like this:
Newton (node) -> invented (relationship) -> Calculus (node)
...so you'd have a bunch of "invented" graph relationships as you added more people and inventions.
The problem is, you start needing to add a bunch of properties to the relationship:
*
*invention_date
*influential_concepts
*influential_people
*books_inventor_wrote
...and you'll want to start creating relationships between those properties and other nodes, such as:
*
*influential_people: relationship to person nodes
*books_inventor_wrote: relationship to book nodes
So now it seems like the "real-world relationships" ("invented") should actually be a node in the graph, and the graph should look like this:
Newton (node) -> (relationship) -> Invention of Calculus (node) -> (relationship) -> Calculus (node)
And to complicate things more, other people are also participated in the invention of Calculus, so the graph now becomes something like:
Newton (node) ->
(relationship) ->
Newton's Calculus Invention (node) ->
(relationship) ->
Invention of Calculus (node) ->
(relationship) ->
Calculus (node)
Leibniz (node) ->
(relationship) ->
Leibniz's Calculus Invention (node) ->
(relationship) ->
Invention of Calculus (node) ->
(relationship) ->
Calculus (node)
So I ask the question because it seems like you don't want to set properties on the actual graph database "relationship" objects, because you may want to at some point treat them as nodes in the graph.
Is this correct?
I have been studying the Freebase Metaweb Architecture, and they seem to be treating everything as a node. For example, Freebase has the idea of a Mediator/CVT, where you can create a "Performance" node that links an "Actor" node to a "Film" node, like here: http://www.freebase.com/edit/topic/en/the_last_samurai. Not quite sure if this is the same issue though.
What are some guiding principles you use to figure out if the "real-world relationship" should actually be a graph node rather than a graph relationship?
If there are any good books on this topic I would love to know. Thanks!
A: Some of these things, such as invention_date, can be stored as properties on the edges as in most graph databases edges can have properties in the same way that vertexes can have properties. For example you could do something like this (code follows TinkerPop's Blueprints):
Graph graph = new Neo4jGraph("/tmp/my_graph");
Vertex newton = graph.addVertex(null);
newton.setProperty("given_name", "Isaac");
newton.setProperty("surname", "Newton");
newton.setProperty("birth_year", 1643); // use Gregorian dates...
newton.setProperty("type", "PERSON");
Vertex calculus = graph.addVertex(null);
calculus.setProperty("type", "KNOWLEDGE");
Edge newton_calculus = graph.addEdge(null, newton, calculus, "DISCOVERED");
newton_calculus.setProperty("year", 1666);
Now, lets expand it a little bit and add in Liebniz:
Vertex liebniz = graph.addVertex(null);
liebniz.setProperty("given_name", "Gottfried");
liebniz.setProperty("surnam", "Liebniz");
liebniz.setProperty("birth_year", "1646");
liebniz.setProperty("type", "PERSON");
Edge liebniz_calculus = graph.addEdge(null, liebniz, calculus, "DISCOVERED");
liebniz_calculus.setProperty("year", 1674);
Adding in the books:
Vertex principia = graph.addVertex(null);
principia.setProperty("title", "Philosophiæ Naturalis Principia Mathematica");
principia.setProperty("year_first_published", 1687);
Edge newton_principia = graph.addEdge(null, newton, principia, "AUTHOR");
Edge principia_calculus = graph.addEdge(null, principia, calculus, "SUBJECT");
To find out all of the books that Newton wrote on things he discovered we can construct a graph traversal. We start with Newton, follow the out links from him to things he discovered, then traverse links in reverse to get books on that subject and again go reverse on a link to get the author. If the author is Newton then go back to the book and return the result. This query is written in Gremlin, a Groovy based domain specific language for graph traversals:
newton.out("DISCOVERED").in("SUBJECT").as("book").in("AUTHOR").filter{it == newton}.back("book").title.unique()
Thus, I hope I've shown a little how a clever traversal can be used to avoid issues with creating intermediate nodes to represent edges. In a small database it won't matter much, but in a large database you're going to suffer large performance hits doing that.
Yes, it is sad that you can't associate edges with other edges in a graph, but that's a limitation of the data structures of these databases. Sometimes it makes sense to make everything a node, for example, in Mediator/CVT a performance has a bit more concreteness too it. Individuals may wish address only Tom Cruise's performance in "The Last Samurai" in a review. However, for most graph databases I've found that application of some graph traversals can get me what I want out of the database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: How would I redirect a non-php file's URL, without editing the .htaccess file? So basically I need a way to take an exe file on my server and make a php function to toggle it's availability. I do not want to just rename, move, or delete the file, but redirect to a page explaining the file is temporarily unavailable.
I know how to set a permanent redirect in .htaccess but this doesn't solve my problem since I'd like to make this automated via a php script....
Any suggestions? Thanks in advance.
A: You won't be able to do this with PHP alone unless your web server is set up to process requests for .exe files as .php, or you add a rule in .htaccess. If the file exists, and .htaccess/server settings allow direct access to files, there's nothing PHP can do to stop access to it.
A: Honestly the simplest way would probably be to write a PHP script that edits your .htaccess file and reloads it in apache. You could just run that script whenever you needed to enable/disable access.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Convert javascript function to jQuery How do I convert this javascript selected to jQuery? I need to select a button class rather than an ID, and I understand the easiest way to do this is jQuery.
var playButton1 = document.getElementById("playButton1");
playButton1.onclick = function() {
var ta = document.getElementById("playButton1");
document['player'].receiveText1(ta.value);
ta.value = ""
};
A: Try the following. You didn't specify the new class name so I assumed it was "playButton".
$(document).ready(function() {
$('.playButton').click(function() {
document['player'].receiveText1(this.value);
this.value = "";
});
});
A: var playButton1 = $("playButton1");
playButton1.click(function() {
var ta = $("playButton1");
document['player'].receiveText1(ta.val());
ta.val("");
});
A: var playButton1 = $("#playButton1");
playButton1.onclick = function() {
var ta = playButton1.val();
document['player'].receiveText1(ta);
playButton1.val('');
};
A: $('#playButton1').click(function(){
document['player'].receiveText1($('playerButton1').val());
$('playerButton1').val('');
});
A: <button class="playButton" value="1">Play 1</button>
<button class="playButton" value="2">Play 2</button>
<script type="text/javascript">
$(function(){
$(".playButton").click(function(){
document['player'].receiveText1($(this).val());
});
});
</script>
A: $('#Class').click(function(e){
document['player'].receiveText1(event.target.value);
event.target.value = ""
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem with SQL query. Need to distinct my results I got table with my conversations, and i need to list alle conversation as topics. So if I'm the sender or the receiver, it should list it as one conversation. So between 2 users, it doesn't matter which role they got.
So if I got:
1, me, mom, "hello mom, I'm good. How are you?", 1, 23/09-2011
2, mom, me, "hello son, how are you?", 1, 22/09-2011
3, me, dad, "hello dad, how are you?", 1, 20/09-2011
I want to show it like this:
between You and Mom - Hello mom... - 23/09-2011 - 2 messeges
between You and Dad - Hello dad... - 20/09-2011 - 1 message
I can't seem to figure out the query. Something with DISTINCT maybe.
I hope you guys can help me out :)
Update
CREATE TABLE IF NOT EXISTS `fisk_beskeder` (
`id` int(11) NOT NULL auto_increment,
`fra` int(11) NOT NULL,
`til` int(11) NOT NULL,
`dato` varchar(50) NOT NULL,
`set` int(11) NOT NULL default '0',
`besked` text NOT NULL,
`svar` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
PHP
$sql = mysql_query(
"SELECT `fra`, `til`, `besked`, `dato`, `set`, `id`
FROM fisk_beskeder
WHERE til = ".$userid."
OR fra = ".$userid."
ORDER BY id DESC")
or die(mysql_error());
Update
Okay, it's working now. Only thing i need is to get the newest data from the group.
SELECT count(id), `id`, `fra`, if(a.fra = $cfg_brugerid, a.til, a.fra) AS other, `til`, `besked`, `dato`, `set`
FROM fisk_beskeder a
WHERE fra = $cfg_brugerid OR til = $cfg_brugerid
GROUP BY other
ORDER BY a.id DESC
A: Something like.
SELECT COUNT(a.msg), a.msg, a.date
FROM table a, table b
WHERE a.from = b.from
AND a.to != b.to
GROUP BY a.from
A: Maybe this:
SELECT COUNT(msg), msg, a.date, if(a.from ='me', a.to , a.from) as otherPerson
FROM table a
WHERE a.from = 'me' or a.to = 'me'
GROUP BY otherPerson
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: text formattation of "description" array variable in graph protocol On the website I am developing, I'm using a function that get information about events taken from a group on facebook.
I noticed that using the graph protocol, the text contained in the "description" of the created array , there are strange characters like "\ u00b" or "\ n" for new lines.
How can I do to display the content formatted correctly?
thanks in advance
Piero
A: It is called unicode_decode ( http://webarto.com/83/php-unicode_decode-5.3 ), it will come out in PHP6 until then...
function unicode_decode($string) {
$string = preg_replace_callback('#\\\\u([0-9a-f]{4})#ism',
create_function('$matches', 'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'),
$string);
return $string;
}
Raska Top\u010dagi\u0107
Raska Topčagić
If you are not using PHP, sorry...
Better solution:
echo json_decode('Raska Top\u010dagi\u0107'); # Raska Topčagić
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Byte-for-byte copies of types in C++11? The C++11 standard guarantees that byte-for-byte copies are always valid for POD types. But what about certain trivial types?
Here's an example:
struct trivial
{
int x;
int y;
trivial(int i) : x(2 * i) { std::cout << "Constructed." << std::endl; }
};
If I were to copy this struct, byte-for-byte, is it guaranteed to copy properly, even though it isn't technically a POD? When is the line drawn as to when it's not okay to byte-copy an object?
A: Yes, it is guaranteed to copy properly.
Quoting the FDIS, §3.9/2:
For any object (other than a base-class subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes making up the object can be copied into an array of char or unsigned char. If the content of the array of char or unsigned char is copied back into the object, the object shall subsequently hold its original value.
And §3.9/3:
For any trivially copyable type T, if two pointers to T point to distinct T objects obj1 and obj2, where neither obj1 nor obj2 is a base-class subobject, if the underlying bytes making up obj1 are copied into obj2, obj2 shall subsequently hold the same value as obj1.
So the requirements you're asking about are, §3.9/9:
Arithmetic types, enumeration types, pointer types, pointer to member types, std::nullptr_t, and cv-qualified versions of these types are collectively called scalar types. Scalar types, POD classes, arrays of such types and cv-qualified versions of these types are collectively called POD types. Scalar types, trivially copyable class types, arrays of such types, and cv-qualified versions of these types are collectively called trivially copyable types.
And §9/6:
A trivially copyable class is a class that:
*
*has no non-trivial copy constructors,
*has no non-trivial move constructors,
*has no non-trivial copy assignment operators,
*has no non-trivial move assignment operators, and
*has a trivial destructor.
A: C++11 broke the definition of POD types into more useful categories, specifically 'trivial' and 'standard layout'. Your example is standard layout, and trivally copyable, although the constructor prevents it from being fully trivial. Trivially copyable types are guaranteed to be safely byte-wise copied:
For any object (other than a base-class subobject) of trivially
copyable type T, whether or not the object holds a valid value of type
T, the underlying bytes (1.7) making up the object can be copied into
an array of char or unsigned char.40 If the content of the array of
char or unsigned char is copied back into the object, the object shall
subsequently hold its original value.
So no, POD status is not required to be safely copied that way, but it is possible to identify the subset of non-POD types that can be.
A: If the standard states it's only defined for POD types (I haven't examined the C++11 standard in detail yet so I don't know if your contention is correct or not (a)) and you do it for a non-POD type, it's not defined behaviour. Period.
It may work, on some implementations, in some environments at certain times of the day, when the planets are aligned. It may work the vast majority of times. That still doesn't make it a good idea if you value portability.
(a) After more investigation, it appears your particular case is okay. Section 3.9/3 of the standard (n3242 draft, but I'd be surprised if it had changed much from this late draft) states:
For any trivially copyable type T, if two pointers to T point to distinct T objects obj1 and obj2 where neither obj1 nor obj2 is a base-class subobject, if the underlying bytes making up obj1 are copied into obj2, obj2 shall subsequently hold the same value as obj1.
Section 9 defines (at a high level) what "trivially copyable" means:
A trivially copyable class is a class that:
- has no non-trivial copy constructors (12.8),
- has no non-trivial move constructors (12.8),
- has no non-trivial copy assignment operators (13.5.3, 12.8),
- has no non-trivial move assignment operators (13.5.3, 12.8), and
- has a trivial destructor (12.4).
with the referenced sections going into more detail on each area, 12.8 for copying and moving class objects and 13.5.3 for assignments.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Remove brackets [] from a list set to a textview? I am parsing content using the following code with jsoup.
try{
Elements divElements = jsDoc.getElementsByTag("div");
for(Element divElement : divElements){
if(divElement.attr("class").equals("article-content")){
textList.add(divElement.text());
text = textList.toString();
}
}
}
catch(Exception e){
System.out.println("Couldnt get content");
}
The only problem is the content is returned with brackets around it [] like that.
Im guessing it is becaue of the list i am setting it to. How can i remove these?
A: Using regex to replace the leading and trailing brackets, String.replace() doesn't work for the edge cases that the list's content contains brackets.
String text = textList.toString().replaceAll("(^\\[|\\]$)", "");
A: Replace:
text = textList.toString();
with:
text = textList.toString().replace("[", "").replace("]", "");
A: Yes, its because of the List. You have to Options:
Subclass whatever TextList is, and override toString()
or
String temp = textList.toString();
text = temp.subString(1, temp.size() -2);
A: For most objects, the toString() method is not intended to be used for display, but usually debugging. This is because the toString() method generally doesn't have a specific format and could vary depending on the particular class used. For example, a LinkedList and ArrayList could return different values from toString(). It's unlikely, but its something you should avoid relying on. Of course, if the object represents actual text (String, StringBuilder, CharSequence), the above doesn't apply.
Also, you are creating and assigning the string multiple times in the for loop. Instead, you should only create the string after the for loop is done.
To create the string you can roll your own or use a library like Apache commons lang, which has a StringUtils.join() utility method.
If you roll your own, it might look something like this:
Elements divElements = jsDoc.getElementsByTag("div");
Iterator<Element> iterator = divElements.iterator();
StringBuilder builder = new StringBuilder();
while (iterator.hasNext()){
Element divElement = iterator.next()
if (divElement.attr("class").equals("article-content")){
builder.append(divElement.text());
if (iterator.hasNext()) {
builder.append(", ");
}
}
}
text = builder.toString();
A: Implement your own method to create the String you need using iteration and StringBuffer. It is not a good practice to replace parentheses or substring such output.
A: You may override toString() method.
Set example:
class SetPrinter<E> extends HashSet<E> {
public SetPrinter(Set<E> set) {
super(set);
}
@Override
public String toString() {
Iterator<E> i = iterator();
if (!i.hasNext()) {
return "";
}
StringBuilder sb = new StringBuilder();
for (; ; ) {
E e = i.next();
sb.append(e == this ? "(this Collection)" : e);
if (!i.hasNext())
return sb.toString();
sb.append(",");
}
}
}
Use:
new SetPrinter(SetToPrint).toString();
A: Simply use like this. It is working for me.
Text(text.toString().replaceAll('[', "").replaceAll(']', ''));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Closure Library or YUI 3 I'm architecting an enterprise web application using python, django. My final decision to make is which javascript library to use. I'm thinking about using Google's closure library or YUI3. Most of the development, I've used jQuery.I can code fast with jQuery but doesn't seem right for enterprise use.
YUI 3 seems pretty good. It includes most widgets I want to use, but Closure library does almost the same. Better offer with Closure library is they have Closure Compiler, but seems like Closure requires to write much more code than YUI 3. Documentation from YUI 3 is pretty good too.
The application will be for both web and mobile devices, so the library should not break in mobile device such as Android or iPhone.
If you were me, what decision would you make?
A: Disclamer
I mostly draw on comment about jQuery in enterprise environment and since I lack experience in YUI, I can not give any conscious advice for [not] using it over Closure.
But in lack of any other answers I'll share my experience with Closure.
Closure library
As for Closure library, which I have been using for last few projects but am, by no means, expert at it, I can say only good things.
Library provides the core components you need when building any kind of UI. But, unlike jQuery, it does not come with trillions of "ready-to-deploy" plugin-in scripts, or as some would say, with no batteries included.
It's got basic events, controls, xhr, dialogs, form components etc., and by my account the most important thing, namespaces (or at least something looking like them...).
With this you can create your own custom UIs limited only by your imagination and the power of JavaScript (and JS is very powerful language even if it does have its own annoyances).
And with help of Closure compiler, which not only minifies the code but it excludes all unused code, does type checking, gives warnings useful for debuging and so forth, it looks like solid foundation for building large applications ground up by teams of any size.
In my opinion, main reason for using Closure over jQuery in enterprise projects is consistency. Plugins are awsome but they tend to include inconsistency at all levels, either programming practices, visual styles and structure, performance, usage, you name it. Removing these small inconsistencies on large project can waste lot of time.
So in conclusion, if you have large project needing custom UI and a lot of flexibility Closure is the Right tool for the job. And with "namespaces" it even feels all Pythonish.
P.S. We also use Django on server side.
A: You have touched on most of the important aspects here, the type checking, minification, namespaces, but I would like to add a few more. Alongside is the templating sollution they offer, which is not only super fast and has full internationalisation support, this mixes in and compresses with the library. It also compiles down to java code so you can render on both the server and the client from the same template.
Then there is the component architecture which has a complete livecycle, seperates renderers from components, (if you are familiar with swing or flex you will get the idea), it has two models, one is client side rendering and the other is decoration which plays beautifully alongside the server side rendering.
The testing sollutions are well defined and now the
We have thousands upon thousands of lines of javascript and without closure it would have been an unmaintainable mess IMO.
A: I'd go with YUI 3. Especially if the only reason you're considering Google's Closure is the compiler. As this works well in YUI 3, with much better compression than the YUI compresser. I'm sure it doesn't do as good a job as it could with Closure code, but that's pretty hard to test.
The modular framework in YUI 3 is awesome, and there is enough sugar to give you a tooth ache without being too heavy. Yahoo use it for all their sites, and they have a strong emphasis on performance (so it can't be all bad).
A: In the tests I made, Google Advanced Compress is the better, and after the the Yahoo! YUI Compressor. You can make the tests here:
http://jsperf.com/closure-vs-yui
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Can't load related entities on the client using RIA Services I am having trouble getting related entities to be loaded on the client using RIA Services and EF 4.1 with Silverlight.
I'm currently using the Include() method on my DbDomainService with an Expression parameter and am finding that when stepping through my service the related entities are loaded just fine. However, when the Queryable results are returned to the client NO related entities are loaded - they are null. All of my entities are marked with the [DataMember] attribute so I have assumed that it isn't a serialization issue. Moreover, my DbDomainService query method is marked with the [Query] attribute.
I was wondering if there is anything specific that has to be set up on the client when using RIA Services with EF 4.1 code first? I must be missing something, but I'm not sure what.
Any help would be appreciated.
Thanks,
sfx
A: While you may have used the .Include() in your service call, you also have to add the [Include] attribute in the metadata class that is also created.
The .Include() statement tells EF to generate the SQL necessary to retrieve the data, while the Include attribute tells WCF RIA Services to make sure the Entity Class is also created on the client.
Once the data arrives at the client, it needs to know what type of structure to put it in as well.
HTH
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: NSTableView hit tab to jump from row to row while editing I've got an NSTableView. While editing, if I hit tab it automatically jumps me to the next column. This is fantastic, but when I'm editing the field in the last column and I hit tab, I'd like focus to jump to the first column of the NEXT row.
Any suggestions?
Thanks to Michael for the starting code, it was very close to what ended up working! Here is the final code that I used, hope it will be helpful to someone else:
- (void) textDidEndEditing: (NSNotification *) notification {
NSInteger editedColumn = [self editedColumn];
NSInteger editedRow = [self editedRow];
NSInteger lastColumn = [[self tableColumns] count] - 1;
NSDictionary *userInfo = [notification userInfo];
int textMovement = [[userInfo valueForKey:@"NSTextMovement"] intValue];
[super textDidEndEditing: notification];
if ( (editedColumn == lastColumn)
&& (textMovement == NSTabTextMovement)
&& editedRow < ([self numberOfRows] - 1)
)
{
// the tab key was hit while in the last column,
// so go to the left most cell in the next row
[self selectRowIndexes:[NSIndexSet indexSetWithIndex:(editedRow+1)] byExtendingSelection:NO];
[self editColumn: 0 row: (editedRow + 1) withEvent: nil select: YES];
}
}
A: You can do this without subclassing by implementing control:textView:doCommandBySelector:
-(BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector {
if(commandSelector == @selector(insertTab:) ) {
// Do your thing
return YES;
} else {
return NO;
}
}
(The NSTableViewDelegate implements the NSControlTextEditingDelegate protocol, which is where this method is defined)
This method responds to the actual keypress, so you're not constrained to the textDidEndEditing method, which only works for text cells.
A: Subclass UITableView and add code to catch the textDidEndEditing call.
You can then decide what to do based on something like this:
- (void) textDidEndEditing: (NSNotification *) notification
{
NSDictionary *userInfo = [notification userInfo];
int textMovement = [[userInfo valueForKey:@"NSTextMovement"] intValue];
if ([self selectedColumn] == ([[self tableColumns] count] - 1))
(textMovement == NSTabTextMovement)
{
// the tab key was hit while in the last column,
// so go to the left most cell in the next row
[yourTableView editColumn: 0 row: ([self selectedRow] + 1) withEvent: nil select: YES];
}
[super textDidEndEditing: notification];
[[self window] makeFirstResponder:self];
} // textDidEndEditing
This code isn't tested... no warranties... etc. And you might need to move that [super textDidEndEditing:] call for the tab-in-the-right-most-cell case. But hopefully this will help you to the finish line. Let me know!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Android Socket High CPU usage I did a client/server(android/pc) and it seems that network usage from client uses a lot of CPU. Like to receive only 4k-5k from network, the cpu rises to 33 milliseconds. The cpu can be higher than 90-100 milliseconds if data is higher like ~32k.
First, I've tried the client(network part) in java version and after in c and the problem is still there.
I profiled the server part that send data and it uses about 0 millisecond.
Some details:
*
*TCP connection.
*The client connects to the server, client sends request, server sends
data (chunk of 4-10k), client send request, server sends...
*Network part is threaded.
*Get data with (recv or recv/select).
*Smart Phone: Nexus one.
*Tested in profiler mode (only network part and display fps/milliseconds).
*Tested in Wifi (computer, phone, network are close).
Let me know if you have any suggestions or questions.
Thanks.
A: Are you using BufferedOutputStream on Android side to write the data? If not, it writes it byte by byte, which would explain the high CPU usage.
If this is not the case, please add some source code to the question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: FTP download is not secure enough - password shows up in fiddler My application is downloading a client from my server via FTP. I must use FTP in this case as I made the file on my server forbidden from public use; thus, the only way to download the file is as an administrator which I can do by supplying an username and password to the FTP client. The problem with doing this, though, is that by using Fiddler I can "sniff" out the password sent to the FTP client from c#.
Code:
var downloadFileRequest = (FtpWebRequest)WebRequest.Create("ftp://" + Public.ftp_host + "//" + fileName);
downloadFileRequest.Credentials = new NetworkCredential(Public.ftp_username, Public.ftp_password);
downloadFileRequest.Method = WebRequestMethods.Ftp.DownloadFile;
downloadFileRequest.UseBinary = true;
ServicePoint sp = downloadFileRequest.ServicePoint;
sp.ConnectionLimit = 2;
var downloadResponse = (FtpWebResponse)downloadFileRequest.GetResponse();
Stream downloadStream = downloadResponse.GetResponseStream();
Is there some way to download files via FTP without exposing this password?
Thank you,
Evan
A: Nope. FTP sends credentials plainly. You have to use SFTP or something equivalent.
A: No. But can you configure an account that's only used for FTP and is not an administrator, to at least limit your exposure if someone gets the credentials?
FTP has no secure authentication mechanism. You'd need to use something else (SFTP or SCP, or HTTPS).
A: If you can configure the FTP server yourself or install another one, there is a protocol called FTPS, which uses TLS/SSL to secure the connection over FTP. Wikipedia has a list of FTP server software with capabilities shown. It may be easier to HTTPS as suggested.
Any connection that is not encrypted will send the passwords in the clear.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to make wp7 map control zoom buttons easier to see with windows phone 7 i am using teh bing map control. i have it working just fine. however, the zoom buttons (+,-) are at the bottom of the page and difficult to see.
The buttons have black border with black text. They are easy to see on a light map background, but with black background they are in essence hidden.
Does anyone have an idea on how to make them easier to see?
A: As invalidusername said you can use the pinching to zoom in and out and it is probably a better way to do it. But in my case I haven't a device or touch screen so needed to use buttons in this way to test my map.
Rather than using the built-in zoom buttons I looked at the sample code from this tutorial which has icons for zoom in/out and data bound them to the zooming of the map. Adapting it to my needs. It works pretty well:
http://msdn.microsoft.com/en-us/wp7trainingcourse_usingbingmapslab_topic2
You can change the positioning/images etc.
As per DanielBallinger's comment the link above seems to no longer work. The following does:
Bing Maps Tutorial
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CakePHP: cakeError and exit Is it advisable to perform an exit; or return; after throwing a cakeError?
if (//successful operation)
{
echo 'YAY';
}
else
{
$this->cakeError('error404');
exit; // is it necessary?
}
A: Looking at the source code for ErrorHandler::error404(), at the end it calls Object::_stop() and its source code is
function _stop($status = 0) {
exit($status);
}
In other words no, you don't have to exit after calling cakeError() because it already does so.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: MySQL Query - Join troubles... again? I'm hoping somebody will be able to help me with a query I'm stuck on.
I have multiple input search form for a photos database. One text box 'searchWords' is to search my 'photoSearch' table and the other text box 'specificPeople' searches the 'people' table, to search for specific people.
For example, a user might search for "Dorchester Hotel London" in box 1 and "Brad Pitt" in box 2.
This is what I am trying but it is only bring back results for "Dorchester Hotel London", it is ignoring my people search:
SELECT photoSearch.photoID, Left(photoSearch.caption,25), photoSearch.allPeople, photoSearch.allKeywords
FROM photoSearch
LEFT JOIN ( photoPeople INNER JOIN people ON photoPeople.peopleID = people.peopleID)
ON photoSearch.photoID = photoPeople.photoID AND people.people IN ('kate moss','jamie hince')
WHERE MATCH (caption, allPeople, allKeywords) AGAINST ('+dorchester +hotel' IN BOOLEAN MODE)
AND
photoSearch.dateCreated BETWEEN '2011-07-21' AND '2011-10-23'
ORDER BY photoSearch.dateCreated
If I take the JOIN away, the fulltext search is perfect. My table schema is a little like this:
**photoSearch**
photoID INT / AUTO / INDEX
caption VARCHAR(2500) / FULLTEXT
allPeople VARCHAR(300) / FULLTEXT
allKeywords VARCHAR(300) / FULLTEXT
dateCreated DATETIME / INDEX
**photoPeople**
photoID INT / INDEX
peopleID INT / INDEX
**people**
peopleID INT / INDEX
people VARCHAR(100) / INDEX
Is this fixable or am I totally doing the wrong thing? If so, could somebody show me what I'm meant to be doing :)
A: You are doing a LEFT JOIN which means it will return results for the left table (photoSearch) even if the join condition fails,
Change LEFT JOIN to JOIN.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: AVAssestReader stop Audio Callbacks So I setup an Audio session
AudioSessionInitialize(NULL, NULL, NULL, NULL);
AudioSessionSetActive(true);
UInt32 audioCategory = kAudioSessionCategory_MediaPlayback; //for output audio
OSStatus tErr = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,sizeof(audioCategory),&audioCategory);
Then setup either an AudioQueue or RemoteIO setup to play back some audio straight from a file.
AudioQueueStart(mQueue, NULL);
Once my audio is playing I can see the 'Play Icon' in the status bar of my app. I next setup an AVAssetReader.
AVAssetTrack* songTrack = [songURL.tracks objectAtIndex:0];
NSDictionary* outputSettingsDict = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithInt:kAudioFormatLinearPCM],AVFormatIDKey,
// [NSNumber numberWithInt:AUDIO_SAMPLE_RATE],AVSampleRateKey, /*Not Supported*/
// [NSNumber numberWithInt: 2],AVNumberOfChannelsKey, /*Not Supported*/
[NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
[NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
[NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
[NSNumber numberWithBool:NO],AVLinearPCMIsNonInterleaved,
nil];
NSError* error = nil;
AVAssetReader* reader = [[AVAssetReader alloc] initWithAsset:songURL error:&error];
// {
// AVAssetReaderTrackOutput* output = [[AVAssetReaderTrackOutput alloc] initWithTrack:songTrack outputSettings:outputSettingsDict];
// [reader addOutput:output];
// [output release];
// }
{
AVAssetReaderAudioMixOutput * readaudiofile = [AVAssetReaderAudioMixOutput assetReaderAudioMixOutputWithAudioTracks:(songURL.tracks) audioSettings:outputSettingsDict];
[reader addOutput:readaudiofile];
[readaudiofile release];
}
return reader;
and when I called [reader startReading] the Audio stops playing. In both the RemoteIO and AudioQueue case the callback stops getting called.
If I add the mixing option:
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof (UInt32), &(UInt32) {0});
Then the 'Play Icon' no longer appears when the audio after AudioQueueStart is called. I am also locked out of other features since the phone doesn't view me as the primary audio source.
Does anyone know a way I can use the AVAssetReader and still remain the Primary audio source?
A: As of iOS 5 this has been fixed. It still does not work in iOS 4 or below. MixWithOthers is not needed (can be set to false) and the AudioQueue/RemoteIO will continue to receive callbacks even if an AVAssetReader is reading.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to respond_to a json request with only the 20 recents objects? (rails) I wish to send to the client only the 20 recent Post objects.
How do i that?
I'm new to rails so ill appreciate your advice very much.
thanks.
A: Just do:
@posts = Post.all(:order => 'created_at desc', :limit => 20)
respond_to do |format|
format.json
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to remove an item from listbox with datasource set, using string in C# refferring to msdn link
how can I remove an item using string???
(I don't want to remove it by using selected index)
I want something like
USStates.Remove("Alabama","AL");
A: You can't change Items collection but you can change the DataSource (List or ArrayList).
First of all override GetHashCode() and Equals() methods in USState type.
public override int GetHashCode()
{
return myLongName.GetHashCode() + myShortName.GetHashCode();
}
public override bool Equals(object obj)
{
return GetHashCode() == obj.GetHashCode();
}
Now, you can remove an element,
listBox1.DataSource = null; // Set null so you can update DataSource
USStates.Remove(new USState("Wisconsin", "WI"));
listBox1.DataSource = USStates;
listBox1.DisplayMember = "LongName";
listBox1.ValueMember = "ShortName";
A: First of all, don't use an ArrayList, use a List. Then you can remove based on whatever the type T is,
list.Remove("whatever");
A: Updated: I assume you add a button that you can click to remove an item.
BindingList<USState> USStates;
public Form1()
{
InitializeComponent();
USStates = new BindingList<USState>();
USStates.Add(new USState("Alabama", "AL"));
USStates.Add(new USState("Washington", "WA"));
USStates.Add(new USState("West Virginia", "WV"));
USStates.Add(new USState("Wisconsin", "WI"));
USStates.Add(new USState("Wyoming", "WY"));
listBox1.DataSource = USStates;
listBox1.DisplayMember = "LongName";
listBox1.ValueMember = "ShortName";
}
private void button1_Click(object sender, EventArgs e)
{
var removeStates = (from state in USStates
where state.ShortName == "AL"
select state).ToList();
removeStates.ForEach( state => USStates.Remove(state) );
}
PS: I thought you're using WPF in my previous answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP cake subdomains session link problem? i have problem with php cake session and subdomains. I have setted all successfully right. When i try to go from
subdomain1.domain.com
to
subdomain2.domain.com
all works nicely when i put these browser url... problem comes when i try to make this with <a href=""> tag, on redirected subdomain i will recieve new session id.
I cant explain to my self how can be this possible, pure php script works fine but in php cake is this bug! thanks for any suggestion...
A: ok, i debug whole php cake session component and lib, i figure out 2 sollutions
*
*easier - set in core.php security level to low
Configure::write('Security.level', 'low');
*advanced - make new config file for sessions, like Ivo said, its in tutorial http://book.cakephp.org/view/1310/Sessions ,most important thing is set
ini_restore('session.referer_check');
because by default php cake check referrer, and if it goes not form same domain it will cause generating new SESSIONID
A: I don't think it's related with cake.
By default, PHP will give you a session for the domain.
*
*subdomain1.domain.com is a domain,
*subdomain2.domain.com is another domain
*domain.com is another different domain
*www.domain.com is another different domain
All thoses examples are 4 distincts domains, with their own session.
If you want to share the session between many (sub)domain, you can try to set the session.cookie_domain variable, like this;
ini_set("session.cookie_domain","domain.com") ;
A: Try using this instead:
http://book.cakephp.org/view/1310/Sessions
Follow the directions to create custom configuration for cake's session saving.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how do I render a specific view from an an urelated action? I need to render the view for controller=user action=profile from a
controller = b action =c
i.e. /b/c will render the same view as when I surf to /user/profile
How can this be achieved (except using include inside the view file) in Yii?
What code do I have to put in the controller?
A: To render which view is not decided by the controller or action id, you can modify it easily. Just change this line in your b controller c action:
$this->render('[path alias to your user/profile view]',array(
$model=>[your data provider]
));
You can check the manual to find how to make a path alias, here's an example:
application.views.user.profile
A: You can also use a "root view path" syntax to render any view file by starting with "//" like:
$this->render('//user/profile');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: YUI DataTable Button events lost after filtering I'm using a YUI2 DataTable.
Some of the rows of the tables have an icon button that when clicked on will popup additional details for the row.
I'm doing the following to define the panel which gets displayed with the additional information:
MyContainer.panel2 = new YAHOO.widget.Panel("popupPanel2",
{ width:"650px", visible:false, constraintoviewport:true, overflow:"auto" } );
MyContainer.panel2.render();
YAHOO.util.Event.addListener("showButton2", "click",
MyContainer.panel2.show, MyContainer.panel2, true);
So, everything works well with that. Then I added a button that when clicked on filters out some of the rows.
MyContainer.oPushButton1.onclick = function onButtonClickp(p_oEvent)
{
var filter_val = "xxx";
myDataTable.getDataSource().sendRequest(filter_val,
{success: myDataTable.onDataReturnInitializeTable},myDataTable);
}
This filters and redraws the table. But after doing that, the buttons on the remaining rows that should popup a panel no longer work.
Nothing happens when I click on the buttons.
I'm sure I've done something wrong, but I don't know what. The buttons and panels with the correct id's still seem to be available on the page.
Do I somehow have to re-enable the listener for the click event after the datatable redraw? I'm not sure where to look for trying to debug the failed listener.
A: I got this working by making a call to addListener again after resetting the data for the Datasource.
MyContainer.oPushButton1.onclick = function onButtonClickp(p_oEvent)
{
var filter_val = "xxx";
myDataTable.getDataSource().sendRequest(filter_val,
{success: myDataTable.onDataReturnInitializeTable},myDataTable);
YAHOO.util.Event.addListener("showButton2", "click",
MyContainer.panel2.show, MyContainer.panel2, true);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MS Access: Query Browser-like Functionality? Is there any way to execute an SQL statement, and view the returned result set in MS Access without having to go through any wizards, the query design view, or creating a form? Kind of like the functionality of the MySQL Query Browser. I usually like to test my queries before I embed them into some sort of GUI (when working with MySQL and Oracle previously). Working with Access has been a bit of an annoyance for me: there is a lot dependency on wizards, and even the "design" views has way too much hand-holding.
A: Change the view in the Query Designer to SQL View.
This will allow you to hand-craft your SQL without the need to use the inbuilt wizards.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I take subsets of a data frame according to a grouping in R? I have an aggregation problem which I cannot figure out how to perform efficiently in R.
Say I have the following data:
group1 <- c("a","b","a","a","b","c","c","c","c",
"c","a","a","a","b","b","b","b")
group2 <- c(1,2,3,4,1,3,5,6,5,4,1,2,3,4,3,2,1)
value <- c("apple","pear","orange","apple",
"banana","durian","lemon","lime",
"raspberry","durian","peach","nectarine",
"banana","lemon","guava","blackberry","grape")
df <- data.frame(group1,group2,value)
I am interested in sampling from the data frame df such that I randomly pick only a single row from each combination of factors group1 and group2.
As you can see, the results of table(df$group1,df$group2)
1 2 3 4 5 6
a 2 1 2 1 0 0
b 2 2 1 1 0 0
c 0 0 1 1 2 1
shows that some combinations are seen more than once, while others are never seen. For those that are seen more than once (e.g., group1="a" and group2=3), I want to randomly pick only one of the corresponding rows and return a new data frame that has only that subset of rows. That way, each possible combination of the grouping factors is represented by only a single row in the data frame.
One important aspect here is that my actual data sets can contain anywhere from 500,000 rows to >2,000,000 rows, so it is important to be mindful of performance.
I am relatively new at R, so I have been having trouble figuring out how to generate this structure correctly. One attempt looked like this (using the plyr package):
choice <- function(x,label) {
cbind(x[sample(1:nrow(x),1),],data.frame(state=label))
}
df <- ddply(df[,c("group1","group2","value")],
.(group1,group2),
pick_junc,
label="test")
Note that in this case, I am also adding an extra column to the data frame called "label" which is specified as an extra argument to the ddply function. However, I killed this after about 20 min.
In other cases, I have tried using aggregate or by or tapply, but I never know exactly what the specified function is getting, what it should return, or what to do with the result (especially for by).
I am trying to switch from python to R for exploratory data analysis, but this type of aggregation is crucial for me. In python, I can perform these operations very rapidly, but it is inconvenient as I have to generate a separate script/data structure for each different type of aggregation I want to perform.
I want to love R, so please help! Thanks!
Uri
A: Here is the plyr solution
set.seed(1234)
ddply(df, .(group1, group2), summarize,
value = value[sample(length(value), 1)])
This gives us
group1 group2 value
1 a 1 apple
2 a 2 nectarine
3 a 3 banana
4 a 4 apple
5 b 1 grape
6 b 2 blackberry
7 b 3 guava
8 b 4 lemon
9 c 3 durian
10 c 4 durian
11 c 5 raspberry
12 c 6 lime
EDIT. With a data frame that big, you are better off using data.table
library(data.table)
dt = data.table(df)
dt[,list(value = value[sample(length(value), 1)]),'group1, group2']
EDIT 2: Performance Comparison: Data Table is ~ 15 X faster
group1 = sample(letters, 1000000, replace = T)
group2 = sample(LETTERS, 1000000, replace = T)
value = runif(1000000, 0, 1)
df = data.frame(group1, group2, value)
dt = data.table(df)
f1_dtab = function() {
dt[,list(value = value[sample(length(value), 1)]),'group1, group2']
}
f2_plyr = function() {ddply(df, .(group1, group2), summarize, value =
value[sample(length(value), 1)])
}
f3_by = function() {do.call(rbind,by(df,list(grp1 = df$group1,grp2 = df$group2),
FUN = function(x){x[sample(nrow(x),1),]}))
}
library(rbenchmark)
benchmark(f1_dtab(), f2_plyr(), f3_by(), replications = 10)
test replications elapsed relative
f1_dtab() 10 4.764 1.00000
f2_plyr() 10 68.261 14.32851
f3_by() 10 67.369 14.14127
A: One more way:
with(df, tapply(value, list( group1, group2), length))
1 2 3 4 5 6
a 2 1 2 1 NA NA
b 2 2 1 1 NA NA
c NA NA 1 1 2 1
# Now use tapply to sample withing groups
# `resample` fn is from the sample help page:
# Avoids an error with sample when only one value in a group.
resample <- function(x, ...) x[sample.int(length(x), ...)]
#Create a row index
df$idx <- 1:NROW(df)
rowidxs <- with(df, unique( c( # the `c` function will make a matrix into a vector
tapply(idx, list( group1, group2),
function (x) resample(x, 1) ))))
rowidxs
# [1] 1 5 NA 12 16 NA 3 15 6 4 14 10 NA NA 7 NA NA 8
df[rowidxs[!is.na(rowidxs)] , ]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Core Data migration failure between NSPersistenceFrameworkVersions 251 and 358 I have what appears to be a bug with Core Data in OS X 10.7.1.
My data store (NSSQLiteStoreType) is not being automatically migrated correctly.
As a side note the exact same Core Data models are used by an iOS version of the app.
-> Here is what appears to be happening.
Up until the latest release everything has been working fine --
I have 14 revisions of the model -- model 13 has been shipping for quite some time without incident.
Recently I updated my app and added a new model so I am at 14 (this is the version now used in the shipping apps).
The iOS version works just fine when migrating from model 13 to 14 -- so no need to worry about that.
So rather then talking about OS X versions lets use NSPersistenceFrameworkVersions
NSPersistenceFrameworkVersions 251 being 10.6.8 and NSPersistenceFrameworkVersions 358 being 10.7.1
If we use like versions -- meaning model 13 version 251 and migrate to model 14 version 251 it works fine.
same is true if we use model 13 version 358 and migrate to model 14 version 358 it also works fine
Here is where it gets interesting
if we migrate model 13 version 358 to model 14 version 251 it still works fine
However migrating from model 13 version 251 to model 14 version 358 does not work
CoreData: error: (1) I/O error for database at blah. SQLite error code:1, 'no such column: FOK_REFLEXIVE'
Again this only happens when going from 10.6.8 (NSPersistenceFrameworkVersions 251) to 10.7.1 (NSPersistenceFrameworkVersions 358) all other permutations work just fine.
Here are the options used for migration that get passed to addPersistentStoreWithType.
// Allow inferred migration from the original version of the application.
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
One final thing, it appears if we only add attributes to model 14 the conversion will not break. It is only with the addition of an entity that will cause it to break.
Anybody else seeing this sort of problem. -thanks in advance.
A: To clarify,
use the unix sqlite3 tool with the path to the database file as a parameter.
You can get your app's db file by pulling it from the organizer's device pane under Applications for a device... You'll get a package.
type ".headers on" for table headers
Find tables (.tables command) for entities with references between objects
Where Z_1REFERENCEDSETOFOBJECTS is the name of your table.
select * from Z_1REFERENCEDSETOFOBJECTS limit 2
to find the names of the table's headers; then run the following for the tables that have the REFLEXIVE column:
ALTER TABLE Z_1REFERENCEDSETOFOBJECTS ADD FOK_REFLEXIVE integer
Push it back down.
A: This bug appears to have been fixed in iOS 5.1 and OSX 10.7.3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Performance userscript injecting code I have a question about userscripts. Is it faster to have this in before or after of the main function initiateFlasher?
if (typeof unsafeWindow !== 'undefined' && unsafeWindow.jQuery) {
initiateFlasher(unsafeWindow.jQuery);
} else {
function addScript(callback) {
var script = document.createElement('script');
script.text = '(' + callback.toString() + ')();';
document.body.appendChild(script);
}
addScript(initiateFlasher);
}
function initiateFlasher(arg) {}
A: The speed difference will be negligible.
But it's better form to define initiateFlasher() first. (When in doubt, use jslint.com.)
This is a good habit to get into because, even though a function declaration will work on most browsers before or after, function expressions or function constructors will not.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ajax loader gif won't display in IE 8 I've read a lot of posts on this but nothing the solved the problem.
I added an IMG tag (for an ajax loader gif) to the page with a style attribute (visibility:hidden), and added event handlers for 2 jQuery ajax events: ajaxStart (to show() the image) and ajaxStop (to hide() the image).
It works fine in Firefox but in IE 8 the image is never displayed. I put alerts in the ajaxStart and ajaxStop event handlers to confirm they fire, and they do.
I also tried a using a plain non-animated gif, but the results were the same: works fine in Firefox but nothing is ever displayed in IE 8.
A: instead of hiding it with css in the beginning use Jquery to hide it ( $("img").hide() ) on page load. and on ajax start use $("img").show() and for stop use $("img").hide() .
Edit
Also, if we all stop supporting IE8 (and all IE in general) the world will be a better place.
A: Just a note, jquery .slow changes css display value, not visibility.
Can I see some code?
Try some Why am I not able to show or hide in Internet Explorer 8, and how I can fix the problem? and see if one of those helps.
A: I recommend you to use image url instead of using hide/show.
you may use background-image: url(loader.gif);
and then change it to;
background-image: url();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java Possible FileChannel.map Bug So I'm trying to read in a very large file using a mapped FileChannel.
The file exceeds 2GB. A snippet of code is:
long fileSize = 0x8FFFFFFFL;
FileChannel fc = new RandomAccessFile("blah.huge", "rw").getChannel();
fc.map(FileChannel.MapMode.READ_WRITE, 0, fileSize);
This throws an error:
Exception in thread "main" java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE
at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:789)
FileChannel.map takes a long as the file size. So does this error make sense? Why would they not provide support for bigger files than that?
A: The native methods this function uses does take long values without reporting an error. You can call them using reflection. However you would have test whether they work for you on your system and using memory mapping this way, could confuse you more than be useful.
The best approach is to create an array of MappedByteBuffers, e.g. 1 GB each in size and create a wrapper which hides this ugliness.
While not technically a bug, it is BAD (Broken As Designed) Part of the reason this was done originally could be that 32-bit JVM could not support this, but I don't see why 64-bit JVMs still have this limit.
A: This is not a bug. FileChannel#map is documented as requiring a size argument not greater than Integer.MAX_VALUE, which makes sense as e.g. ByteBuffer#get takes an integer for its index parameter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do you programmatically create a System DSN using Powershell or .NET? How do you create a System DSN in the control panel on ones PC using Powershell or .NET?
A: This can be done with some registry edit. Refer this link:
http://derek858.blogspot.com/2010/02/create-32-bit-system-dsn-with.html
Note that for 64-bit you will be using HKEY_LOCAL_MACHINE\Software\Odbc\Odbc.ini\
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Android ArrayAdapter tell all other views to refresh themselves I need all of the other views in my arrayadapter to check their attributes and return to a default attribute at certain times
use case: listview items (a)(b)(c)(d) , when you touch (a) it's background turns black. This is done in the ontouchListener. But when you touch view (b) it's background turns black BUT (a)'s needs to turn back to the default which is not black
I dabbled around with recalling the arrayadapter at the end of the view.OnClickListener but the problem with this is that it also resets the scroll position of the view, so if this list was much longer - which it is - and user touched item (r) , then it would reset the list and put the user back at item (a) at the top
I was looking at notifydatasetchangedbut I am not sure how to use that and where it should work
insight appreciated
A: notifyDataSetChanged will do the job. You can call that at any time in your code and this will trigger the adapter to call getView for the visible list items again and so update their content. So basically the only thing you have to do is to update the list item states or information before calling that method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Passing variables on the same page
*
*The user enters a number and clicks submit. The number now shows up on the page.
*The user is then asked if they would like to double the number. They click yes.
*The doubled number now appears on the page.
I am having trouble with part 3. Is this possible using just PHP?
UPDATE: Thanks for your answers. This is my first ever PHP script, so I wasn't sure. I am going to research doing it with AJAX just now. I'm very curious to know why it is possible to get to part 2 if you can't get to part 3. Can anyone explain this or provide a link?
A: I think you're talking about session variables. At the top of the script add the following script to start a session for the current user:
session_start();
This will allow you to store variables in session $_SESSION which persists between requests. Use isset to check if a value is set in session.
A: <?php
$double = (isset($_REQUEST['do_double']) && $_REQUEST['do_double'] == '1') ? ($_REQUEST['number'] * 2) : '';
?>
<form method="get" action="?">
<input type="hidden" name="do_double" value="<?php echo isset($_REQUEST['number']) ?'1' : '0'; ?>" />
<input type="text" name="number" value="<?php echo isset($_REQUEST['number']) ? $_REQUEST['number'] : '';?>" />
<?php if ( ! isset($_REQUEST['number'])) { ?>
<input type="submit" value="submit" />
<?php } else { ?>
<input type="submit" value="Verdoppeln" />
<?php } ?>
</form>
<div id="number"><?php echo $double; ?></div>
A: Take the form ID using something like document.formname.inputname (http://www.quirksmode.org/js/forms.html) and then multiple by two then use javascript to show it where ever you want.
A: Asynchronous is required I think. Try these 2 reads:
the difference between synchronous and async: http://javascript.about.com/od/ajax/a/ajaxasyn.htm and
possible examples: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
A: This is really more of a comment than an answer, but SO limits comment length so here 'tis:
The misconception that a web page is synonymous with a PHP script appears to be common among novice PHP programmers. Really, a web page is an HTML document (with associated resources) that is sent from a web server to a web browser as part of an HTTP response. A single server-side script can generate many different kinds of web pages, and when processing HTML forms (as you seem to be doing) it is common for a single server-side script to do exactly that. In "web 1.0" applications, clicking on "Submit" (for example) typically causes the browser to make a new HTTP request (called a "page turn"), and the web server keeps track of what the user is doing across page turns by storing "state" either in a "session" (with an associated key included in the HTTP header of each HTTP request - and the HTTP response generated by the web "login") or in one or more HTTP parameters. The point is that each new HTTP request may be for the same script/URL on the server, but the behavior (and the appearance of the web page) will be different because the server is somehow tracking the state of the "workflow" across page turns.
Now if you really must avoid page turns, you can use Javascript to change the appearance/state of the page displayed by the browser without making the user click on a "Submit" button. And the XMLHTTPRequest mechanism (aka AJAX), which allows content to be fetched from the web server "behind the scenes" and change the state of the client-side document without the user doing anything, is typically used to achieve this. But is only really necessary if you're doing something rather different (e.g. scrolling a map or updating a stock ticker) than what you describe in your question, which looks like a perfect example of a "web 1.0" application workflow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Configuring Notepad++ to run php on localhost? I am trying to get the option Run->Launch With Firefox; to open the file I am currently viewing in Notepad++ at http://127.0.0.1:8080/currentfile.php, but instead it just opens to current file directory in Firefox.. I've tried to edit the shortcut xml file in the Notepad++ directory, I've shut Notepad++ down and edited the XML file with regular Notepad, and when I start Notepad++ back up it does not show the settings I entered.. How can I edit the settings to load localhost rather than the file directory in Firefox?
A: well two things
*
*you edited the wrong file , i'm guessing you are using windows vista/7 so real preferences files are in C:\Users\user\AppData\Roaming\Notepad++
*i don't think that notepad++ has a variable that contains only half of the address
meaning : the variable used now is $(FULL_CURRENT_PATH) == file:///C:/server/htdocs/pages/example.php
so you don't have any variable that contains only this pages/example.php.
so i think it's impossible
but just keep the page open and refresh after editing
A: If you save your PHP file directly into the www directory of WAMP (no subfolders), you can execute it by selecting the "Run..." command and pasting in this line:
firefox.exe "http://localhost/$(FILE_NAME)"
It's not great, but it will help you debug in a jiffy.
A: I know this is an older question but:
A. Gneady's solution works well. However, it may require some modification on Windows so the DOCUMENT_ROOT is replaced before the slash directions are replaced. Otherwise, no replacement will be made and the $file will output the same as the original path and file name, except with the slashes reversed.
Since I test in multiple browsers, I modified all of the pertinent rows in
C:\Users[username]\AppData\Roaming\Notepad++\shortcuts.xml:
<Command name="Launch in Firefox" Ctrl="yes" Alt="yes" Shift="yes" Key="88">firefox "http://localhost/redirect.php?file=$(FULL_CURRENT_PATH)"</Command>
<Command name="Launch in IE" Ctrl="yes" Alt="yes" Shift="yes" Key="73">iexplore "http://localhost/redirect.php?file=$(FULL_CURRENT_PATH)"</Command>
<Command name="Launch in Chrome" Ctrl="yes" Alt="yes" Shift="yes" Key="82">chrome "http://localhost/redirect.php?file=$(FULL_CURRENT_PATH)"</Command>
<Command name="Launch in Safari" Ctrl="yes" Alt="yes" Shift="yes" Key="70">safari "http://localhost/redirect.php?file=$(FULL_CURRENT_PATH)"</Command>
Then create the "redirect.php" file in the web root directory as follows:
<?php
$root = $_SERVER['DOCUMENT_ROOT'];
$file = $_GET['file'];
$file = str_replace($root, '', $file);
$file = str_replace('\\', '/', $file);
header("Location: http://localhost{$file}");
?>
A: Here's a quick and dirty fix to run php files even if they are in subdirectories inside your document root. In shortcuts.xml:
<Command name="Launch in Firefox" Ctrl="yes" Alt="yes" Shift="yes" Key="88">firefox "http://localhost/redirect.php?file=$(FULL_CURRENT_PATH)"</Command>
Then create the file "redirect.php" in your web server document root:
<?php
$root = $_SERVER['DOCUMENT_ROOT'];
$file = str_replace('\\', '/', $_GET['file']);
$file = str_replace($root, '', $file);
header("Location: http://localhost{$file}");
A: Was forgotten mark / after localhost
<?php
$root = $_SERVER['DOCUMENT_ROOT'];
$file = $_GET['file'];
$file = str_replace($root, '', $file);
$file = str_replace('\\', '/', $file);
# Was forgotten mark /
header("Location: http://localhost/{$file}");
?>
A: this is the code which worked for me:
<?php
$root = $_SERVER['DOCUMENT_ROOT'];
$file = $_GET['file'];
$file = str_replace($root, '', $file);
$file = str_replace('\\', '/', $file);
$file = str_replace('C:/wamp64/www/', '', $file); // Cause 'localhost' is equal to 'C:/wamp64/www/' in my case.
header("Location: http://localhost/{$file}");
?>
Thanks everybody..
A: If one is just looking to run HTML and/or PHP directly from Notepad++ in Chrome, or other, add:
<Command name="Launch in Chrome FOLDER" Ctrl="yes" Alt="yes" Shift="yes" Key="82">chrome "http://localhost/FOLDER/$(FILE_NAME)"</Command>
in Notepad++'s shortcuts.xml file (At least in Windows)
Change both instances of "FOLDER" to one's subfolder in the webserver's root folder. The root folder in XAMPP is htdocs. Of course, change "Chrome" to the browser one is desiring to open the file.
For instance, one of mine is:
<Command name="Launch in Chrome 7GENERALTEST" Ctrl="yes" Alt="yes" Shift="yes" Key="82">chrome "http://localhost/7GENERALTEST/$(FILE_NAME)"</Command>
"7GENERALTEST" the containing subfolder for my HTML and PHP files IN development.
One can then duplicate and modify the above for additional browsers and/or folders, say, Firefox, or the folder "7GENERALTEST2", etc.
A: To fix this problem just have Notepad++ open to a redirect file on your webserver. For instance....
Line in shortcuts.xml:
<Command name="Launch in Chrome" Ctrl="yes" Alt="yes" Shift="yes" Key="88">
chrome http://localhost/redirect.php?path=$(FULL_CURRENT_PATH)</Command>
Now your Redirect.php file:
if (!empty($_GET['path'])) {
$path = str_replace($_SERVER['DOCUMENT_ROOT'], '', $_GET['path']);
$redir = 'http://localhost' . $path;
header("Location:$redir");
}
Now any page that you run from any directory on your webserver will automatically open like it should. & obviously you can place the redirect.php anywhere on your localhost webserver it doesn't have to be in your root "htdocs" folder if that bothers you. hide it in a config dir or something where you keep your db link file or your head/foot files, etc..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Global Facebook login session accessible for all activities Hello everyone!
Im currently developing an Android Application for mobiles using the official Facebook SDK. The first screen on my application is the LoginActivity. That activity is bringing up an Facebook login dialog, were the user can enter his facebook username and password and then press the login button. I think you know which dialog im talking about, i bet you have seen it somewhere.
When the user are logging to Facebook using that dialog, theres a Facebook session which are set to true, exactly as it should be. BUT, I found out that this session is only true if you are in the LoginActivity. If the user makes an successfull login to Facebook the user are moved to another Activity by this code:
private class LoginDialogListener implements DialogListener {
@Override
public void onComplete(Bundle values) {
Intent intent = new Intent().setClass(LoginActivity.this, LocationActivity.class);
startActivity(intent);
}
And when the user are moved to the new activity in this case LocationActivity,
the session is still true but only for the LoginActivity. I want the session to be global and be true for the whole application and all activities as soon as the user are logging in.
Here is some code from LoginActivity, i hope this will make your guys to understand it all better, i bet if i post the whole activity no one would read it.
public class LoginActivity extends Activity {
public static final String APP_ID = "123123123123123";
public static final String TAG = "FACEBOOK CONNECT";
private Facebook mFacebook;
private AsyncFacebookRunner mAsyncRunner;
private static final String[] PERMS = new String[] { "user_events" };
private Handler mHandler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFacebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
}
...
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case FacebookCon.LOGIN:
if (mFacebook.isSessionValid()) {
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(
mFacebook);
asyncRunner.logout(this, new LogoutRequestListener());
} else {
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
break;
...
private class LogoutRequestListener implements RequestListener {
@Override
public void onComplete(String response, Object state) {
// Dispatch on its own thread
mHandler.post(new Runnable() {
public void run() {
}
});
}
A friend told me that i should make a "ApplicationController", i did not really understand what that were but he said that class should extend the whole application and all the variabels in the ApplicationController would be global for the whole application, and that's what i would like to do with the loginsession so it won't get lose when changing activities. But i don't know how to make this changes in my Application so i would like to have some help with this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I can't change the default Python version from Apple supplied 2.7.2 to 3.2.2 (OS10.7) in Lion, have installed python 3.2.2 from python.org. It comes with a terminal command that is supposed to move this version of python earlier by updating my shell profile. When i run it, and then check my default python in Terminal, it still says 2.7.2 which is the Apple supplied one.
Do I need to run the command with sudo to get it to change the default python to 3.2.2?
I've also tried the VERSIONER method but it doesn't work.
A: For Python 3 interpreters, you must enter python3 not python.
$ python -V
Python 2.7.2
$ python3 -V
Python 3.2.2
For more background on the current recommendation that python refer to a version of Python 2 and python3 refer to a version of Python 3, see the draft PEP 394 - The "python" Command on Unix-Like Systems.
A: Unfamiliar with osX, but as several system applications might depend on a certain python version, it might be a bad idea to swap the default.
One alternative that might suite your needs is to use pythonbrew, it allows you to have several python versions side by side and lets you set a default version on a user to user basis, without having to meddle with your system python, among other things. It is the equivalent of RVM for those who are familiar with ruby, or a sort of virtualenv for python interpreters. One big advantage is that it allows you to easily install and use the exact python versions you need independently from what is available in your operating system.
Some examples:
Install a python interpreter:
pythonbrew install 2.7.2
Permanently use the specified python (for current user):
pythonbrew switch 2.7.2
pythonbrew switch 3.2
Use the specified python in current shell:
pythonbrew use 2.7.2
Runs a named python file against specified and/or all pythons:
pythonbrew py test.py
pythonbrew py -v test.py # Show verbose output
pythonbrew py -p 2.7.2 -p 3.2 test.py # Use the specified pythons
The only downside of pythonbrew, is the need of a compiler and header files, and that an install can take a bit of time, as it compiles from source.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Adding element before a div with title attribute containing content of the div using JQuery I have:
<li class="ingredient">
<div>
<span class="amount">1 lb</span>
<span class="name">asparagus</span>
</div>
i want to use jQuery to get:
<li class="ingredient">
<img class="myImage" title="Yes!!! asparagus" src="/white2x2.gif">
<div>
<span class="amount">1 lb</span>
<span class="name">asparagus</span>
</div>
so far I got:
$(".ingredient div").before("<class='myImage' src="/white2x2.gif' />");
but how do I get the title in there. Note that there is lots of these on the page and I want the title to represent the element.
Many thanks!
A: based on your comments, this should do it for you.
$('.ingredient div').each(function() {
var name = $(this).find('.name').text();
$(this).before($('<img />').attr({class:'myimage', src:'/white2x2.gif',title:name}));
});
here's a jsfiddle
A: Try:
var newDiv = $("<img />").attr('src','/white2x2.gif').attr('class','myImage').attr('title','Yes!!! asparagus');
$(".ingredient div").before(newDiv);
A: If you're trying to use the text in your span as the title:
var name = $('.ingredient').find('.name').text();
$('.ingredient div').before($('<img />').attr('class','myImage').attr('src','/white2x2.gif').attr('title', name);
A: You can use jQuery .prepend():
$(document).ready(function(){
$.each($(document).find("li.igredient"), function(){
img_title = $(this).find('.name').text();
$(this).prepend("<img class='myImage' src='/white2x2.gif' title='" + img_title + "' />");
});
});
http://jsfiddle.net/KHFRh
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Flash CS5.5 Library & Flash Builder 4.5 workflow Because of intricate animations for an iOS project, I'm kinda forced to use Flash CS5.5 IDE, but I'm trying to use Flash Builder 4.5.1 to code library movieClips. For the most part this is working; I'm making movieClips in the library, giving them class names I then edit in FB 4.5. My rationale is for iOS it all has to be one big ass file anyway. I don't really want to make everything a swc and embed in Flash Builder, just want to make movieClips and edit their code in FB.
But, say I have made a ball in the Flash IDE. In the Library I give it a class name of 'Ball' that extends MovieClip. When I go back to Flash Builder in my main class I use
var _ball:Ball = new Ball();
addChild (_ball)
The code works and the ball is placed from library onto stage, however there is the "?" next to the Ball instantiation suggesting the type cannot be found or is not a compile time constant. I don't really want to make a custom class for Ball - although I'm pretty sure if I did and imported a custom Ball class it would find it and the '?' would go away, but is there not a way to force Flash Builder 'see' the Flash IDE library objects/classes?
Many Thanks!
A: In Flash Professional, the AS Linkage should match the class name. You can right-click from the library and "Edit Class", then select Flash Builder to edit the class.
Test the AS Linkage to assure your class package is correctly referenced from Flash Professional to your code.
Views constructed in Flash Professional will instantiate and add children. If you drag your "Ball" movie clip from the library to the artboard, at runtime the "Ball" class will be instantiated and added to stage.
If the symbol requires no programmatic implementation, then there's no need to create the class.
As per size, there's no magic to the symbol's class definition - Flash Pro automatically creates the class for you. You won't know it's name or how it's been defined when the compiler references the class.
This question could be refined to better understand your objective, or specific issue you are experiencing.
If your desire is to code in Flash Builder, than use Flash Pro to design and layout your views, and export SWC from Flash Pro. In Flash Builder, use the [Embed] meta tag to reference the symbols.
If your desire is to code in Flash Pro, you can still use Flash Builder when editing code.
The "?" does not mean there is an error. It's a warning. You might see it all over the place from the default package - things like int, string, Number, MovieClip may show a "?" on the left by the line numbers because the playerglobal.swc from Flash Pro needs corrected in your Flash Builder's .actionScriptProperties.
Flash Pro's compiler should resolve those references and build your SWF; however, editing in Flash Builder may be tedious without code completion, or simply seeing so many "?" by line numbers.
I'd suggest:
*
*Create your FLA in Flash Pro.
*Establish a base class, or give a AS Linkage class name to a symbol.
*From the library, "Edit Class" in Flash Builder, and let Flash Builder stub the project in your workspace referencing Flash Pro's src.
*If you see "?" from default package classes, update your .actionScriptProperties by replacing the playerglobal.swc:
<libraryPathEntry kind="3" linkType="1" path="${FLASHPRO_APPCONFIG}/ActionScript 3.0/FP10.2/playerglobal.swc" useDefaultLinkType="false"/>
If your symbol has no AS Linkage, you cannot reference it using ActionScript, unless you can assure access via a base class such as calling objects as MovieClip. This would not be recommended.
A: The workflow you're describing in your question has always bothered me. Setting a linkage file of an asset seems like to much of a coupling to me - at the end this is just a bunch of assets - why should I couple them with some fixed behavior? Assets for a button should also be sufficient and for a toggle button. Couple it with the Button-class and then you need to duplicate an asset and link it to the ToggleButton. Some may argue that there should only be one Button-class with toggable-property. Nevertheless, I think you all are getting the point. That's why I relly dig into Flex 4 and into the whole designer-developer contract and very decoupled way of using component and a skin.
There is a way to use this approach in Flash without setting any linkages in the FLA. In fact I'm using the compiled SWF as an assets library of skins. I've developed a component model inspired from the early inception of Gumbo and the OpenFlux framework and applied similar principles in Flash. If you're interested in the details you can read the introduction article in my blog about the FLit framework. The whole code + examples are available at Google Code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Generate Create Table Script MySQL Dynamically with PHP I do not think that this has been posted before - as this is a very specific problem.
I have a script that generates a "create table" script with a custom number of columns with custom types and names.
Here is a sample that should give you enough to work from -
$cols = array();
$count = 1;
$numcols = $_POST['cols'];
while ($numcols > 0) {
$cols[] = mysql_real_escape_string($_POST[$count."_name"])." ".mysql_real_escape_string($_POST[$count."_type"]);
$count ++;
$numcols --;
}
$allcols = null;
$newcounter = $_POST['cols'];
foreach ($cols as $col) {
if ($newcounter > 1)
$allcols = $allcols.$col.",\n";
else
$allcols = $allcols.$col."\n";
$newcounter --;
};
$fullname = $_SESSION['user_id']."_".mysql_real_escape_string($_POST['name']);
$dbname = mysql_real_escape_string($_POST['name']);
$query = "CREATE TABLE ".$fullname." (\n".$allcols." )";
mysql_query($query);
echo create_table($query, $fullname, $dbname, $actualcols);
But for some reason, when I run this query, it returns a syntax error in MySQL. This is probably to do with line breaks, but I can't figure it out. HELP!
A: You have multiple SQL-injection holes
mysql_real_escape_string() only works for values, not for anything else.
Also you are using it wrong, you need to quote your values aka parameters in single quotes.
$normal_query = "SELECT col1 FROM table1 WHERE col2 = '$escaped_var' ";
If you don't mysql_real_escape_string() will not work and you will get syntax errors as a bonus.
In a CREATE statement there are no parameters, so escaping makes no sense and serves no purpose.
You need to whitelist your column names because this code does absolutely nothing to protect you.
Coding horror
$dbname = mysql_real_escape_string($_POST['name']); //unsafe
see this question for answers:
How to prevent SQL injection with dynamic tablenames?
Never use \n in a query
Use separate the elements using spaces. MySQL is perfectly happy to accept your query as one long string.
If you want to pretty-print your query, use two spaces in place of \n and replace a double space by a linebreak in the code that displays the query on the screen.
More SQL-injection
$SESSION['user_id'] is not secure, you suggest you convert that into an integer and then feed it into the query. Because you cannot check it against a whitelist and escaping tablenames is pointless.
$safesession_id = intval($SESSION['user_id']);
Surround all table and column names in backticks `
This is not needed for handwritten code, but for autogenerated code it is essential.
Example:
CREATE TABLE `table_18993` (`id` INTEGER .....
Learn from the master
You can generate the create statement of a table in MySQL using the following MySQL query:
SHOW CREATE TABLE tblname;
Your code needs to replicate the output of this statement exactly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: phpQuery behaving weird, changing HTML I want to process a template with a Google plusone button in it through phpQuery and I run into the following problem:
require_once( "phpQuery.php" );
$p = phpQuery( "<g:plusone></g:plusone>" );
echo $p->html();
the expected output would be:
<g:plusone></g:plusone>
But instead the output of this is:
<plusone></plusone>
Which doesn't match up with what google is expecting, so the button doesn't work any more. How can I stop phpQuery from changing (fixing?) my code, or how can I work around this problem without changing the string from plusone to g:plusone once the processing is done? (that's a nasty workaround, plus, I run into more of these 'translation'-problems in phpQuery).
A: I had the same problem while including a google+ badge. I could force the code generator from google to generate code with a div container. I just had to tick the "html5 valid code" checkbox.
A: I've been looking all over for solutions for this problem, to no avail. I found a horrible workaround. I'm sure this is NOT the most elegant way to do this, but at least it fixes the problem.
Instead of the tags:
<g:plusone>...</g:plusone>
use:
<g__0058__plusone>...</g__0058__plusone>
Then simply str_replace the result before you're outputting:
echo str_replace("__0058__",":",$doc->html());
Basically in a tag where you would normally put a colon (:) you put 0058 instead. It's a very non-elegant solution, I realise that, but at least it's a workaround to this old problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++: Why does casting as a pointer and then dereferencing work? Recently I have been working on sockets in C++ and I have come across this:
*(struct in_addr*)&serv_addr.sin_addr.s_addr = *(struct in_addr *)server->h_addr;
While this does do what I want it to I am a little confused as to why I can't do this:
(struct in_addr)serv_addr.sin_addr.s_addr = *(struct in_addr *)server->h_addr;
Since it becomes a pointer and then immediately is dereferenced shouldn't the second work as well as the first? I am still new to C++ and this is a little confusing to me. Any help would be greatly appreciated. Below is the code. All it does is takes the host name or IP and prints the IP to the screen.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
using namespace std;
int main(){
int socketfd, portno, rwResult;
struct sockaddr_in serv_addr;
struct hostent* server;
char inputName[50];
//The next block gets the host name and port number and stores them in variables
cout<<"Enter host(Max Size 50): ";
cin>>inputName;
cout<<endl<<"Enter port number: ";
cin>>portno;
cout<<endl;
server = gethostbyname(inputName);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
*(struct in_addr*)&serv_addr.sin_addr.s_addr = *(struct in_addr *)server->h_addr;
//This is where I am confused
//(struct in_addr)serv_addr.sin_addr.s_addr = *(struct in_addr *)server->h_addr;
cout<< "Server: "<<inet_ntoa(*(struct in_addr *)server->h_addr_list[0])<<endl;
cout<< "Server: "<<inet_ntoa(*(struct in_addr *)&serv_addr.sin_addr.s_addr)<<endl;
//The two cout's tell me if the address was copied correctly to serv_addr I believe.
return 0;
}
A: Objects can only be cast as another class if a constructor exists which accepts an argument of the original type.
Pointers, on the other hand, can be cast willy nilly. However, it can be very dangerous to do so. If it is necessary to cast, use static_cast or dynamic_cast when doing so, and potentially check to see if the cast was successful. One additional stylistic advantage to casting in this more explicit fashion is it makes the cast more blatant to someone browsing your code.
A: What the code is doing is trying to re-interpret serv_addr.sin_addr.s_addr as a type in_addr. However, this conversion is not compatible. Therefore, you get a compiler error in the second snippet if you try a direct cast.
In the first snippet, you're essentially using pointer casting to get around this type incompatibility.
A: A simpler example might help to explain the difference:
double q = 0.5;
int n;
n = (int) q; // #1
n = *(int*)(&q) // #2
The first version converts the value of q into a value of type int according to the rules of the language. Conversion is only possible for primitive types and for classes that define conversion operators/constructors.
The second version reinterprets the binary representation of q as an integer. In good cases (like in your example) this produces something useful, but in general this is undefined behaviour, as it is not allowed to access a variable of one type through a pointer to a different type.
Your example may be valid because the two types in question are both POD structs with the same initial members, and you are accessing only one of the common initial members. Edit. I checked, server->h_addr is of type char *. It's possible that this just serves as a placeholder and the pointer is in fact to a structure of the correct type.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: .htaccess query string to folder format I have a query URL with query string and I want to convert it to folder structured URL.
For example:
http://localhost/index.php?page=about-us
http://localhost/index.php?page=contact-us
how would I covert it to
http://localhost/index/page/about-us
http://localhost/page/about-us
I know this can be done with .htaccess. I just don't know where to start
A: You would need something along the lines of...
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^page/([-a-z-0-9]+)*/$ ./index.php?page=$1
RewriteRule ^index/page/([-a-z-0-9]+)*/$ ./index.php?page=$1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: MySQL Subselect Limit What im trying to do was to list all categories and their posts but only limit posts per category. And exclude a category without any posts.
I did this with two queries though, get all the categories that have posts, loop the results and get X number of posts per category ID.
How can I do this in just 1 query?
EDIT: this is what I accomplished so far..
SELECT p.post_id, c.category_id
FROM category as c
JOIN posts AS p ON p.category_id = c.category_id
WHERE
FIND_IN_SET(p.post_id, (
SELECT SUBSTRING_INDEX(a.post_ids, ',', 10)
FROM
(
SELECT GROUP_CONCAT(b.post_id) AS post_ids, b.category_id
FROM posts as b
GROUP BY b.category_id
) AS a
WHERE a.category_id = c.category_id
))
A: To exclude all categories without any posts do an inner join between category and post. If you want to limit the number of rows returned, use the LIMIT command.
A: how about something like this
SELECT `category_name`
FROM `categories`
WHERE `posts` !=0
LIMIT 0 , 30
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Timespan in Java and SQL? I want to save time intervals in my SQL table but I'm not sure what type to use in Java for this.
What I need to store are durations like 12:33:57 or just minutes and seconds like 02:19. Any ideas what type I could use for java and for sql? I don't really need to make any calculations with these values, but I would like to generate charts later on, with the lengths of the mesured times.
A: The mysql type you want is TIME, ie:
create table mytable (
...
my_interval TIME,
...
);
If you read such columns in via JDBC, you'll get a java.sql.Time object, which is actually a java.util.Date with only the time portion set (ie a time on 1970-01-01)
A: You could store the durations as seconds (or milliseconds) in an int field in Java and in an integer column in SQL (e.g. 5 minutes and 12 seconds would be stored as 312).
The Java int field could be easily converted to any format necessary for your charts (if int isn't already the best format).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Java .bin url for cloud server installation I am trying to install java on a fedora core on cloud server by doing so:
wget -O /java/jdk-6u6-linux-i586.bin http://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/VerifyItem-Start/jdk-6u6-linux-i586.bin?BundledLineItemUUID=ACBIBe.lcAEAAAEa0f1UGJK0&OrderID=KodIBe.ljeAAAAEaxP1UGJK0&ProductID=VXZIBe.ootIAAAEZTrBAkQve&FileName=/jdk-6u6-linux-i586.bin
however, i don't believe that this is a valid download link. Would anyone know a valid link?
Thanks, tone
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Creating a unique sequence of dates Let's say that I want to generate a data frame which contains a column with
is structured in the following format.
2011-08-01
2011-08-02
2011-08-03
2011-08-04
...
I want to know if it's possible to generate this data with the seq() command.
Something like the following: (obviously doesn't work)
seq(2011-08-01:2011-08-31)
Would I instead have to use toDate and regex to generate this date in this
specific format.
A: You could try timeBasedSeq in the xts package. Notice the argument is a string and the use of the double-colon.
timeBasedSeq("2011-08-01::2011-08-31")
A: As I noted in my comment, seq has method for dates, seq.Date:
seq(as.Date('2011-01-01'),as.Date('2011-01-31'),by = 1)
[1] "2011-01-01" "2011-01-02" "2011-01-03" "2011-01-04" "2011-01-05" "2011-01-06" "2011-01-07" "2011-01-08"
[9] "2011-01-09" "2011-01-10" "2011-01-11" "2011-01-12" "2011-01-13" "2011-01-14" "2011-01-15" "2011-01-16"
[17] "2011-01-17" "2011-01-18" "2011-01-19" "2011-01-20" "2011-01-21" "2011-01-22" "2011-01-23" "2011-01-24"
[25] "2011-01-25" "2011-01-26" "2011-01-27" "2011-01-28" "2011-01-29" "2011-01-30" "2011-01-31"
A: I have made the same mistake with seq() attempting to make a numeric sequence. Don't use the ":" operator between arguments, and they will need to be dates if you want to make a date sequence. Another way is to take one date and add a numeric sequence starting with 0:
> as.Date("2000-01-01") + 0:10
[1] "2000-01-01" "2000-01-02" "2000-01-03" "2000-01-04" "2000-01-05" "2000-01-06"
[7] "2000-01-07" "2000-01-08" "2000-01-09" "2000-01-10" "2000-01-11"
A: I had to generate a seq by min, and it was no easy, but i found seq.POSIXt in base. In your case, you want a seq of daily data from 2011-08-01 to 2011-08-31. So i suggest you
days <- seq(ISOdate(2011,8,1), by = "day", length.out = 31)
class(days)
"POSIXct" "POSIXt"
A: This worked for me! I know it's similar to the most upvoted answer, but that fact that i can specify "1 month" in text is amazing!
seq(as.Date("2012-01-01"),as.Date("2019-12-01"), by = "1 month")
A: You can use clock's date_build, which comes with nice functionalities and useful error message:
library(clock)
date_build(2011, 8, 1:31)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Loading Obj files in Libgdx not working on android The following code shows a torus slowly revolving and coming into display:
package com.objloader.example;
import ...
public class ObjLoaderProg implements ApplicationListener{
String torus;
Mesh model;
private PerspectiveCamera camera;
@Override
public void create() {
InputStream stream=null;
try {
stream = new FileInputStream(Gdx.files.internal("data/torus.obj").path());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
model = ObjLoader.loadObj(stream, true);
Gdx.gl.glEnable(GL10.GL_DEPTH_TEST);
Gdx.gl10.glTranslatef(0.0f,0.0f,-3.0f);
}
@Override
public void dispose() {
}
@Override
public void pause() {
}
protected int lastTouchX;
protected int lastTouchY;
protected float rotateZ=0.01f;
protected float increment=0.01f;
@Override
public void render() {
Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
camera.update();
camera.apply(Gdx.gl10);
Gdx.gl10.glTranslatef(0.0f,0.0f,-3.0f);
Gdx.gl10.glRotatef(rotateZ, rotateZ, 5.0f, rotateZ);
model.render(GL10.GL_TRIANGLES);
if (Gdx.input.justTouched()) {
lastTouchX = Gdx.input.getX();
lastTouchY = Gdx.input.getY();
} else if (Gdx.input.isTouched()) {
camera.rotate(0.2f * (lastTouchX - Gdx.input.getX()), 0, 1.0f, 0);
camera.rotate(0.2f * (lastTouchY - Gdx.input.getY()), 1.0f, 0, 0);
lastTouchX = Gdx.input.getX();
lastTouchY = Gdx.input.getY();
}
rotateZ+=increment;
System.out.println(""+rotateZ);
}
@Override
public void resize(int arg0, int arg1) {
float aspectRatio = (float) arg0 / (float) arg1;
camera = new PerspectiveCamera(67, 2f * aspectRatio, 2f);
camera.near=0.1f;
camera.translate(0, 0, 0);
}
@Override
public void resume() {
}
}
It renders a torus obj that's saved in the data folder, and by clicking and dragging on the screen the user can rotate the camera.
This works fine on the desktop, but when I try to run it on android, I get a NullPointerException at:
model.render(GL10.GL_TRIANGLES);
I've tried placing torus.obj just inside assets, and within assets/data. I'm using libgdx 0.9.2.
A: I assume you are referring to model.render(GL10.GL_TRIANGLES);. I believe you have two problems. First, model is null because you are catching a FileNotFoundException and ignoring it. I suggest you don't catch the FileNotFoundException right now, let it crash, and look at the stack trace. That will give you a better indication of why this failing. Note that e.printStackTrace() is not useful for debugging on android, try using the gdx log.
The second problem is that I suspect the path/stream is actually going to the wrong place. Instead of creating a FileInputStream, use the FileHandle.read() function. It returns a java.io.InputStream that you can pass to ObjLoader.loadObj().
in = Gdx.files.internal("data/torus.obj").read();
model ObjLoader.loadObj(in);
in.close();
The difference between this and your code is that FileHandle.read() in libgdx's android backend uses the android AssetManager to open files that are bundled with the program.
Finally, copy the torus.obj file to <YourAndroidProject>/assets/data/torus.obj.
An aside: if you specify the line number, please provide the full file otherwise the line will be off. Line 52 of the code you have provided is: lastTouchY = Gdx.input.getY();. Note the "import ..." at the beginning of your code. Those imports affect the line number.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: UIButton in UITableViewCell stops UITableView from scrolling I've two buttons in each row the buttons are in a custom UITableViewCell designed in IB
The cell has UIButton -- UIImageView -- UILabel in this order for each of the two columns
each of these two buttons recieve proper touchupInside events but I can't scroll the tableview by tapping on buttons and scrolling.
The table view can be scrolled using the space in between these two buttons.
what do I need to wire to make the tableview scroll while keeping the buttons and other views
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Help managing many-to-one results for lookup I didn't see this exactly asked, so I'm hoping it wasn't.
I have a table that has multiple columns with code variables and a table that has all lookup codes and descriptions for the whole database. Is there a way to join the lookup values so that everything stays on one row, instead of what i'm getting where one row has the race value and one row has the sex value. Thanks. I'm using TOAD but understand SQL.
Table 1
User_id Race_cd Sex_cd
101 3201 4501
102 3201 4502
103 3202 4501
104 3203 4501
Table 2
CD_Num CD_descrip
3201 White
3202 Black
3203 Asian
4501 Male
4502 Female
A: I played around for an hour with the joins over your tables, without an easy result.
Then I created views like this :
create view race as select * from lookup where id < 4000
create view sex as select * from lookup where id > 4000
thenafter, the select was just this easy :
select user.id, race.desc, sex.desc from users, race, sex
where user.ra = race.id
and user.se = sex.id
showing up this :
101 White Male
102 White Female
103 Black Male
104 Asian Male
May this inspire you a nice solution ! ( You will naturally have to deal with the "between value and value" predicate when creating your views. )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Click button from method that is outside the oncreate in Android The following is a basic striped down overview of one of my projects. I would like for a method outside of the oncreate to be able to click a button that is declaired in the oncreate but i cannot figure out how.
Here is my code: I would like to be able to performClick() the webButton from the method clickButton() but it does not work. If that is not possible i would atleast like to know how to start the intent that is trying to be started when the button is clicked from instide the clickButton() method.
Thank you in advance!!
public class cphome extends Activity {
static final int check =111;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button webButton = (Button) findViewById(R.id.button1);
webButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), web.class);
startActivity(myIntent);
}
});
}
public void clickbutton(){
webButton.performClick();
}
}
A: This is a really strange pattern. I would suggest you to do something like that instead:
public class cphome extends Activity {
static final int check =111;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button webButton = (Button) findViewById(R.id.button1);
webButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
performClickAction();
}
});
}
public void performClickAction(){
Intent myIntent = new Intent(this, web.class);
startActivity(myIntent);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What jQuery was exposed? jQuery is exposed via:
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
But there are two jQuery:
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
i understand that it's legitimate names - they're from different scope.
But which one was exposed?
i suppose it's var jQuery = function( selector, context ) but it seems it's in different scope from window.jQuery = window.$ = jQuery;
A: I assume you're looking at src/core.js and src/outro.js.
At the top of core.js, there is this code (as shown in your question):
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
That, on its own, might look like it's assigning a new function to jQuery. However, if you look at the bottom:
return jQuery;
})();
It's executing a function that it just created, and setting jQuery to the result (which is the jQuery from inside the function).
Then, in outro.js, there is this code:
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
})(window);
jQuery here is the jQuery from the top of core.js. Thus, through a series of steps, it is setting window.jQuery (as well as window.$) to the jQuery object defined like this:
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: synchronous messaging with STOMP over HornetQ I am trying to figure out how to do syncronous messaging using stomp with hornetq, or if its even possible. I have an async stomp client working, but I can't see how I would implement a sync version.
On the server side, my acceptor looks like this:
<acceptor name="stomp-acceptor">
<factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
<param key="protocol" value="stomp" />
<param key="port" value="61613" />
</acceptor>
and my listener looks like this:
public class SimpleSyncListener extends BaseListener implements SessionAwareMessageListener<Message> {
@Override
public void onMessage(Message message, Session session) throws JMSException {
String lastMessage = "";
try {
lastMessage = ((TextMessage) message).getText();
//System.out.println("server recieved: " + lastMessage);
Destination replyDestination = message.getJMSReplyTo();
StringBuffer sb = new StringBuffer();
sb.append("reply ");
sb.append(Calendar.getInstance().getTimeInMillis());
sb.append(" ");
sb.append(lastMessage);
TextMessage replyMessage = session.createTextMessage(sb.toString());
replyMessage.setJMSCorrelationID(message.getJMSMessageID());
MessageProducer replyProducer = session.createProducer(replyDestination);
replyProducer.send(replyMessage);
} catch (JMSException e) {
throw new RuntimeException(e);
}
incrementCount();
}
I assume I need to put something in the temp queue and send it back like you do with JMS. Its just not clear to me how that works with STOMP. Do i need to open another tcp connection back on the client side that correspond to the "temp queue" on the server side?
A: Stomp is a simple protocol, and on this case I don't think you can have a multiplexed channel. So you will probably need a Stream to send, and a Stream to receive.
A: The common strategy to implement synchronous (request / response) communication with JMS - using temporary destinations - is also available with the STOMP implementations of many message brokers (ActiveMQ, Apollo, OpenMQ and RabbitMQ are examples).
However, HornetQ does not support temporary destinations in the current 2.4.0.Final version.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What free JIT compilers are there today, and which is easier to use? I will start writing a JIT/interpreter for a small language, and would like to use some of the free JIT tools/libraries available today. What are my options (I only know of libjit, LLVM and GNU lightning), and which would be the easier to use (but not too slow)?
The requiremens would be:
*
*Compiling time is not important
*Execution time is important, but so long as using the JIT compiler isn't too hard
*Ease of use is important
*No garbage collection necessary.
*Actually, no run-time environment necessary (I'd really just want the JIT: compile into a memory region, then take the pointer and start executing the generated code)
*Development will be done in plain standard C (no C++, no platform-specific features), with pthreads.
A: Plain standard C with good execution time? you must be looking for LuaJIT(actually dynasm which is the backend, but thats still part of LuaJIT), which is a tracing JIT compiler (where as most of those mentioned are static). It does have garbage collection, but it can easy be taken out or modified (there is a planned overhaul of it soonish), and it has a native FFI, so it can easily do external binding (from a C level, so you don't always have to get into the nitty gritty).
Best part, its totally public domain code, and the code is the documentation (which is nice as its well structured).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to Determine the Work Items Fixed in a particular TFS Build when using Branches? We have begun using the following branching structure in TFS 2010:
All changes so far have been performed in the Development branch, and all check-ins have been associated with a Task work item. The Tasks are all children either of a Bug or a Product Backlog Item work item. Each CI build is triggered for a particular changeset, and the changeset is associated with a Task, so we can manually figure out which Bug or PBI was just built.
Some time after the code has been built, deployed to our Integration environment and tested by the developer, it is merged to the Main branch. Obviously, more than one changeset may be merged to Main at the same time. The nightly build will build this code if we don't manually trigger the nightly before that. QA will later deploy one of these "Main" builds to the QA environment.
There may have been several builds of the Main branch since the last time QA have deployed. These builds are associated with the "Merge" changesets, not with the original changesets which were associated with the Tasks.
How do I determine the set of tasks which have been addressed by a given "Main" build, which is a build of a different branch than the one associated with the Task work items?
Once we've begun preparing for a release, we may very well need to make changes in the Release branch, which will complicate things further since we will be merging back from Release to Main, and the Release changesets will be associated with Tasks. Those will then be merged to Development, making life even more interesting!
P.S. The question "How to determine the work items associated with a source branch in TFS 2010?" comes close to asking the same question, but not quite.
A: Take a look at Jacob Ehn's blog post Automatically Merging Work Items in TFS 2010. He wrote a plug in that can be downloaded from codeplex. It will automatically associate the work items that were associated with the merged changesets. So when you merge to Main or Release the work items will be associated with the changesets in those branches, and the work items will be included in the build reports for builds off of those branches. The plug-in is super easy to deploy.
A: The other option is that you can build a custom workflow activity that you can run during your build that can traverse the merge history for each of the changesets that would normally be associated. It's essentially walking the tree starting with a known set of associated changesets. I would prefer this approach since you can let your developers worry about only needing to associate work items with the original changesets instead of having to also do it with merge changesets as well. This also allows you to get around having to deploy a custom work item policy as Bryan described in his suggestion.
I might have some sample code to get you started with traversing the merge history tree if you want to contact me at http://www.edsquared.com
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: My c program to remove lines from a text file works on a small file, but has a stacksmash error with a large file I am working on a program to filter a list of craigslist results; I want to find a relatively cheap room for rent. The finished program will remove lines that have a price over $600, and create a new file, but for now I am removing every line with a $ character, and printing to the terminal.
The program works fine when run on its own source, but when I run it on an html page of craigslist results saved from Firefox, it prints until the closing html bracket and throws a stack smashing detected warning and a backtrace. I am learning C from K&R so if this code looks antiquated that's why.
# include <stdio.h>
# define MAXLINE 300
main()
{
char line[MAXLINE];
int c;//current character
int p = 0;//position in the line
int flag = 0;//there is a dollar sign
while ((c = getchar()) != EOF){
line[p++] = c;
if (c == '$'){
flag = 1;
}
if (c == '\n'){
if(flag == 0){//there was no $, print the line
int i;
for(i=0;i<p;i++){
putchar(line[i]);
line[i] = '\0';
}
}
p = 0;
flag = 0;
}
}
}
A: I imagine the problem is just that the HTML contains at least one line that is more than MAXLINE characters long. You don't check anywhere whether you're about to exceed the size of the array; if you do, you would indeed smash the stack. Your while loop could check whether p was less than MAXLINE, print a message if not, and stop. You couldn't do anything else without fairly significant changes to your program.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ManageBean method don't works anymore because of FacesValidator? I was having some problem with password validation, which @BalusC help me out, here.
But after I insert the validation code in my form, when I call the controller method, nothing happens.
Here goes my JSF page:
Register.xhtml
<!DOCTYPE html>
<html lang="pt-br"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<h:head>
<title>TITLE</title>
</h:head>
<h:body>
<h:form id="form">
<h:panelGrid columns="3" >
<h:outputLabel for="name" value="Nome:" />
<h:inputText id="name" value="#{register.person.name}" >
<f:ajax event="blur" listener="#{register.validateName}" render="m_name" />
</h:inputText>
<rich:message id="m_name" for="name" ajaxRendered="false"/>
// some fields ..
<h:outputLabel for="password" value="Password" />
<h:inputSecret id="password" value="#{register.user.password}">
<f:validator validatorId="confirmPasswordValidator" />
<f:attribute name="confirm" value="#{confirmPassword.submittedValue}" />
<f:ajax event="blur" execute="password confirm" render="m_password" />
</h:inputSecret>
<rich:message id="m_password" for="password" />
<h:outputLabel for="confirm" value="Senha (novamente):" />
<h:inputSecret id="confirm" binding="#{confirmPassword}" >
<f:ajax event="blur" execute="password confirm" render="m_password m_confirm" />
</h:inputSecret>
<rich:message id="m_confirm" for="confirm" />
<h:commandButton value="Register" action="#{register.registerPerson}" >
<f:ajax execute="@form" render="@form" />
</h:commandButton>
<h:outputText value="#{register.recordStatus}" id="out" />
<a4j:status>
<f:facet name="start">
<h:graphicImage name="loader.gif" library="image"/>
</f:facet>
</a4j:status>
</h:panelGrid>
</h:form>
</h:body>
</html>
So when I fill the form and try to register, nothing happens, not even any exception it's lauched.
The passwod validator (thanks BalusC mate):
@FacesValidator("confirmPasswordValidator")
public class ConfirmPasswordValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
String password = (String) value;
String confirm = (String) component.getAttributes().get("confirm");
if (password == null || confirm == null) {
return; // Just ignore and let required="true" do its job.
}
if (!password.equals(confirm)) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, null, "password not equal"));
}else{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_INFO, null, "ok"));
}
}
}
I think this problem is very weird, I really don't know what's happening here.
Thanks guys.
A: You threw a ValidatorException on a succesful match.
if (!password.equals(confirm)) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, null, "password not equal"));
} else {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_INFO, null, "ok"));
}
This causes JSF to block the form submit. The severity doesn't matter. A validator exception is a validator exception. It indicates a vaildation failure.
Rather use FacesContext#addMessage() instead.
if (!password.equals(confirm)) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, null, "password not equal"));
} else {
context.addMessage(component.getClientId(), new FacesMessage(FacesMessage.SEVERITY_INFO, null, "ok"));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why does the "keypress" event handler not fire consistently? I am having a problem with this function. I cannot get it to fire properly. It does work, but when I highlight the quantity in the form and change the value (the value is initially set to 1), my stock level is 20, when I type in 21 it won't display the message unless I press another key. What am I doing wrong? I have tried every event possible, and can't figure out what I am doing wrong. BTW, this is in a jQuery UI dialog box.
$('#qty').live('keypress', function() {
$('#response').hide();
if($('#qty').val() > stockLevel) {
var response = 'You selected more than we have in stock, we have reset your quantity to the maximum number available in stock';
$('#qty').val(stockLevel);
$('#response').html(response).show('blind', {}, '200');
return false;
}
});
Thanks for you help.
A: The keypress event has notoriously inconsistent behavior (because it is not defined in any standards). In your case your event is firing before the browser puts the text into the textbox. Use the keyup event instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to copy files from file system to IntelliJ IDEA 10.5 I have just started using IntelliJ IDEA.I am really novice to this IDE, so please bear if my question sounds silly.
I am facing a problem regarding copying of files from OS's File explorer to IntelliJ Project.
I am using following versions:
Operating System: Ubuntu v. 11.04
IntelliJ IDEA: v. 10.5.1
JDK: v. 1.6.0_27
For e.g. in the following image I have created a project having a Maven module.
I am unable to copy a schema file (.xsd) on my file system into the folder ..../src/main/conf/vehAvailRate.I tried out so many times but the file is not getting copied.Also I tried the Synchronize feature too but that too didn't helped.However when I open the project in file system and copy my desired schema file there ,IntelliJ IDEA relfects the change.
Am I doing something wrong or there is some other reason behind this behavior?
Thanks,
Jignesh
A: Such copy should be performed externally, using your favorite file manager. IDEA will refresh files under its project directory automatically.
If something goes wrong, check idea.log file in ~/.IntelliJIdea10/system/log directory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I do an ajax post and have a master page webmethod handle it? I am developing a set of new pages for an existing (and large) web app and am making them much more HTML and JQuery-centric than we've done before. For example, there are NO server controls and I am not using ViewState - everything is done in standard HTML. I've created the first page and it works great. It has lots of explicit ajax calls into static methods on the ASPX code-behind class to get or store data and these work fine.
Before I branch out to the remaining pages, I am placing a fair amount of the page into a Master page and the callbacks for these components into the Master page code-behind. However, any function call to a static method on the master page is failing. I could just move these methods to an ASMX web service page but now my curiosity is piqued and I'd like to understand why calls to methods in the aspx page work but calls to methods defined on the master page do not.
This is not an issue of identifying DOM elements (most of the questions around this topic are about DOM element access). It is a question about why an AJAX callback to "SaveWeightData" works when the method is defined on the page but fails when the method is defined on the master page:
$.ajax({
type: "POST",
url: "<%=PageName%>/SaveWeightData",
data: "{'weightItem':" + JSON.stringify(newWeight) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("Success!");
},
error: function (xhr, ajaxOptions, thrownError, request, error) {
alert('xrs.status = ' + xhr.status + '\n' +
'thrown error = ' + thrownError + '\n' +
'xhr.statusText = ' + xhr.statusText + '\n' +
'request = ' + request + '\n' +
'error = ' + error);
}
})
Thanks!
A: A master page becomes a UserControl at runtime under the Page object. UserControls cannot host WebMethods.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7536338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.