text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: How do I trigger a php function on onclick event? For instance I have a php function
<?php
function SayHi($msg){
return $msg;
}
?>
The following part triggers the onclick event
<a href="" onclick="">Click</a>
How can I merge the two such that when I click on Click, the php function is invoked..?
A: You can not. PHP is executed serverside, while javascript is executed clientside.
THe generic solution for this is to use asynchronous Javascript (ajax) to call on your webserver, which in turn can invoke PHP code to do various things.
jQuery is a very nice library to handle this, and much more.
A: There are many ways to do this, most are complicated.
One easier way is:
<?php
function myFunc() { die('yay'); }
if (isset($_REQUEST['myButton'])) myFunc();
?>
<form><button name="myButton">Click Me</button></form>
A: Whaaat? PHP is server-side you cannot invoke a php function from javascript. However you can do this with ajax.
AJAX
A: You'll want to use AJAX. You need to call a server-side resource from the JavaScript code, and jQuery has a very handy function for making the call to the server. But making the call from the JavaScript is only half the story, you'll also need something on the server listening for that call. It would essentially be another PHP script which acts as a page in and of itself, but would return data in the form of (most likely) JSON instead of HTML. It's not meant to be human-readable, but rather to be a sort of web service for your JavaScript code to use.
You can find a simple example here.
A: please get involved with the basics of PHP: http://tut.php-quake.net/en/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript anonymous functions in Firefox 7 After updating to Firefox 7, I am getting the following error:
function statement requires a name
This particular functions is defined as
fun = eval("function (item) { //Function body }");
If I rewrite it as:
fun = eval("function view(item) { //Function body }");
The error does not show up any more, but the program still does not work.
Ps.- I know that evaluating a string is not a good idea. This is a legacy application that I have to fix in which some functions are downloaded from a database as strings on demand.
A: Wrap it in brackets
eval("(function (item) { alert('hello'); })");
But that doesn't make sense as it does nothing. Maybe you want:
eval("(function () { alert('hello'); })()");
Or
eval("var func = function (item) { };");
A: A function declaration (is what you've got there) requires an identifier by spec.
function() {
}
just like that is not allowed by ES specification (even if some browsers might allow it anyway). Only function expression may be anonymous.
A: just a guess, maybe try with:
fun = eval("return function (item) { //Function body }");
(I just added the return statement)
A: if the function is defined as a string and you wish to use it without calling eval everytime, you could do this:
var myFunc = 'function(){alert("myFunc");}';
var fun = eval('(function(){return '+myFunc+'})()');
fun();
Or just
var myFunc = 'function(){alert("myFunc");}';
var fun = eval('('+myFunc+')');
fun();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Cron logging in /var/log/syslog I Have a rake task which executes successfully . But the cron logs it in the /var/log/syslog. Is it a genuine problem. I'm observing this issue for more than a month now, but the cron always logs it as an error in the /var/log/syslog. Is there any reason behind this.
A: Check the return value of the executed command and the output it prints to STDOUT and STDERR. This is the reason why cron logs it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to provide free begin/end functions for your own types In one of his latest talks, Herb Sutter recommended to prefer the free begin(container) end(container) functions templates over container.begin(). I like it, because these function can be provided for all iterable types that don't come with begin()/end() methods. Since most of my domain classes have interfaces that talk in the domain language and don't use general names like begin/end, I can now provide an iterable interface compatible to STL containers and range base for loops without messing up the main class interface.
I am wondering what is the best way to provide begin/end functions for my own types. My first thought was to do it the same way I do with swap and write the function in the same namespace where my type lives.
namespace My
{
class Book
{
public:
typedef std::vector<Page>::const_iterator PageIterator;
PageIterator FirstPage() const { return begin(pages_); }
PageIterator LastPage() const { return end(pages_); }
private:
std::vector<Page> pages_;
};
Book::PageIterator begin(const Book& b)
{
return b.FirstPage();
}
Book::PageIterator end(const Book& b)
{
return b.LastPage();
}
}
Is it ok to rely in ADL here, or should they be in std namespace? I think another way is to provide a specialization in std namespace (overloading in std is not allowed, right?). What is the best way espacially regarding lookup for range based for loops?
A: I would let ADL do its work. While you are allowed to add specializations in the std namespace, there is no strong reason I can think of for doing so when a plain free function in your namespace suffices.
In particular for the range for loops, the standard states:
§6.5.4/1 (definition of begin-expr and end-expr):
*
*otherwise, begin-expr and end-expr are begin(__range) and end(__range), respectively, where begin and end are looked up with argument-dependent lookup (3.4.2). For the purposes of this name lookup, namespace std is an associated namespace.
A: It's perfectly OK and recommended to "rely" on ADL. The begin and end functions are part of your type's interface (regardless of whether they are freestanding functions or not) and they should be in the same namespace as your type.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: How to validate if an item is removed from picklist? I need to verify if an item is able to me removed from selected items into the picklist. I've tryed using valueChangeListener but for some reason my method has not been called.
So i've tryed another way. I've used a4j:support with onlistchange event. With this one I get in server side, but only when i add items to my picklist. If I remove some item the method in server side to validate it is not called.
<rich:pickList value="#{home.instance.campos}" styleClass="pick_margin_fix" required="true"
copyControlLabel="Selecionar" copyAllControlLabel="Selecionar Todos" removeAllControlLabel="Remover Todos"
removeControlLabel="Remover" >
<a4j:support event="onlistchanged" action="#{home.testeModificacao2}" ajaxSingle="true"/>
<s:selectItems value="#{campoService.obterTodos()}" var="campo" label="#{campo.descricao}" noSelectionLabel="true" />
<s:convertEntity />
</rich:pickList>
Someone knows what can be the problem?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sql Error in android android.database.sqlite.SQLiteException: unrecognized token I am querying the android calendars db and looking for an event with particular 'iCalGUID' .
here is the query I am using
final Cursor cursor = resolver.query(uri.getCalendarUri(),
null, "events.iCalGUID=" + uid, null, null);
Current uid is 0804eaa1-3472-43df-96c2-af73ae5c31ab
But I am getting an exception while executing this query
android.database.sqlite.SQLiteException: unrecognized token: "0804eaa1": ,
while compiling: SELECT originalEvent, visibility, rrule, hide_declined, reminder_type, hasAlarm,
description AS suggest_text_2, rdate, transparency, timezone, dtstart, _sync_time, hasAttendeeData,
commentsUri, description, reminder_duration, htmlUri, _sync_account, _sync_version, hasExtendedProperties,
last_update_time, eventLocation, dtend, allDay, organizer, sync_source, deleted, url, originalInstanceTime, alerts_vibrate, importance, selfAttendeeStatus, eventTimezone, ownerAccount, _sync_account_type, lastDate, guestsCanModify, guestsCanSeeGuests, exrule, selected, title, _id, _sync_id, alerts_ringtone, calendar_id, access_level, _sync_local_id, title AS suggest_text_1, originalAllDay, iCalGUID, _sync_dirty, duration, parentID, color,
guestsCanInviteOthers,
exdate, eventStatus FROM view_events WHERE (1)
AND (events.iCalGUID=0804eaa1-3472-43df-96c2-af73ae5c31ab)
How could I do this in android
Thanks.
A: Try this:
final Cursor cursor = resolver.query(uri.getCalendarUri(),
null, "events.iCalGUID=\"" + uid + "\"", null, null);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Control-M binding with Integration Server I know its very rare to think of that but , is there a way to link BMC Control-M with Cruise Control.Net server ? Is there a Control-M command line or executable to use with CCNet ?
I want to deploy automatically Jobs through CCNet.
A: With BMC Control-M, you can execute your job as a batch.
So yes, you can configure CC.NET to execute a BMC CM task but only if CC.NET & jobs are on the same machine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android - ListView event when user reaches 50º list item I want to set a simple listener in a ListView so when the user passes through the 50º item of the list, I call a thread that will append 100 more items into that list.
I am looking for an event to do that for over an hour now and I don't seem to be able to find one. There are tons of events for when a list item will be clicked or something like that, but I can't find one for when the user simples passes through the item in the scroll processing.
Thank you so much in advance!
A: Put the ScrollListener on list view, when it reaches end of the list u will get the last item, then add the progressbar at the footer and then start thread where u can load the other items, and notifyDataSetChanged() for adapter , and you will get the list with added items..!!
And you can check whether the item number 50 is reached, in onScroll().
A: I think there is no need to do this, because the ListView recycles the item views. So you dont occupy memory for the listview items (per each value), you just use memory for the ArrayList(or any data type you use for feeding).
Also you can do this whenever user reaches the end of the listview (last listview item) then refeed the adapter with the new value and then call .notifyDataSetChanged().
About reaching 50% of listview visible items can make things scrambled because you'll always have the 50% reached, otherwise you can improvise (reaching 50% on the ArrayList instead ListView) by checking if more than 50% of the existing ArrayList is displayed, let's say you 10 items and the 6th item is on the listview count / 2, you check if the on that half listview item is more than 50% of data feed for the listview you feed with new data. (I might be unclear)
I hope the idea will help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL query with SUBSTRING and CONTAINS I have following table
ID | Name | Url
Each Url contains address to file fe: "http://blah.blah.com/abcde.bin". Address is always same but file name. In need SQL query to update all cells in this column, where Url contains http and store only file name.
Example:
SELECT URL FROM TABLE
1 | "http://blah.blah.com/abcde.bin"
UPDATE ...
SELECT URL FROM TABLE
1 | "abcde.bin"
A: Try this query:
UPDATE TABLE SET URL = REPLACE(URL ,'http://blah.blah.com/','')
it doesn't use contain or substring, but does the same, with less code. If it finds the 'http://blah.blah.com/' string, it will be replaced with an empty string, so you will have just your name.
I didn't try it but I think it's correct.
Hope it helps you.
A: If your adress is same except file name then you can do like :
UPDATE TABLE SET URL = REPLACE(URL ,'http://blah.blah.com/','')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: codeigniter, library or helper can access through url? In Codeigniter, there are library and helper.
I can access controller and its sub function.
for eample.
login/getid
Is there any way to access library or helper through url?
Update :
I made a captcha library in login controller.
I want to use it in many other controller's view.
in view file, the captcha code should be like this,
<img src="/login/get_captcha" />
everytime I want to use captcha, I have to call login controller.
So, I thought that there should be better way to do this.
If library or helper can access through url, I can make this to helper.
can access another controller's view without loading login's controller.
A: You can create a wrapper controller to access those functions exclusively and use your routes to utilize said URL's
Example: yoursite.com/helper/geo/citiesNearZip/90210
class helperController extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper($this->uri->segment(1)); // geo helper in this example
if($this->uri->segment(2))
{
$helper_method = $this->uri->segment(2);
}
else
{
show_404();
return false;
}
// check if helper has function named after segment 2, function citiesNearZip($zip) in this example...
if(function_exists($helper_method)
{
// Execute function with provided uri params, xss filter, secure, etc...
// You would also want to grab all the remaining uri params and pass them as
// arguments to your helper function
$helper_method();
}
}
}
A: Nope. This is simply not the way the framework was designed to work.
If you think you have to access a helper/library directly, then you're probably doing something wrong.
Can explain what you're trying to do? There must be a better way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What does bare strings in the body of a class definition mean? Here is a snippet of code from django.core.exceptions:
class MiddlewareNotUsed(Exception):
"This middleware is not used in this server configuration"
pass
Is the bare string in the body of the class a mere literal for documentation ? Or does it perform some magic ?
A: It's a doc string:
A docstring is a string literal that occurs as the first statement
in a module, function, class, or method definition. Such a docstring
becomes the __doc__ special attribute of that object.
All modules should normally have docstrings, and all functions and
classes exported by a module should also have docstrings. Public
methods (including the __init__ constructor) should also have
docstrings. A package may be documented in the module docstring of the
__init__.py file in the package directory.
A: It's a docstring. The only magic is that it ends up on the object as __doc__.
A: It's called a docstring.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Apache mpm for a social networking site I am trying to build a social networking website that would have a large amount of users logged in at the same time, with an upper limit of around 5000 at a time.
I plan to use the LAMP stack. Apache can have 2 mpms (multi processing modules) - preforker(forks a new process per request) and the worker model (which uses threads per request).
Considering that my server side code is in PHP, and I want to be able to scale up the website on demand, which one would be more preferable. Some third party PHP modules we are using are not thread safe, so ideally preforker is recommended.
*
*Is there any way by which delay between swapping processes can be decreased in preforking
*Is there any way by which I can use the worker module, with php as well ?
Social networking sites running on the LAMP stack, normally use which mode?
A: If you plan to server push services, apache is not a good choice. Take a look at cherokee and nginx, both work much better with php-fpm than mod_php with apache2, since you do not need CGI support (only FastCGI is supported with cherokee and nginx) only PHP.
A few weeks ago I migrated my WordPress network from apache2-mpm-itk with mod_php to nginx+php5-fpm. As a result system load drastically dropped, memory load became predictable and the user experience seems to be a lot faster. I also added some free test from loadimpact.com, the serving times were better with the new config also.
A: Apache isn't preferred with so much requests. You'd be better off with nginx for example. http://nginx.net/
"10000+ concurrent connections per server" sounds good enough ;-)
A: You could use Apache in worker mode if you do not use PHP with mod_php. Use PHP in Fastcgi mod, php-fpm is a must-try for that.
With current apache stable version (2.2) you will have problems if you want to use it in chrooted mode. But you may try apache 2.3 or wait for the 2.4 and use mod_proxy_fastcgi instead of mod_fastcgi or others. You could also test the new event basef mpm with this version of Apache. Or of course you could try the other web servers as answered by @petermolnar
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Working with CAReplicatorLayer I've been trying to create a cool text effect with the CAReplicatorlayer, CATextLayer and very basic animations. I'm trying to make the letters look like they are being droped from the top of the screen followed by cool replicators which will become less and less visible. I've managed to do this effect but not completely.
So far this is what I've got:
CATextLayer *messageLayer = [CATextLayer layer];
[messageLayer setForegroundColor:[[UIColor blackColor] CGColor]];
[messageLayer setContentsScale:[[UIScreen mainScreen] scale]];
[messageLayer setFrame:CGRectMake(0, 0, 40, 40)];
[messageLayer setString:@"A"];
CAReplicatorLayer *replicatorX = [CAReplicatorLayer layer];
//Set the replicator's attributes
replicatorX.frame = CGRectMake(0, 0, 40, 40);
replicatorX.anchorPoint = CGPointMake(0,0);
replicatorX.position = CGPointMake(0, 0);
replicatorX.instanceCount = 9;
replicatorX.instanceDelay = 0.15;
replicatorX.instanceAlphaOffset = -0.1;
replicatorX.zPosition = 200;
replicatorX.anchorPointZ = -160;
[replicatorX addSublayer:messageLayer];
[self.view.layer addSublayer:replicatorX];
messageLayer.position = CGPointMake(40, 400);
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.y"];
animation.fromValue = [NSNumber numberWithInt:0];;
animation.toValue = [NSNumber numberWithInt:400];
animation.duration = 3;
[messageLayer addAnimation:animation forKey:@"s"];
I have two problems:
*
*The replicated layers are starting in the End point.
*When the main layer reach his last animated point the animation stops and the replicated layers can't finish their animation.
A: Setting the correct values to the animation object's fillMode and removedOnCompletion properties will hopefully solve your problems:
"The replicated layers are starting in the End point."
This is caused by the value assigned to instanceDelay property, which delays the animation with 0.15s in your example. To present the animation from the fromValue, you need to account for this delay by setting the animation's fillMode to kCAFillModeBackwards .
animation.fillMode = kCAFillModeBackwards;
"When the main layer reach his last animated point the animation stops
and the replicated layers could not finish their animation."
This happens because by default "the animation is removed from the target layer's animations upon completion."1. You can override this default behavior by setting the animation attribute removedOnCompletion to NO.
animation.removedOnCompletion = NO;
Hope this helps. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: How to run php & java script code at the backend of Joomla article or module.. advise i am confused how to attach my php and javascript code in with their modules etc.. can anyone recommend me with tutroial so that i can understand ..
I tried making static pages but could find the way to write php code.. all extension their i found out are about inserting the php code as in to the pages but not executing .. banging head on wall
A: You can use the Sourcerer plugin (http://extensions.joomla.org/extensions/edition/custom-code-in-content/5051) in order to be able to code php/javascript straight into articles and have it execute on the page.
It works really well - is a simple installation and runs well.
If you're having issue with the code disappearing on you, read through the documentation - you can change the tags to [[ instead of < and it will save the code in the article for you and it works really well.
Best plugin I've used for executing JS/PHP inside articles/modules.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ggplot2 geom_smooth fails with error with scale_y_probit I am trying to plot lines of best fit to a cumulative density
I am representing the results using a reciprobit plot (log latency vs
probit cumulative probability).
grp<-c("g1","g1","g1","g1","g2","g2","g2","g2","g3","g3","g3","g3")
lat<-c(1, 4, 6, 8, 2, 3, 7, 9, 1, 4, 8, 8)
data<-data.frame(grp,lat)
d.f <- arrange(data,grp,lat) # sort data into ascending values
d.f.ecdf <- ddply(d.f, .(grp), transform, ecdf=ecdf(lat)(lat) ) #
calculate ecdf
p <- ggplot( d.f.ecdf, aes(lat, ecdf, colour = grp) )
p+geom_point()+
scale_x_log10()+
scale_y_probit()
All ok up to this point but if I add
p+scale_y_probit()+geom_smooth()
OR
p+scale_y_probit()+stat_smooth()
i get the error:
Error: NA/NaN/Inf in foreign function call (arg 1)
It works with most other distributions, for example
p+geom_point()+
scale_x_log10()+
scale_y_inverse()+
geom_smooth()
Is there any way around this issue?
A: You compute the ECDF for each group, which results in several values exactly equal to 1. The probit function evaluated at 1 is infinite. (Probit(1) should give you the value of a standard normal random variable with all of the other values to the left, i.e. the area to the left of this value should be 1. So, infinite.)
And the scatterplot smoothing methods (and most other fitting methods as well) won't play nicely with infinite response values.
After building the data frame, you can change all the value in ecdf that are 1 to something just slightly less than one and your code will run without errors.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: tapestry form type=image in input not working I am trying to use an image for a submit buttin like this
<input t:id="submitButton" t:type="image" type="image" src="images/h_logon_button.png"/>
but when i render the page, i get this error
Unable to resolve 'image' to a component class name.
How do I use an image to create the submit button. if I use css, the image disappears after validation fails.
Any ideas?
Tx
A: CSS will work. It sounds like another CSS rule with higher specificity is applied to the button on failed validation. Just inspect the button and see which rule overwrites it.
The error you are seeing is due to the t:type="image". Here you are telling tapestry that your input should be of component type image. You can fix this in three ways:
*
*Remove the t:id="submitButton" and t:type="image" so that your submit will just be a plain old html submit
*change the t:type to submit like t:type="submit"
*Remove the t:type="image" and add a component relating to your provided id like @Component(id="submitButton") private Submit submitButton;
A: Tapestry has a specific component, ImageSubmit, for your situation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Where do i find the Source codes from the Pragmatic programmers-iPhone SDK Development book I have just started reading the book and i seem to have a problem with the code from the Tab-Bar project. I dont know where i'll get the source code from for free. can ne1 help me out with that?
Thanks in Advance.
A: I looked at the main web page (http://pragprog.com) and found these link: "Where can I find sample code and errata." Clicking that I found: "Where do I find the code for my book?"
Alternatively I searched for the book on their site and found this link: "Code". Clicking that link I found this link: "Download .zip".
It really is that simple to use the Internet. :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: android, auth, keep HTTP connection, use connection in few Activity in my app i try to get access to some web service. I'm going through form based authentication and getting an authorized connection. If i passed authorization i want open new Activity, but any new instance of DefaultHttpClient got unauthorized right.
And questions is:
1) How pass this connection through activity
2) Or how keep connection authorized correctly, if i think about httpclient interceptor, I'm on the right way? If, yes, then first question remain, but relativity of pass CookieStore data.
A: You should almost always make a class that handles your Http Requests call is ConnectionManager thats the most common name.
And you should make it with Singleton Design Pattern. This way your connections will be handled correctly.
public class ConnectionManager {
private static ConnectionManager instance = null;
private DefaultHttpClient client;
private ConnectionManager() {
client = new DefaultHttpClient(...);
}
//public method that will be invoked from other classes.
public static ConnectionManager getInstance() {
if(instance == null) {
instance = new ConnectionManager();
}
return instance;
}
public void authenticate(){
// Do your auth call with the client here
}
public void postStuff(){
// Use the same client here, this way you keep using the same client for ALL of your calls.
}
}
When you need to use the ConnectionManager use this:
private static ConnectionManager conn = ConnectionManager.getInstance();
conn.authenticate();
conn.postStuff();
A: Subclass the Application. You'll need to list it in the manifest so that it is created. You'll be able to retrieve it from within any activity.
public class ClientApplication extends Application {
Session Session = null;
public Session getSession() {
return Session;
}
public void setSession(Session session) {
Session = session;
}
}
elsewhere
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: Start");
super.onCreate(savedInstanceState);
setContentView(R.layout.startresume);
ClientApplication app = ((ClientApplication)getApplication());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Horizontal scroll view and image views? I want to add a number of image views to a HorizontalScrollView dynamically.
I have my scroll view:
myScroller = new HorizontalScrollView(this);
Then:
myScroller.addView(myImageView1);
This works, but I want to add more than one image view to the scroller, then it doesnt work.
Any ideas?
A: HorizontalScrollView can only have 1 child, so you need to put all the images inside a horizontal linearLayout and add it to the HorizontalScrollView.
HTH.
A: Take a horizontal scrollview, and take a horizontal linear layout inside it, then if u know how many number of images are there? take it in for loop, add them imageview one by one into linearlayout...!!
A: If you add ImageViews you could also use Gallery which will also scroll horizontally and you can use an adapter to set the content.
If you want to stick to the ScrollView you can only have one child, so you have to add a container like a LinearLayout where you're adding your ImageViews.
A: ScrollView it allow only one child view,
A ScrollView should place
one child in it containing the entire contents to scroll
A: Using a HorizontalScrollView to do that is much harder than using the ViewPager class that comes in the compatibility package.
For more info, read this blog post.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rotate div with top-left corner in javascript please help, to rotate div to 90 degrees, based on a specific point, ie, top-left corner of that div in Internet Explorer 7 using javascript or jQuery or css or html.
I had tried with fiter,
filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.00000000, M12=-1.00000000, M21=1.00000000, M22=0.00000000,sizingMethod='auto expand');
This rotates the div to 90 degrees but the top-left corner is displaced.
A: Your best bet would be to let the CSS do the rotate, and then use jQuery to reposition the element to a specified set of coordinates. AFAIK, you can't provide a filter and restrict its rotation about a fixed point
jQuery animate() may help.
A: You can actually have it rotate around a corner with the transform-origin CSS3 property. Read more on it here: W3C CSS3 2D Transforms - Transform Origin
A: Try BasicImage rotate instead of matrix for a 90 degree rotation
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is n/(log(n)) considered polynomial time? Not exactly sure if this is considered polynomial or something else. Couldn't find the exact example here: http://en.wikipedia.org/wiki/Time_complexity
A: Yes, because it is upper-bounded by a polynomial (n).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How is the 'notes' field implemented in iOS Contacts App? I need to create something very similar to the notes field in iOS Contacts application.
Does anyone know how to create the auto-resizing effect. I presume that the cell contains a UILabel on the left and an editable UITextView on the right.
I am aware that this question has been already asked before however the answer posted was not detailed enough and I cannot leave a comment to ask for more detail.
Any thoughts are welcome. Thanks.
A: Start with the accepted answer to this thread.
You'll set some object, possibly the table view's delegate, as the delegate of the text field in the cell. When the text view delegate gets a – textView:shouldChangeTextInRange:replacementText: message (or perhaps just -textViewDidChange:) it can calculate the required height of the text view and, if that's different from the current height, call the table's -reloadRowsAtIndexPaths:withRowAnimation: method. This will cause the table to reload the row, effectively changing the height.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Extract currency from formatted amount I'm getting a formatted amount of money from a web service. It can be in different formats and using different currencies, e.g.
*
*$ 1.10
*€ 1,10
*1,10 €
*EUR 1.10 (perhaps, I'm not sure I'll actually encounter this one)
I would like to extract the currency symbol ($) from it, and if possible get the associated Currency object (Java) from that symbol. I don't need to extract the amount, I can get that somewhere else.
A: you can use a regular expression, to parse your result from the webservice. You have to filter all characters, except numbers, dots and whitespaces. Here is the regex for that:
String regexp = "[^0-9\\.,\\s]*";
The first group of the matching result is the currency symbol (or the name e.g. EUR).
Here is my sample method:
public void test() throws Exception {
String text = "2.02 $";
String regexp = "[^0-9\\.,\\s]*";
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(text);
while (m.find()) {
for (int i = 0; i < m.groupCount() + 1; i++)
LOG.info(m.group(i));
}
}
A: You could have a look at Joda Money, it might offer a solution for your problem. Caution: it is still version 0.6
A: getSymbol() method from java.util.Currency will help you to get the currency symbol
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: How to get Id of a selected checkbox, when checkboxes are cteated programmatically using java code in android I have created checkboxes programmatically. I want to get Id of setected checkbox.
public class TestValidCheckboxActivity extends Activity implements OnCheckedChangeListener{
private RelativeLayout layoutMiddle = null;
private TableLayout layout1;
private CheckBox chk;
private String[] resarr = {"silu", "pinky", "meera"};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
layoutMiddle = (RelativeLayout)findViewById(R.id.layoutMiddleUp);
layout1 = (TableLayout)findViewById(R.id.tableId1);
final Button btnNext = (Button)findViewById(R.id.btnNext);
int i = 0;
for(String res: resarr){
TableRow tr=new TableRow(this);
chk=new CheckBox(this);
chk.setId(i);
chk.setText(res);
chk.setTextColor(Color.BLACK);
tr.addView(chk);
i++;
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
lay.addRule(RelativeLayout.BELOW, layoutMiddle.getId());
layout1.addView(tr, lay);
}
chk.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
if (arg1)
{
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(final View view) {
Log.e("1111111111","111111111");
if(chk.isChecked()){
Intent intent = new Intent(view.getContext(),NextPage.class);
startActivityForResult(intent, 0);
}else{
Toast msg = Toast.makeText(view.getContext(), "please choose at least one option", Toast.LENGTH_LONG);
msg.show();
}
}
});
}else{
Toast msg = Toast.makeText(TestValidCheckboxActivity.this, "please choose at least one option", Toast.LENGTH_LONG);
}
}
});
}
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
}
}
A: if(chk.isChecked()==true){
chk.getId()
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Search of explicit type conversions in C style: a = (int)b; I have a question concerning the benefit of this diagnostic.
One user suggested that we implemented search of all the explicit type
conversions in C style in the PVS-Studio analyzer.
That is, a diagnostic to detect constructs of this kind:
int *x = (int *)y;
float a = float(b);
float c = (float)(d);
Its purpose is to replace all these conversions with their safer
versions - reinterpret_cast/static_cast/const_cast. During the process
of such refactoring, some defects in code may well be detected.
Of course, this is not detection of crucial errors, and if we
implement this diagnostic, it will be in the section [Customer's
Specific Requests] and disabled by default.
But I even doubt the benefit of this diagnostic. So I decided to ask
other users: does anybody else need this option of searching for explicit
type conversions in C style? Would anybody like to perform this kind
of refactoring in their code?
A: A common view (e.g. expressed by Stroustrup) is that C-style casts are apt to hide errors. I assume that these views would motivate quite a number of people not to use them, so a anti-C-cast diagnostic would get some usage, I guess. I personally wouldn't care to do it because I avoid C-style casts anyway, but given legacy code, I'd find the search useful.
A: I would even go further, casts in general are a bad thing and code that uses them a lot is suspicious. This certainly the case for C, where the rules of implicit conversions that may happen is very limited and well defined by the language.
C++ is a bit more complicated because of overloading, but still, you shouldn't need much explicit casts. A design should always be such that there is one unique path to cast one type into another.
Cast are bad, because they easily hide problems if the type of the expression that is cast changes. In your example if y is changed from a pointer type to an integer type for example. But in any case C++ style casts are much better, be it alone that they are easier to search for, and that are really a pain to type, to people would naturally avoid them :) And just try to forbid reinterpret_cast completely or at least it should be really rare.
A: I understand the motivation of C++ cast in favor of C cast (essentially because C cast are sometime static_cast, sometime reinterpret_cast, with risk of surprises) but ... refactoring something that already works may introduce even unexpected bugs, simply because you may misinterpret what the original developer was going to do...
Unless you are reconsidering rewriting the logic (so you are not working "statement by statement", but also understanding the overall semantics), I will not do it.
A:
does anybody else need this option of searching for explicit type conversions in C style?
yes. it's an easy means to introduce/hide bugs (e.g. the most direct update of your program may produce some warnings or errors).
i favor cpp style casts because they are eyesores, while c style casts are easily obscured (that is by design).
better yet, going through the process and fixing the programs to be typesafe (most casting is unnecessary in cpp) is often a better solution.
Would anybody like to perform this kind of refactoring in their code?
i got rid of all the old style casts and stuck with it along the way (some bugs as well). i am happier. depending on your codebase(s) and your level of trust of the developers that built it, it may not be a good use of time. it's a boring process, but time may end up being spent debugging the issues theta are masked (again, depends on the codebase).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: .NET COM Interop deployment with Wix failing I'm developing a .NET BandObject toolbar for Internet Explorer. I'm working off the sample at CodeProject ( http://www.codeproject.com/KB/cs/Issuewithbandobjects.aspx ) and everything was working fine, I was using gacutil and regasm to test the toolbar and that was working. Then I moved to using Wix in order to test real deployment and construct the msi file, which meant, switching to Heat.
Initially, I created the fragments for the various dll's and this was working fine having manually added the <... assembly=".net" ...> attribute to the various wxs files. However, in order to further prepare it for deployment I ended up renaming the project and dll filename, changing the GUID's from the samples 2 dll's and following this, also tried to test upgrading the major version number. Having changed the dll's I also regenerated the wxs files with Heat, manually adding necessary attributes. However, now the toolbar no longer loads in IE, even though the option is there. It fails silently.
On inspecting the Registry entries, using OLEVIEW.exe , I can create an instance of the old project dll and access it's COM interface that was registered with gacutil and regasm. However, the Wix installed file fails to load with an error of:
CoGetClassObject failed.
The system cannot find the file specified.
severity: SEVERITY_ERROR, facility: FACILITY_WIN32 ($80070002)
I suspect that this is because the new COM object has for some reason not been registered corrrectly either by Wix or the msi installation process. This is because on comparing the old and new dll's in OLEVIEW, the new dll has Registry entries of the form:
InprocServer32[CodeBase]=file///C:\Release\MyProject.dll
--1.0.4279.39243[CodeBase]=file///C:\Release\MyProject.dll
The old COM object has non of these lines. This suggests that even though it has been installed to the GAC, it has not been registered properly. What's even more confusing is that old msi installation files that used to work also failed if installed (all previous Wix versions first removed).
I am at a loss. Hopefully someone can shed light on the situation.
Best Regards,
Daniel.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Looking for method / module to determine the compiler which was used for building the CPython interpreter When I start the Python interpreter in command line mode I get a message saying which compiler was used for building it. Is there a way to get this information in Python ? I know I could start the interpreter with subprocess.Popen and parse the output, but I'm looking for an easier and more elegant method.
The background is that I want to build Python extensions for a CMake based C++ framework, and I would like to write a CMake macro wich checks if the correct compiler is installed.
A: Use platform.python_compiler().
A: You can use the sys.version variable to access this information:
>>> sys.version
'2.7.2 (default, Jun 29 2011, 11:17:09) \n[GCC 4.6.1]'
It will tell you which compiler was used to compile Python, but it won't ensure the mentioned compiler is installed on the system (this could be a pre-built Python version).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Can JavaScript make web-application drag&drop? I want to create a web-application that can be drag&drop where ever you want it to make the page your own style. Does anyone one know how can I do this in JavaScript? I'm currently studying JavaScript on my own and then move into HTML5 for video streaming, Java for apps & MySQL, and ColdFusion because someone told me I need it if I want to get my website working on smart-phones.
The only thing I need for ColdFusion because someone told me is for video recording, chat, etc.. to computer users or phone to phone contacts.
A: You can use jQuery UI for that.
Also check out:
*
*Drag And Drop Everything With These 30 Handy jQuery Plugins
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the use of faces-config.xml in JSF 2? After the JSF 2 big support for annotations, I'm wondering what I would use the faces-config.xml for. What is its importance now?
In other words, what are the configurations that can only be done through faces-config.xml and not via annotations?
Right now all what I am using it for is to declare Spring's EL resolver.
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
</application>
</faces-config>
A: It's still to be used for many things which can't be annotated. E.g. custom JSF validation messages:
<application>
<message-bundle>com.example.i18n.messages</message-bundle>
</application>
A global i18n bundle (so that you don't need to declare <f:loadBundle> in every view):
<application>
<resource-bundle>
<base-name>com.example.i18n.Text</base-name>
<var>text</var>
</resource-bundle>
</application>
Explicitly supported i18n locales (so that the not-declared ones will be ignored even though there's a message bundle or resource bundle for it):
<application>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>nl</supported-locale>
<supported-locale>es</supported-locale>
<supported-locale>de</supported-locale>
</locale-config>
</application>
Custom view handlers:
<application>
<view-handler>com.example.SomeViewHandler</view-handler>
</application>
Phase listeners (there's still no annotation for that):
<lifecycle>
<phase-listener>com.example.SomePhaseListener</phase-listener>
</lifecycle>
Managed beans which can't be annotated (the below one gives current Date on #{now}):
<managed-bean>
<description>Current date and time</description>
<managed-bean-name>now</managed-bean-name>
<managed-bean-class>java.util.Date</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
Custom factories, such as custom exception handler factory (it also allows factories for FacesContext, ExternalContext, LifeCycle and many more so that you can provide your custom implementation):
<factory>
<exception-handler-factory>com.example.SomeExceptionHandlerFactory</exception-handler-factory>
</factory>
To name only the commonly used ones. If you have faces-config.xml tag autocompletion in your IDE, you can find them all out. Only the managed beans, validators, converters, components, renderers and point-to-point navigation cases are not needed anymore thanks to the new annotations and implicit navigation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "92"
}
|
Q: NStableView selected row color (remove border of NSTableView on selection) I am using NSTableView for display my data. I want to remove color of selected row which by default taking blue color. Can i set it to Clear color. Is it possible??
EDIT:
how can i remove this blue border?? I have set Clear color to table background.
Thanks in advance..!!! :)
A: [tableView setSelectionHighlightStyle:NSTableViewSelectionHighlightStyleNone];
To remove the table's blue focus ring border, select the table in your .XIB and set Focus Ring to None
A: This line should remove the ring.
[tableView setFocusRingType:NSFocusRingTypeNone];
A: @Snhl
Francis McGrew said "select the table in your .XIB and set Focus Ring to None", that table's inside the Scroll View
A: This would do the trick :)
[result setSelectable:NO];
Put the above code in the below method ...
- (NSView *)tableView:(NSTableView *)tableView
viewForTableColumn:(NSTableColumn *)tableColumn
row:(NSInteger)row {
NSTextField *result = [tableView makeViewWithIdentifier:@"MyView" owner:self];
// There is no existing cell to reuse so create a new one
if (result == nil) {
result = [[NSTextField alloc] initWithFrame:CGRectMake(0, 0, 289, 50)];
result.identifier = @"MyView";
}
[result setBackgroundColor:[NSColor clearColor]];
[result setBordered:NO];
//set selectable proeprty to NO and your blue border will disappear
[result setSelectable:NO];
// Return the result
return result;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: If I have built for iOS 4.3 my App, will it run on a device with OS 4.2? Will backward compatibility supported for iOS?
If I have built for iOS 4.3 my App, will it run on a device with OS 4.2?
A: You just need to set the "iOS Deployment Target" to "iOS 4.1".
A: It depends what you mean by "built for". Backward compatibility is not defined by the release number of the SDK you are building against. For example, with the SDK 4.3, you can build applications that will run on iOS 4.2 (and earlier of course).
You define the minimum version of iOS your application will support, by filling in the Deployment Target entry of the target info page. If you put "4.3" in there, then your application will not even install on a machine running iOS 4.2 or earlier.
It also remains then your responsibility not to use APIs that are not available on the versions of iOS you want to support.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Perl: Decoding "garbled" unicode strings I'm working on a CGI script that is called from a piece of software (that I can't change). The variables submitted by the software are giving me problems, because if they contain non-ascii characters they look like this:
ÿFFFFDEetta er texti meÿFFFFF0 ÿFFFFEDslenskum stÿFFFFF6fum
instead of
Þetta er texti með íslenskum stöfum.
I've tried messing with the Encode::decode function but nothing has come of it - all I've gotten it to do is change how the ÿ gets represented.
So yeah, I'm kind of stumped. What do I do to change all the ÿFFFFDEs into Þs and so on, without resorting to replacing each non-ascii character individually (which is not a solution because this needs to work for languages I don't even speak)?
A: use Encode qw(decode);
use Encode::Escape qw();
$_ = 'ÿFFFFDEetta er texti meÿFFFFF0 ÿFFFFEDslenskum stÿFFFFF6fum';
s/ÿFFFF/\\x/g;
decode('iso-8859-1', decode('unicode-escape', $_));
# returns 'Þetta er texti með íslenskum stöfum'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: online platform for flex application? Is there any platform/compiler for creating flex application online? Any version will work. I know some action script online compiler but not able to find any flex online compiler.
A: There used to be one in the Flex 2 time frame; which Adobe created using the command line Flex compiler and ColdFusion. You entered your code into an input box, and then on the backend it would compile it using the cfexecute command.
If you Google "Online Flex Compiler" a bunch of blog posts about it come up, but it looks like the actual app is no longer available. Most likely because it was pretty useless. Writing code in a browser is not very productive.
A: Check out wonderfl: http://wonderfl.net/
Here's nifty example: http://wonderfl.net/c/y5Cx
Or are you looking for something different?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CSS3 multiple background images - support on mobile devices? Im mobile optimising my site with media queries. Is it safe to use multiple background images on the mobile optimised version? Mobile browsers are generally quite up to date so I would have thought this would be fine...
Thanks
A: Sure, you can use multiple backgrounds. The support is up-to-date with modern browsers: http://caniuse.com/#search=multiple%20backgrounds
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ASP.NET MVC Async Controllers and Active MQ Scenario: User saves an Order
Things need to be done to complete Order workflow:
*
*Save order to Database with a flag 'not acknowledged'.
*Push order to Active MQ and listen for acknowledgement message due to appear in another Q. Usually it takes from 1 minutes to unknown time to receive acknowledgement message in the other Q.
*When I receive acknowledgement update flag in Database.
I don't want user to wait until acknowledgement message received, so once Order saved successfully to the database user can navigate away from the web page. Currently I'm saving orders to Database using an Ajax post method and planning to call an Async action when saving to Database is successful. This Async action is suppose to work with Active MQ and wait indefinitely till it receive an acknowledgement.
Question: Is Async controllers is the right choice here? Or shall I write a Windows services which polls for the acknowledgement Q and update Database accordingly. Main objective to reduce complexity and maintenance overhead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Little Confused about the Microsoft Excel Interop Library I know how to make new columns, I know how to add a header to that column, but I am a little unsure about adding values programatically.
I am going to be looping through rows and then adding values to the new columns that I create based on some functions I perform on the Data Set. I thought a good way to start would be to just pick a row and loop through it and print out all the information in that row. If I could figure out how to do that, I could probably right all the code necessary to loop through appropriate rows and get the data I need. But I am a little confused about how to use this Range object...
Range rng = (Range)wkSheet.get_Range("A1", Type.Missing);
Lets say I wanted to print out all the Range Row information to a console? How would I loop through that Range and print out that information? Even change the information in the Range. I know how to change the value of a single row, the header, but changing multiple rows is alluding me.
A: object[,] values = (object[,])rng.Value;
Probably duplicate reading-from-excel
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Timezone issues with timestamps in the FQL table 'event' I'm having trouble with event timezones in the start_time and end_time fields in the event FQL table. I want to show the timestamp in a formatted date that accounts for the user timezone. Empirically, it appears the timestamps are in the PST timezone, so I convert them to GMT and add the user timezone, as contained in the timezone field in the user table. Conversion to GMT is performed by Java, with the following code (this should account for daylight saving time automatically):
long millis = 1000 * timestamp;
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
int offset = tz.getOffset(millis);
long timestampGMT = millis + offset;
However, this approach produces different results than the Facebook site.
For example I have an event with start_time=1317416400 and a user with timezone=2. Converting to GMT and adding the user timezone I get September 30th 2011, 16:00:00, but the Facebook site shows September 30th 2011, 14:00:00.
How can I obtain the correct (as in FB site) result?
Examples:
Summer:
http://www.facebook.com/event.php?eid=234094353309432
Created by a user on GMT+2
Time shown on the site: Friday, September 30 · 2:00pm - 7:00pm
start_time (from FQL): 1317416400
If it was UTC, then: Friday, September 30th 2011, 21:00:00 (GMT)
If it was PDT (with DST, so GMT-7), then: Friday, September 30th 2011, 14:00:00 (GMT-7)
Winter:
http://www.facebook.com/event.php?eid=254174591293234
Created by a user on GMT+2
Time shown on the site: Sunday, December 25 · 1:00pm - 4:00pm
start_time (from FQL): 1324846800
If it was UTC, then: Sunday, December 25th 2011, 21:00:00 (GMT)
If it was PST (no DST, so GMT-8), then: Sunday, December 25th 2011, 13:00:00 (GMT-8)
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Need to fetch distinct elements through XSLT I have a list of table elements under element named Query that may duplicate, I need to fetch distinct table elements (not its value but the tag/element name itself.
/ShopArea/Connection/Query/* lists the table names including duplicates.
Below is the XML
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="ShopArea.xslt"?>
<ShopArea>
<Connection name="Connection1">
<Report date="25-09-2011">
<Query id="1">
<TABLE1>1.1</TABLE1>
<TABLE2>1.2</TABLE2>
<TABLE3>1.3</TABLE3>
</Query>
<Query id="2">
<TABLE21>2.1</TABLE21>
<TABLE22>2.2</TABLE22>
<TABLE23>2.3</TABLE23>
</Query>
</Report>
<Report date="26-09-2011">
<Query id="1">
<TABLE1>26 1.1</TABLE1>
<TABLE2>26 1.2</TABLE2>
<TABLE3>26 1.3</TABLE3>
</Query>
<Query id="2">
<TABLE21>26 2.1</TABLE21>
<TABLE22>26 2.2</TABLE22>
<TABLE23>26 2.3</TABLE23>
</Query>
</Report>
</Connection>
</ShopArea>
I refered How to select unique nodes in XSLT but I'm not able to get it right.
A: I. XSLT 1.0. This transformation uses simple Muenchian grouping:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:key name="kChildByName" match="Query/*"
use="name()"/>
<xsl:template match=
"Query/*
[generate-id()
=
generate-id(key('kChildByName', name())[1])
]">
<xsl:value-of select="name()"/>
<xsl:text>
</xsl:text>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
When applied on the provided XML document:
<ShopArea>
<Connection name="Connection1">
<Report date="25-09-2011">
<Query id="1">
<TABLE1>1.1</TABLE1>
<TABLE2>1.2</TABLE2>
<TABLE3>1.3</TABLE3>
</Query>
<Query id="2">
<TABLE21>2.1</TABLE21>
<TABLE22>2.2</TABLE22>
<TABLE23>2.3</TABLE23>
</Query>
</Report>
<Report date="26-09-2011">
<Query id="1">
<TABLE1>26 1.1</TABLE1>
<TABLE2>26 1.2</TABLE2>
<TABLE3>26 1.3</TABLE3>
</Query>
<Query id="2">
<TABLE21>26 2.1</TABLE21>
<TABLE22>26 2.2</TABLE22>
<TABLE23>26 2.3</TABLE23>
</Query>
</Report>
</Connection>
</ShopArea>
the wanted, correct result (all different names of elements that are children of a Query) is produced:
TABLE1
TABLE2
TABLE3
TABLE21
TABLE22
TABLE23
II. XSLT 2.0: This transformation uses <xsl:for-each-group>:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/*/*">
<xsl:for-each-group select="Report/Query/*"
group-by="name()">
<xsl:sequence select="current-grouping-key(), '
'"/>
</xsl:for-each-group>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to realise long-term high-resolution timing on windows using C++? I need to get exact timestamps every couple of ms (20, 30, 40ms) over a long period of time (a couple of hours). The function in which the timestamp is taken is invoked as a callback by a 3rd-party library.
Using GetSystemTime() one can get the correct system timestamp but only with milliseconds accuracy, which is not precise enough for me. Using QueryPerformanceTimer() yields more accurate timestamps but is not synchronous to the system timestamp over a long period of time (see http://msdn.microsoft.com/en-us/magazine/cc163996.aspx).
The solution provided at the site linked above somehow works only on older computers, it hangs while synchronizing when i try to use it with newer computers.
It seems to me like boost is also only working on milliseconds accuracy.
If possible, I'd like to avoid using external libraries, but if there's no other choice I'll go with it.
Any suggestions?
A: Deleted article from CodeProject, this seems to be the copy: DateTimePrecise C# Class The idea is to use QueryPerformanceCounter API for accurate small increments and periodically adjust it in order to keep long term accuracy. This is about to give microsecond accuracy ("about" because it's still not exactly precise, but still quite usable).
See also: Microsecond resolution timestamps on Windows
A: Which language are you using?
*
*In Java (1.5 or above) I'd suggest 'System.nanoTime()' which requires no import.
Remember in Windows that time-slice granularity is 1000ms / 64 = 15.625ms.
*
*This will affect inter-process communication, especially on uni-processor machines, or machines that run several heavy CPU usage processes 'concurrently'*.
*In fact, I just got DOS 6.22 and Windows for Workgroups 3.11/3.15 via eBay, so I can screenshot the original timeslice configuration for uni-processor Windows machines of the era when I started to get into it. (Although it might not be visible in versions above 3.0).
A: You'll be hard pressed to find anything better than QueryPerformanceTimer() on Windows.
On modern hardware it uses the HPET as a source which replaces the RTC interrupt controller. I would expect QueryPerformanceTimer() and the System clock to be synchronous.
A: There is no such QueryPerformanceTimer() on windows. The resource is named QueryPerformanceCounter(). It provides a counter value counting at some higher frequency.
Its incrementing frequency can be retrieved by a call to QueryPerformanceFrequency().
Since this frequency is typically in the MHz range, microsecond resolution can be observed.
There are some implementations around, i.e. this thread or at the Windows Timestamp Project
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Using CSS @Variables I am trying to use CSS Variables. I look online for tutorials and all of them worked so far.
Here's my CSS:
@variables {
defaultColor: #8E5050;
defaultBackGround: #E1DBC3;
}
body {
background: var(defaultBackGround);
}
a {
color: var(defaultColor);
}
I also tried:
body {
background: @defaultBackGround;
}
a {
color: @defaultColor;
}
None of them works, What am I doing wrong? Thanks
A: The variables you are using are not part of the normal CSS specification. It looks like you are writing in some CSS framework.
If you do want to use pure CSS, you are stuck with setting the values of colors / margins / padding manually every time. But a good "Search & replace"-function in your favorite text editor may help you there. :)
If you want to use these variables, @Petah has the right answer for you. :)
A: Use Native CSS3 Variables!
Variables are actually a native feature in CSS3 - you can read the spec at MDN. However, they are still a relatively new feature, so you may want to check out the Browser Support charts here before using them.
That being said, CSS Variables are supported by the latest versions of Chrome, Firefox, Opera, Safari and Microsoft Edge.
The following code shows an example of how CSS variables can be used:
:root {
--name: #ff0000;
}
p {
color: var(--name);
}
How does this work?
Variables can be used if they are defined on the parent container of the element - here I use :root so that the variable is accessible everywhere.
A variable can be defined using --name:content; where name is the name of the variable and content is the contents of the variable (this can be a color, like #ff0000, a size like 1em, or one of many more possible values).
Then, simply use var(--name) instead of a property in your CSS code, where name is again the name you called the variable.
A: I would use a CSS preprocessor such as Sass or Less.
A: From what I understand, variables aren't fully supported yet, but this is how you will set them when they are:
/* declare in :root with the usual browser prefixes */
:root {
var-myVariableColor: #f00;
-webkit-var-myVariableColor: #f00;
-moz-var-myVariableColor: #f00;
-ie-var-myVariableColor: #f00;
}
/* to reference encase in var() */
body {
background-color: var(myVariableColor);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Changing the log path on fly I am using log4j for logging activities in my application.I want to take the log path from data base.
now I need to configure my log4j properties dynamically.
can we do it on the fly we change the log4h logging path..
Please suggest.
Thanks
A: You should create a class what loads at the startup and configurate the log4j.
Here is a code what I used in a JavaEE project, what loads the configuration file from an outer directory:
public class InitListener implements ServletContextListener {
public InitListener() {
}
public void contextInitialized(ServletContextEvent sce) {
try {
File file = null;
file = new File(System.getProperty("catalina.base") + "/conf/query-log4j.xml");
DOMConfigurator.configure(file.toURL());
System.out.println("Log4J successfully configured!");
} catch(Exception e) {
System.out.println("There was an error when initialize the Log4J config!");
e.printStackTrace();
throw new RuntimeException(e);
}
}
public void contextDestroyed(ServletContextEvent sce) {
}
}
A: If you were using MentaLog, all you have to do was that:
yourLogger.setFilename("newfilenamehere.log");
Your log would be automatically re-opened with the new name. In my personal opinion, programmatic configuration is the way to go over XML and/or annotations. It provides unmatched flexibility and easy of use.
A: Create seperate properties file to hold Specific Enviroment related settings example:
**uatLog4j.properties**
#######################
UAT Settings
#######################
{Add your Settings here}
And another for sy production enviroment.
**productionLog4j.properties**
########################
PRODUCTION settings
########################
{Add your Settings here}
And then using say the IP Address or the Server Name to determine the deployed platform, pass the path from the database to the required enviroment properties file as required.
Alternatively you can use LogManager to retreive Logger instances or to operate on the current LoggerRepository. See Javadoc and a RepositorySelecter example.
NOTE:
You can achieve the same using XML.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: split function for C++ Is there a split type function for C++ similar to Java? I know of ignore, but I don't quite understand it, and how it'll work for my case.
My input is:
{
item = ball
book = lord of the rings
movie = star wars
}
My input given is an <attribute> = <value> and I have to store the two in different strings, or integers (depending on the value, for example, if its a number, use an integer).
A: Use Boost::tokenizer as it does what you want to do. From the manual:
// simple_example_1.cpp
#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>
int main(){
using namespace std;
using namespace boost;
string s = "This is, a test";
tokenizer<> tok(s);
for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg){
cout << *beg << "\n";
}
}
A: Use strtok(): http://www.cplusplus.com/reference/clibrary/cstring/strtok/.
Just know that its not re-entrant because it uses an internal static variable, so don't call it twice in nested loops or anything like that.
and EDIT:
This is a very cool SO solution that would tokenize the whole string by spaces - you'd have to process the values back together after the = but it would teach you STL well :)
Split a string in C++?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: how to implicitly `git push` from a local branch "X" to "origin/Y" Say you have a branch on your origin that has a ridiculously long name...
$> git branch -a
* master
origin/master
origin/branch-with-a-ridiculously-long-name
And when you work on that branch locally, you want to give it a less ridiculous name, like bob.
$> git checkout origin/branch-with-a-ridiculously-long-name
$> git checkout -b bob
$> git branch --set-upstream bob origin/branch-with-a-ridiculously-long-name
When it comes time to push, what can you do such that if you run:
$> git checkout bob
$> git push
then any local changes on "bob" will be sent to the "branch-with-a-ridiculously-long-name", and won't create a new branch on origin called "bob"?
I'm effectively after a way of making git push implicitly expand in to git push origin bob:branch-with-a-ridiculously-long-name.
I think setting git config push.default upstream goes part of the way, but I'm not sure how to deal with the fact that the local branch's name differs from the remote.
A: If you set push.default to upstream (or tracking in versions of git before 1.7.4.2), that should do exactly what you want when you run:
git push
... or:
git push origin
The git branch --set-upstream command that you ran, in combination with the config setting, should make that work.
I wrote a post about this unfortunate asymmetry between git push and git pull.
A: Is this what you're after?
http://markmcb.com/2008/09/21/multiple-remote-git-branches-with-different-local-names/
A: More recent versions of git (most 2.x versions) include the option to set all of this configuration in one command:
git checkout -b bob origin/branch-with-a-ridiculously-long-name
That will set the upstream of bob to the correct remote branch.
Alternatively if you have a local branch already, you can use the --set-upstream-to flag:
git checkout bob
git branch --set-upstream-to origin/branch-with-a-ridiculously-long-name
Both of these will correctly set the git config
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to solve cast issues in ValidationRule classes' properties? I need to create a few tests for the user roles in a web application. To minimize the description, one of the tests involves checking if a menu entry is displayed or not for an user.
For this test, I use a table called UserRoles, that looks like this:
sUserName bDoesntHaveMenuX
User1 1
User2 0
User3 1
bDoesntHaveMenuX is of type bit.
I have a class derived from ValidationRule that checks if a certain text is present in a page, based on a XPath expression to locate the node where to look for the text.
The public properties of this class are:
string XPathExpression
string Text
bool FailIfFound
The last one dictates if the rule should fail if the text is found or not found.
In the test I added a datasource for the table mentioned in the beginning, called DS.
For the request I'm interested in I added a new instance of my validation rule class, with the following values:
Text=MenuX
XPathExpression=//div[@id='menu']//td
FailIfFound={{DS.UserRoles.bDoesntHaveMenuX}}
Unfortunately, this doesn't work.
The reason seems to be that the data binding process creates a context variable
DS.UserRoles.bDoesntHaveMenuX has the value "False" or "True". The value is a string, so the binding results in a casting error.
My options, as far as I can think of, are:
*
*Change the validation rule to accept strings for FailIfFound. Not a valid
option, for 2 reasons: it's a hack and the same rule is used in
other places.
*Make a new validation rule that will use the above mentioned one,
and implement the FailIfFound as string. I also don't like this, for
the same reason as above. It's a hack.
*Make the test coded and do the proper cast before passing the data
to the validation rule. I don't like this one because I prefer to
have the test as coded only if there is no other way.
Which brings me to the question. Is there another way?
Thank you.
A: So the fundamental issue is that you have no control over how the data-binding treats the 'bit' data type, and it's getting converted to string instead of bool.
The only solution I can think of (which is sadly still a bit of a hack, but not so egregious as changing FailIfFound to string) is to create a WebTestPlugin, and in the PreRequestDataBinding or PreRequest event, convert the value from string to bool. Don't forget to add the plugin to your test(s) (easy mistake I have made).
Then when the validation rule is created it should pick up the nice new bool value and work correctly.
e.g.
string val = e.WebTest.Context["DS.UserRoles.bDoesntHaveMenuX"].ToString();
e.WebTest.Context["DS.UserRoles.bDoesntHaveMenuX"] = (val == "True");
I didn't actually try this... hope it works.
EDIT: round two... a better solution
*
*Change the FailIfFound property to string (in a subclass as you mentioned), so it can work properly with data-binding.
*Implement a TypeConverter that provides a dropdown list of valid values for the property in the rule's PropertyGrid (True, False), so in the GUI it looks identical to the rule having FailIfFound as a bool. You can still type your own value into the box when necessary (e.g. for data-binding).
*Add the path of the .dll containing the TypeConverter code to your test project's References section.
This is what I have started doing and it is much more satisfying than having to type 'True' or 'False' in the property's edit box.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Absolute positioned element width issue I've following DOM structure
<div>
<span>/* comment action */</span> //float:left
<span>/* like action */</span> //float:left
<span>/* other actions //float:right; position:relative;
<ul> //position:absolute;
<li>Set due date</li>
<li>Delete</li>
</ul>
</span>
</div>
The problem is, the width of list item is set to width of longest word. I want each list item to appear in one line (like block) and maximum width should as of longest list item, and show them one below other.
Here are some screen shots that will give much better idea.
http://imgur.com/IkbAI (max width of word "Options")
http://imgur.com/h6uHc (max width of word "time")
http://imgur.com/lNCQu (max width of word "Setduetime" when removed spaces)
How can I fix this? (I don't want to specify specific width to ul)
A: @Bongs; write like this:
ul{white-space:nowrap}
A: Why do you absolutely position the ul tag? That's causing you the problem with the width.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Ruby + Titanium mobile can Ruby be used to develop iphone app with Titanium mobile ? i read Titanium desktop can be developed with ruby, but is it possible for titanium mobile?
A: No, it cannot.
Ruby is available for desktop developement only. Like PHP, Python & Ruby.
For mobile development you can only use JavaScript in its provided API.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Help understanding this line in lisp (defun dump-db ()
(dolist (cd *db*)
(format t "~{~a:~10t~a~%~}~%" cd)))
The dolist makes it go through every element of the list *db* with the variable cd right?
and ~a means print it in a more readable form, but these two confuse me.
~{ ~} does this mean anything in between will be the way every element of *db* will be formatted?
What's the : in ~{~a:?
A:
[The] iteration directive ~{ [...] tells FORMAT to iterate over the elements of a list or over the implicit list of the format arguments. 1
The : isn't a format directive, it's just printed verbatim in after each element:
> (format t "~{~a: ~}" '(foo bar))
FOO: BAR:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: best algorithm for search between arrays I have a problem I need to solve in the best algorithm I can find.
Let me describe the problem first.
I have a class A with number of Hashset<int> with Z number of items
A -> {x,y,z | x = {0,1,2} , y = {-1,0,9} ... }
B -> {x,y,z,k | x = {0,1,-2} , y = {-1,0,19} ... }
...
with an input of a new array of int { ... } entered by the user, the result should be the group with the most hashset with matching numbers between the input and the groups.
For example :
A : {[1,2,3][2,3,8][-1,-2,2]}
B : {[0,-9,3][12,23,68][-11,-2,2]}
Input :
[2,3,-19]
result A : {[2,3][2,3][2]}
result B : {[3][][2]}
A : 3
B : 2
A is the correct answer.
Or something like that .
Yes, I know it's a subjective question but it's for a good cause.
A: apparently you want to use C# to implement this. I don't know if this is the best algorithm (in whatever context) but you could use LINQ to write it down very plain and simple:
int[][] arrays = new[] { new[] { 1, 2 }, new[] { 2, 3 }, new[] {3, 4} };
int[] input = new[] { 1, 4 };
Console.WriteLine(arrays.Count((itemarray) => itemarray.Any((item) => input.Contains(item))));
in an array of int arrays this finds the number of arrays that have at least one of the values of the input array. this is what you're doing, though I'm not sure if it's what you're asking of us.
A: Given a sample class HashHolder and an instance A of it:
public class HashHolder
{
public HashHolder()
{
Hashes = new List<HashSet<int>>();
}
public List<HashSet<int>> Hashes { get; set; }
}
You can group by hashset and take the maximum count between all groups:
var maxHash = A.Hashes.GroupBy(h => h)
.Select(g => new { Hash = g.Key, Count = input.Count(num => g.Key.Contains(num)) })
.OrderByDescending(g => g.Count)
.FirstOrDefault();
The result will then be maxHash.Hash if maxhHash is not null.
A: Assuming you have an unknown number of samples to check on the input set, this Linq query should do the trick.
from sample in samples
let intersectedSets =
from set in sample
let intersection = input.Intersect(set)
where intersection.Count() > 0
select intersection
orderby intersectedSets.Count() descending
select intersectedSets;
The top-most element is your desired sample, thus yourCollection.First() will yield your result set - In your given example:
var samples = new[] {
new[]{
new[]{1, 2, 3},
new[]{2, 3, 8},
new[]{-1, -2, 2}
},
new[]{
new[]{0, -9, 3},
new[]{12, 23, 68},
new[]{-11, -2, 2}
}
};
var input = new[]{2, 3, -19};
var result =
(from sample in samples
let intersectedSets =
from set in sample
let intersection = input.Intersect(set)
where intersection.Count() > 0
select intersection
orderby intersectedSets.Count() descending
select intersectedSets).First();
result.Dump(); // LINQPad extension method
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Sending float arrays over c++ sockets between windows and linux I wish to send float array data from between a windows client and linux server (bi-directionally). Most queries in the forum address slightly advanced issues like c++ to java etc. My array could be as large as 1024x1024. Which is the best approach to this problem? Please show by pseudocode and real code example if possible. I prefer using the native winsock library for this.
Thanks
Thanks all,
I think sending the floats as char array might be the simplest of all. I am not worrying about bandwidth since I won't be sending data that often, but the other recommendations seem so demanding for a quick fix.
A: You may use protobuf library.
A: If you want to be really portable, then sending the floats as strings might be the best way to go.
That said, if you are okay with assuming that all computers will be using the IEEE754 floating point standard (which is a valid assumption for PC/Mac/Linux programming these days) then you can just send the raw data verbatim (i.e. send each float as 4 bytes via memcpy()).
The only wrinkle is if you want to deal with machines that use different endian-ness... e.g. sending from an Intel to a PowerPC machine. In that case, one of the machines will need to reverse the ordering of the 4 bytes before it sends them (and after it receives them) so that it will still interpret them the same as its counterpart. (There is no ntohf() or htonf() function, but you can byte-swap a float manually by memcpy()ing it to a int32_t, then byte-swapping the int32_t and sending that... on reception you would recv() the data into an int32_t, byte-swap the int32_t, then memcpy() the result into a float. Note that casting-and-assignment isn't sufficient here, you must use memcpy() to copy the data from int32_t to float and vice versa -- otherwise the lack of interoperability between the floating point and integer registers on some CPU types (e.g. Intel) will bite you and give you wrong results)
A: Sending floats between two different boxes is not a good idea. The internal representation of floats is not guaranteed by the standard, so a bit for bit copy of a float may result in different values on the two machines.
You could convert the floats to strings and back again, but this isn't particularly efficient (for the processor or bandwidth).
A: As lollo says, you can use Google Proto Buffers. But if you just want to send these floats, you don't want the WHOLE complex stuff.
You can serialize the float to bytes, send them and read them on the other end. Make sure that both compilers/OSs uses the IEEE float format (which is true for mainstream compilers/OSs).
Check also this question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Access ograph insights from another app without admin? Been trying to get insights data from a page in another app (without admin), yet no luck.
Been using Facebook API to access 'insights' through Open Graph. I have two Facebook profiles:
*
*one being the app holder
*the other being some Facebook page not
related to the app.
I am able to get the data when the 'app holder' has admin rights on the 'Facebook page'.
I saw Odata app and tried that, yet I wanted to keep it within the Facebook app control.
I have also linked the application with the page, hoping that will work (yet no joy).
Am I missing some 'Facebook App setting' that I can use or is this not possible?
Any thoughts much appreciated.
A: Read the instructions on this page, it explains how to do it: obtaining a permanent facebook oauth access token
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Toast isn't working in listener I want to open a Toast, but it doesn"t seem to work in a listener (of Smack), like this example:
private ChatManagerListener chatManagerListener = new ChatManagerListener() {
public void chatCreated(Chat newChat, boolean createdLocally) {
if(!createdLocally) {
Toast.makeText(mCtx, "CHAT CREATED", Toast.LENGTH_SHORT).show();
// do some stuff
}
}
};
If I use the Toast-code somewhere else in the class, it works, as long as it isn't a listener.
A: runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(Activity.this, "import finished", Toast.LENGTH_SHORT).show();
}
});
A: Make sure you're assigning the appropriate Context. Your mCtx should be the context of the parent class. Try assigning it like this: ParentClassName.this
A: Are you sure that it goes inside the if condition?
If so, then I think you are not getting the context there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Does thrift support sending data over websockets? I would like to use thrift with a Java server sending data to a browser using websockets. Is this possible?
A: According to this issue: https://issues.apache.org/jira/browse/THRIFT-2355 Thrift recieved support for web sockets in the javascript compiler for version 0.9.2.
A: In thrift there are 2 important things: protocol, and transport. Protocol defines how is data serialized into the data stream. And transport defines how are those streams of data exchanged between communicating entites.
There is json protocol in thrift which is supported by javascript, but as far as transports go I think Thrift supports only 2 transports raw tcp, and http. Later can be used to invoke operation on a HTTP server, and fetch the result from it, but not the other way around as you need it.
I guess you might be able to use json protocol, but you would need to roll your sleeves up and implement your own websockets transport. This could be a a non trivial task.
A: As of v.0.9.0 of Thrift, the answer is no.
On the client side, the javascript generated uses AJAX for it's transport as seen in Thirft.js library, so if a client was to use a WebSocket, then transport in Thrift needs modified.
On the server side, the Java code shows a socket server, but I believe it doesn't have the handshaking needed for the WebSocket server side code. Again, probably be added somewhat easily. It probably makes more sense for you to use jWebSocket as your server and the Java object classes created by thrift than the Thrift version of the server. You can inspect the code to know it better in Thrift. see /lib/java/src/org/apache/thrift/ section of the trunk in Thrift.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Java collapsible if statements I use PMD to check my code. It gives me very useful hints in most cases, but I can't figure out what could be improved in the following scenario.
The original code looks something like this:
if ((getSomething() != null && getSomethingElse() != null)
|| (getSomething() == null && getSomethingElse() == null))
{
...
}
PMD tells me:
Sometimes two 'if' statements can be consolidated by separating their
conditions with a boolean short-circuit operator.
For simplicity, let's just use a and b as boolean variables. Then this piece of code looks like this:
if ((!a && !b) || (a && b))
This can be transformed to one of the following:
if ((!a || b) && (a || !b))
if (!(a^b))
and finally
if (a==b)
So I simplified my code to
if ((getSomething() == null) == (getSomethingElse() == null))
However, PMD keeps complaining (in fact about all three versions). Is this a false positive or is there a better way of writing the if-condition?
A: The problem was something different. The if-statement was the only code inside another if (the code comes from a validation-method):
if (...)
{
...
}
else if (...)
{
...
}
else if (...)
{
if ((getSomething() == null) == (getSomethingElse() == null))
{
...
}
}
What the PMD-message means, is that I could combine the conditions of the last else-if and the inner if-clause:
if (...)
{
...
}
else if (...)
{
...
}
else if (... && ((getSomething() == null) == (getSomethingElse() == null)))
{
...
}
However, I'm not sure, if I'll do this, because the original version seems much clearer to understand.
A: if ((a != null) && (b != null) && (a==b))
..although personally, I'd do the null checking prior to this if statement so I could handle the a == null and b == null cases individually
A: The issue is that large blocks of conditionals are difficult to reason about.
OTOH, not every warning PMD emits needs to be paid attention to--consider the ROI. Is it worth refactoring or restructuring to make it cleaner? Can the same functionality be handled in a different way?
If it's not worth it, don't bother.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jQuery UI - Custom widget - Datepicker to Whole Year Calendar i want to display whole year with jquery ui. is it possible to cut down the code to just whole year Calender?
A: Set the "defaultDate" to the 1th of january, and then set "numberOfMonths" to 12.
http://jqueryui.com/demos/datepicker/#multiple-calendars
Edit: you don't have to set the defaultDate to 1th of january, it depends on the date you want the calender to start.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: can not seem to enable cache in ajax call I am have a problem with cache being disabled
I have this function call below:
When i watch the console i always see the ?_= added forcing to reload and i have a number of them
//mydomain/inc/js/jqSelect/jquery.selectBox.js?_=1317158809279
from what i have read , by default cache is set to true, but i tried setting it anyways
is there somewhere else that there is a flag set or something?
thanks
Randy
function(){
$.ajax({
url: "/secure/",
type: 'GET',
data: data,
cache: true,
beforeSend: function(){
$('#secureLoading').animate({width: "600px"}, 250);
$('#iframebody')
.fadeOut(250)
.find('.smallDdb')
.selectBox('destroy');
},
error: function(jqXHR, textStatus, errorThrown){
},
success: function(data){
$('#iframebody').html(data).fadeIn(250);
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: EventHandler and remoting In my application there is a clss containing an event of type EventHadler and this class should be remoted in another application (it must treat those events). First parameter of this EventHandler is object o (object in which event was fired). Is this parameter make sense in another application or not? These events will be calling ? Sorry for complicated question but I can't express my thought clearly while.
A: It depends on whether or not anyone is going to use the sender parameter.
If they are, then it depends on what the object is; if it is something that is only significant to the app domain that the object is in, then you need to make sure that the object derives from MarshalByRefObject so that the calls from the client can be remoted back to the instance on the server.
If it makes sense to send the sender by value, then you have to make sure that it is serializable.
That said, events over remoting is usually a bad idea. A better solution is to create an assembly with an interface that can be shared between the client and the server. This interface contains methods that would be implemented on the client (with a base class of MarshalByRefObject) and an instance of that implementation would be passed to the service. The service would then store this reference and make the calls on the implementations of the interface whenever you wanted to raise an "event".
WCF abolishes the concept of events over distributed calls, opting for exactly this pattern, using a callback interface when the client wants to be notified of events by the server.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Facebook Registration PLugin question I'm working on using the fb registration plugin on my sites. Sometimes a site doesn't support iframes. Is there another version of this script below that works without iframes or is there a workaround?
<iframe src="https://www.facebook.com/plugins/registration.php?
client_id=113869198637480&
redirect_uri=https%3A%2F%2Fdevelopers.facebook.com%2Ftools%2Fecho%2F&
fields=name,birthday,gender,location,email"
scrolling="auto"
frameborder="no"
style="border:none"
allowTransparency="true"
width="100%"
height="330">
</iframe>
thanks for any help
A: I don't understand what you mean by the idea that a site 'doesn't support iframes', but to answer your question, the Registration plugin is only available as an iFrame and i'm not aware of any other way to use it.
There's no reason you couldn't implement the Registration plugin's functionality yourself using the regular APIs if you needed to for some reason. The registration plugin just optimises a particular use-case ('sign up for a site with the possibility of using Facebook account information') and makes it faster to implement.
A: Yes there is. You can use the XFBML version of the plugin. This allows you to not only do what you are asking but to validate custom fields. This is what I choose to use on my application. However, I am not sure if fb is going to deprecate this or not come Jan 1st. Considering there is no replacement, it would be a little messed up if they did. For information on how to use and implement this see this link:
http://developers.facebook.com/docs/plugins/registration/advanced/
Brandon
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problems in jQuery when hovering an image over the image? I have a page listing the images. And when I hover on that image it will display the play icon over the image.
I have written some jQuery code for that:
$('#hovervideo').mouseenter(function (){
var isviddiv = $(this).find('.video-thumb');
if(isviddiv.length){
isviddiv.css('display','block');
}
console.log(isviddiv.length);
});
$('#hovervideo').mouseleave(function (){
var isviddiv = $(this).find('.video-thumb');
if(isviddiv.length){
isviddiv.css('display','none');
}
console.log(isviddiv.length);
});
Html Part
<h1 class="productvideo" id="hovervideo"><a href="#"><img src="images/tst-img.jpg" alt="" /></a>
<span class="video-thumb"></span>
</h1>
but it will work only for one image. bcoz the id "hovervideo" is same for all the H1. but i want it in all the image hover effect.
Can any one suggest me what to do.
Thanks
A: Use the class selector instead, add the class "test-image" to all images as so:
<h1 class="productvideo" id="hovervideo"><a href="#"><img src="images/tst-img.jpg" class="test-image" alt="" /></a>
<span class="video-thumb"></span>
</h1>
Then change the script to use the class selector
$('.test-image').mouseenter(function (){
var isviddiv = $(this).find('.video-thumb');
if(isviddiv.length){
isviddiv.css('display','block');
}
console.log(isviddiv.length);
});
$('.test-image').mouseleave(function (){
var isviddiv = $(this).find('.video-thumb');
if(isviddiv.length){
isviddiv.css('display','none');
}
console.log(isviddiv.length);
});
A: You cannot have more than one element with the same ID. Id should be a unique identifier.
If you want the event to be bound to multiple elements, simply select them by class:
$('.productvideo')...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting value back from ListBox to EventHandler in WP7 In my WP7 application I have ListBox control that binds with List<ItemTemplate> collection. On each ListBoxItem I have Click event which navigates to DisplayItem.xaml. Each ItemTemplate object has Id property which has to be passed to DispalyItem.xaml. I know that I can pass this value from Click EventHandler to DisplayItem.xaml using QueryString but how do I pass it from ListBox item to EventHandler ?
<ListBox x:Name="listBoxItems">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Ellipse Fill="red" Width="30" Height="30"></Ellipse>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding Status}" FontSize="35" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<HyperlinkButton Content="{Binding ItemContent}" Name="itemButton" Click="itemButton_Click"/>
</StackPanel>
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Header="edit"/>
<toolkit:MenuItem Header="delete"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Id property is not mentioned in the above code because I just simply didnt know where to place it. Generally I want to know how can I get Id property back to the click EventHandler ? I'm sorry if this question is basic for you but I'm new to that and i wasn't sure how to google that.
A: If you're really new to Windows Phone 7, you may want to stop using the "Click" event and instead use the ListBox.SelectionChanged event. If you are bound to List<MyObject>, you could do the following:
In your XAML:
<ListBox SelectionChanged="NavigateToMyDetail" ... >
Then in the code behind, you would have something like this:
private void NavigateToMyDetail(object sender, SelectionChangedEventArgs e)
{
// Make sure that the ListBox change wasn't due to a deselection
if(e.AddedItems != null && e.AddedItems.Count == 1)
{
MyObject selectedItem = (MyObject)e.AddedItems[0];
// Now you have access to all your MyObject properties
// and you can pass that to your new page as a parameter
NavigationService.Navigate(new Uri("DisplayItem.xaml?ItemID=" + selectedItem.id.ToString(), UriKind.Relative));
}
}
And you can get that ID with the following code (probably in your "OnNavigatedTo" method).
string myItemID = null;
if(this.NavigationContext.QueryString.ContainsKey("ItemID"))
myItemID = NavigationContext.QueryString["ItemID"];
Hope that helps. The other way to try to get it is to give your ListBox a x:Name and then references it in your Click handler like:
private void MyClickHandler(object sender, System.Windows.RoutedEventArgs e)
{
MyObject selectedObject = (MyObject)MyListBoxName.SelectedItem;
}
A: There is a much simpler solution if you use data binding with an MVVM viewmodel behind it.
Simply bind you view to a property in the view model for the listbox "Source" and then also do the same for the ListBox "SelectedItem" or "SelectedIndex" properties, then you will have all you need accessible where ever you needed.
Only think to be aware of (as I'm uncertain if it ever got fixed) is to fixed the selected index property when an item has been selected, if you do not reset it to -1 then if the user returns to the list they cannot select the same item. (do this in the codebehind for the click event)
Also if you use MVVM and databinding you can enact an action from the change of the Selected item rather than using Code behind to drive the direction, always an option to keep things simple (but not mandatory)
A: I have also came to my own solution. I'm not sure If its correct bit its certainly solving my problem for now.
I found this CommandParameter property of object HyperlinkButton. I bound my MyObject.Id property value to it.
<HyperlinkButton Content="{Binding ItemContent}" Click="itemButton_Click" CommandParameter="{Binding Id}" />
Then in my EventHandler i said:
private void itemButton_Click(object sender, RoutedEventArgs e)
{
HyperlinkButton butt = sender as HyperlinkButton;
NavigationService.Navigate(new Uri("/ViewItem.xaml?itemId=" + butt.CommandParameter.ToString(), UriKind.Relative));
}
It works as I need it to work but I'm not sure If i should use it in my applications in the future.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I retrieve the path to my dylib at runtime? On OS X, how can code in a dylib find the path it was loaded from, at runtime?
Coming from a Windows background, I'm used being able to call GetModuleFileName(dllHandle,...).
There exists NSGetExecutablePath() which will give me the path of the executable for the current process. Is there an equivalent to give me the current dylib path?
A: Use dladdr(3). Given a memory address, dladdr() outputs a structure that has, amongst other data, the path of the library containing the address. For example, inside your library:
#include <stdio.h>
#include <dlfcn.h>
void test(void) {
Dl_info info;
if (dladdr(test, &info)) {
printf("Loaded from path = %s\n", info.dli_fname);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Composite Chart + Objective C I want to implement below chart like structure.
Explanation:
1. Each block should be clickable.
2. If the block is selected, it will be highlighted(i.e. Red block in figure).
I initially google for this but was unable to find. What should be "Drawing logic" corresponding to this with animation?Thanx in advance.
A: I think you need to use MCSegmentedControl.
You can get it from here.
A: Generally speaking, I'd have an image for the outline with a transparent middle, then dynamically create colored blocks behind it of the appropriate colors, with dynamic labels. The highlighting is a little tricky, but could be done with a set of image overlays. One could also try to shrink and expand fixed images for the bars/highlighting, but iPhone scales images poorly.
(Will it always be 4 blocks? There are a couple of other ways to manage it using fixed-size images overlaying each other.)
A: Maybe you should look into using CALayer for this?
A: U need to implement this type of logic using button. Just scale button width according to percentage.
And to make round rect button like appearance use the code below and don't forget to import quartz-core framework in class file.
And to scale first and last button as you need some overlap from nearby button.
btn.layer.cornerRadius = 8.0;
btn.layer.borderWidth = 0.5;
btn.layer.borderColor = [[UIColor blackColor] CGColor];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Options for high performance SQLite I'm developing an embedded system, which needs to store and retrieve data very frequently. I am expecting perhaps 100s of writes per second and 10s of reads. The data will arrive in bursts rather than continuous.
I would like to use SQLite to store all this data, but since it is a flash file-system, the writes (INSERTS & UPDATES) are much too slow. I tried setting synchronous=off and this does certainly improve the performance, but I am nervous about corrupting the database.
In my application, power failures would be a rare, but real possibility. I can live with losing some recent data, but absolutely cannot risk losing all the data due to a database corruption.
I also thought about using an in-memory SQLite database as the primary database and periodically sync it to the file-system as discussed in Synchronizing sqlite database from memory to file
Are there any other options I should consider?
A: When a burst of data arrives, be sure to do the series of inserts and updates within a single transaction.
sqlite3_exec(handle, "BEGIN TRANSACTION", NULL, NULL, NULL);
for ( ... ) {
// Do your inserts/updates
}
sqlite3_exec(handle, "END TRANSACTION", NULL, NULL, NULL);
By default, SQLite puts every insert/update in its own transaction. This can make SQLite quite slow if the underlying filesystem is slow. By declaring your own transactions, you can significantly reduce the amount of actual writing that is done to the filesystem, thereby substantially increasing SQLite's performance.
A: I don't know how large are your data sets, but if they are not too big, then the WAL mode might help. You may experiment with "PRAGMA synchronous=1": This setup does not sync after each transaction, but once in a while. (Default: When 2 MB of new data is written.) SQLite docs say that you might loose a few recent transactions, but the DB won't be corrupted.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: YARD: document custom getter/setter pair like attr_accessor I'm using YARD to document my project. YARD document attributes created with
attr_accessor :some_attribute
in a separate section "Instance Attribute Summary". Now I have another attribute, but with custom setter and getter
def some_other_attribute
# ...
end
def some_other_attribute= value
# ...
end
so basically my question is, how can I get YARD to document this pair of setter/getter just like attr_accessor in the previous case, and list some_other_attribute within "Instance Attribute Summary"?
A: As of 0.8 (which is in pre-release right now), the @!attribute directive is the recommended way to denote that an object is an attribute. The @attr_* tags are deprecated in favour of this directive. You could also do (in 0.8.0+):
# @!parse attr_accessor :some_attribute
To parse code that isn't necessarily executed by Ruby. Prior to 0.8, you could just add the attr_accessor directly and then redefine the setter/getter as follows:
class MyClass
attr_accessor :foo
def foo; something_else end
def foo=(v) something_else(v) end
end
Ruby shouldn't mind, except that in ruby -w it will warn about method redefinitions. If this bugs you, you can add undef foo, foo= in there too. It's a little messy (if you care about -w), which is why we added things like @!parse and @!attribute.
A: You should be able to use the @attr tag on the class:
# @attr [String] name The name of this object.
class MyClass
def name
end
def name=
end
end
There are other tags (like @attr_reader and @attr_writer) than can also be helpful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to delete all roles of a list of users using membership. -MVC I have a list of username's in a string array . l wanna give the all selected users a new role .I can easily give that using membership
But before doing that i want remove all roles assigned to selected users. How can i do that ..
or at least how can i remove all roles assigned to a particular user?
A: Roles.RemoveUserFromRoles(user.UserName, Roles.GetRolesForUser(user.UserName));
A: Try this for one user
Roles.RemoveUserFromRoles
or
Roles.RemoveUsersFromRoles
for many.
Here is a good tutorial about Roles, http://www.asp.net/security/tutorials/assigning-roles-to-users-cs
A: I know its old...but I was just looking for this myself:
MembershipUser mUser = Membership.GetUser((Guid)User.UserID);
foreach (var role in Roles.GetAllRoles())
{
Roles.RemoveUserFromRole(mUser.UserName, role);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: OpenCV as a static library (cmake options) I want to use OpenCV library in an embedded system and I need to compile my project using OpenCV as a static library.
How can I create the library using cmake options ?
A: To build OpenCV as static library you need to set BUILD_SHARED_LIBS flag to false/off:
cmake -DBUILD_SHARED_LIBS=OFF ..
But I think it is not enough for your task because you actually need to cross-compile library for you architecture. In case of Android or IOS such port already exists and you can simply use it. In case of another platform you need to create your own cmake toolchain file for cross-compiling and probably make a number of fixes in OpenCV build system.
A: The BUILD_SHARED_LIBS=OFF cmake option will create static libraries.
It should be noted that at the time of writing this, OpenCV does not really support static build, in that the result will not be useable when installed somewhere.
https://github.com/opencv/opencv/issues/21447#issuecomment-1013088996
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "49"
}
|
Q: GPS Data time to distance base transformation I am developing an application that logs a GPS trace over time.
After the trace is complete, I need to convert the time based data to distance based data, that is to say, where the original trace had a lon/lat record every second, I need to convert that into having a lon/lat record every 20 meters.
Smoothing the original data seems to be a well understood problem and I suppose I need something like a smoothing algorithm, but I'm struggling to think how to convert from a time based data set to a distance based data set.
A: This is an excellent question and what makes it so interesting is the data points should be assumed random. Which means you cannot expect a beginning to end data graph that represents a well behaved polynomial (like SINE or COS wave). So you will have to work in small increments such that values on your x-axis (so to speak) do not oscillate meaning Xn cannot be less than Xn-1. The next consideration would be the case of overlap or near overlap of data points. Imagine I’m recording my GPS coordinates and we have stopped to chat or rest and I walk randomly within a twenty five foot circle for the next five minutes. So the question would be how to ignore this type of “data noise”?
For simplicity let’s consider linear calculations where there is no approximation between two points; it’s a straight line. This will probably be more than sufficient for your calculations. Now given the comment above regarding random data points, you will want to traverse your data from your start point to the end point sequentially. Sequential termination occurs when you exceed the last data point or you have exceeded the overall distance to produce coordinates (like a subset). Let’s assume your plot precision is X. This would be your 20 meters. As you traverse there will be three conditions:
*
*The distance between the two points is greater than your
precision. Therefore save the start point plus the precision X. This
will also become your new start point.
*The distance between the two points is equal to your precision.
Therefore save the start point plus the precision X (or save end
point). This will also become your new start point.
*The distance between the two points is less than your precision.
Therefore precision is adjusted to precision minus end point. The end
point will become your new start point.
Here is pseudo-code that might help get you started. Note, point y minus point x = distance between. And, point x plus value = new point on line between poing x and point y at distance value.
recordedPoints = received from trace;
newPlotPoints = emplty list of coordinates;
plotPrecision = 20
immedPrecision = plotPrecision;
startPoint = recordedPoints[0];
for(int i = 1; i < recordedPoints.Length – 1; i++)
{
Delta = recordedPoints[i] – startPoint;
if (immedPrecision < Delta)
{
newPlotPoints.Add(startPoint + immedPrecision);
startPoint = startPoint + immedPrecision;
immedPrecsion = plotPrecsion;
i--;
}
else if (immedPrecision = Delta)
{
newPlotPoints.Add(startPoint + immedPrecision);
startPoint = startPoint + immediatePrecision;
immedPrecision = plotPrecision;
}
else if (immedPrecision > Delta)
{
// Store last data point regardless
if (i == recordedPoints.Length - 1)
{
newPlotPoints.Add(startPoint + Delta)
}
startPoint = recordedPoints[i];
immedPrecision = Delta - immedPrecision;
}
}
Previously I mentioned "data noise". You can wrap the "if" and "else if's" in another "if" which detemines scrubs this factor. The easiest way is to ignore a data point if it has not moved a given distance. Keep in mind this magic number must be small enough such that sequentially recorded data points which are ignored don't sum to something large and valuable. So putting a limit on ignored data points might be a benefit.
With all this said, there are many ways to accurately perform this operation. One suggestion to take this subject to the next level is Interpolation. For .NET there is a open source library at http://www.mathdotnet.com. You can use their Numberics library which contains Interpolation at http://numerics.mathdotnet.com/interpolation/. If you choose such a route your next major hurdle will be deciding the appropriate Interpolation technique. If you are not a math guru here is a bit of information to get you started http://en.wikipedia.org/wiki/Interpolation. Frankly, Polynomial Interpolation using two adjacent points would be more than sufficient for your approximations provided you consider the idea of Xn is not < Xn-1 otherwise your approximation will be skewed.
The last item to note, these calculations are two-dimensional and do consider altitude (Azimuth) or the curvature of the earth. Here is some additional information in that regard: Calculate distance between two latitude-longitude points? (Haversine formula).
Never the less, hopefully this will point you in the correct direction. With no doubt this is not a trivial problem therefore keeping the data point range as small as possible while still being accurate will be to your benefit.
One other consideration might be to approximate using actual data points using the precision to disregard excessive data. Therefore you are not essentially saving two lists of coordinates.
Cheers,
Jeff
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Teradata Default List There is this one table which contains the amounts and states that I need. However, this table contains a year information but I want month. For example, in the table it shows information for Kentucky for 2011..and thats it. For California it shows about 5 different years. But I need it to repeat by month.
So if in 2011 Kentucky had 12 total, then I need a query that shows 12 for January, February, May....repeatedly
Right now I get this output with a dumb query I have:
Kentucky 12 January
California 800 January
This is done easily by grouping by State, Quantity and Month
I want to make sure that no matter what the Quantity is, each State has ALL months
Kentucky 12 January
Kentucky 12 February
Kentucky 12 May
California 800 January
California 800 February
California 800 May
Any idea on how to do this with Teradata SQL?
A: The overall query would look something like this:
SELECT
state_quantities.state,
state_quantities.quantity,
all_months.month_name
FROM state_quantities
CROSS JOIN (
...
) all_months
What goes between the brackets for all_months depends on what you mean by "all months".
If you mean all months that appear in state_quantities irrespective of state (so if you have Kentucky with January, California with February and Florida with May, you'd only get those three months) you could use something like this:
SELECT
month_name
FROM state_quantities
GROUP BY month_name
If you want all 12 months, you would join to a table containing all 12 months. In the absence of that, you could use sys_calendar.calendar (syntax below might be off):
SELECT
CAST(calendar_date AS DATE FORMAT 'MMM') AS month_name
FROM sys_calendar.calendar
GROUP BY month_name
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Change the background in ListPicker´s FullMode in WP7? Anyone knows how to easily change the background in ListPicker´s FullMode? Do I need to set a style to be able to do that? I´ve tried that, but can´t find the right place to set the background... If it is a style that needs to be used, where exactly in that style can I set the background? Any help would be highly appreciated :)
Here is the standard Style for the ListPicker:
<Style TargetType="toolkit:ListPicker">
<Setter Property="Background" Value="{StaticResource PhoneTextBoxBrush}"/>
<Setter Property="Foreground" Value="{StaticResource PhoneTextBoxForegroundBrush}"/>
<Setter Property="FontSize" Value="{StaticResource PhoneFontSizeMediumLarge}"/>
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="Margin" Value="{StaticResource PhoneTouchTargetOverhang}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="toolkit:ListPicker">
<StackPanel>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="PickerStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="Expanded">
<Storyboard>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="Border"
Storyboard.TargetProperty="Background"
Duration="0">
<DiscreteObjectKeyFrame
Value="{StaticResource PhoneTextBoxEditBackgroundColor}"
KeyTime="0"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="Border"
Storyboard.TargetProperty="BorderBrush"
Duration="0">
<DiscreteObjectKeyFrame
Value="{StaticResource PhoneTextBoxEditBorderBrush}"
KeyTime="0"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<ContentControl
Content="{TemplateBinding Header}"
ContentTemplate="{TemplateBinding HeaderTemplate}"
Foreground="{StaticResource PhoneSubtleBrush}"
FontSize="{StaticResource PhoneFontSizeNormal}"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="0 0 0 8"/>
<Grid>
<Border
x:Name="Border"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding Background}"
BorderThickness="2">
<Canvas x:Name="ItemsPresenterHost" MinHeight="46">
<ItemsPresenter x:Name="ItemsPresenter">
<ItemsPresenter.RenderTransform>
<TranslateTransform x:Name="ItemsPresenterTranslateTransform"/>
</ItemsPresenter.RenderTransform>
</ItemsPresenter>
</Canvas>
</Border>
<Popup x:Name="FullModePopup">
<Border Background="{StaticResource PhoneChromeBrush}"> <!-- Popup.Child should always be a Border -->
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<ContentControl
Grid.Row="0"
Content="{TemplateBinding FullModeHeader}"
Foreground="{StaticResource PhoneForegroundBrush}"
FontFamily="{StaticResource PhoneFontFamilySemiBold}"
FontSize="{StaticResource PhoneFontSizeMedium}"
HorizontalAlignment="Left"
Margin="24 12 0 0"/>
<ListBox
x:Name="FullModeSelector"
Grid.Row="1"
ItemTemplate="{TemplateBinding ActualFullModeItemTemplate}"
FontSize="{TemplateBinding FontSize}"
Margin="{StaticResource PhoneMargin}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/> <!-- Ensures all containers will be available during the Loaded event -->
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</Grid>
</Border>
</Popup>
</Grid>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
A: There is no way to do this through templating.
The only way to do this is by changing the source of the control. (You'll need to change the Style for TargetType="controls:ListPicker".)
Specifically, you'll ned to change the contents of the FullModePopup.
A: I was wondering this same thing.
While there is no way of directly changing the background color of the ListPicker, it does follow along with the color of the PhoneChromeBrush resource, and thus you can override the color of all of those in your app to change the color of this background.
For example:
((SolidColorBrush)App.Current.Resources["PhoneChromeBrush"]).Color = Colors.Cyan;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Extending Django Admin for data import I'm trying to build an import feature/form in the django admin interface for a specific model.
I have already found the following question on Stackoverflow, however as I am new to django, I have not been able to wire it all up. Import csv data into database in Django Admin
I guess I understand how to work with Django objects and how to use the CSV reader module, but I have a heck of a time putting it all together in Django.
what i tried so far is this:
models.py
class RfidTag(models.Model):
"""
Available RFID-Tags from Importfile
"""
system = models.DecimalField(
_('system'),
max_digits=4,
decimal_places=0,
)
tagId = models.DecimalField(
_('tag ID'),
max_digits=4,
decimal_places=0,
)
serial = models.CharField(
_('serial'),
max_length=10,
)
# forms.py #
class RfidImport(forms.ModelForm):
file_to_import = forms.FileField()
class Meta:
model = RfidTag
fields = ("file_to_import",)
def save(self, commit=False, *args, **kwargs):
form_input = RfidImport()
file_csv = self.cleaned_data['file_to_import']
csv.register_dialect('excel-new', delimiter=';', quoting=csv.QUOTE_NONE)
records = csv.reader(file_csv, dialect='excel-new')
for line in records:
self.system = line[0]
self.tagId = line[1]
self.serial = line[2]
form_input.save()
datafile.close()
admin.py
class RfidTagAdmin(admin.ModelAdmin):
list_display = ('system','tagId','serial')
actions = ['import_tags']
def get_urls(self):
urls = super(RfidTagAdmin, self).get_urls()
my_urls = patterns('',
(r'^import/$', self.admin_site.admin_view(import_tags))
)
return my_urls + urls
def import_tags(self, request, queryset):
return HttpResponseRedirect("./import")
import_tags.short_description = "Import new RFID tags"
pass
admin.site.register(RfidTag, RfidTagAdmin)
views.py
@staff_member_required
def import_tags(request):
if request.method == "POST":
form = RfidImport(request.POST, request.FILES)
if form.is_valid():
form.save()
success = True
context = {"form": form, "success": success}
return HttpResponseRedirect("../")
else:
form = RfidImport()
context = {"form": form}
return HttpResponseRedirect("../")
My question is, is admin action actually the right way? Is there a better way to achieve what I am trying? And how do I wire this up? I have yet to see the form, after I select the import action and click "go".
A: The admin is the right way, however i wouldn't be using an action for this, those are designed to function over a list of objects and you don't need that. For this case simply extend the admin/index.html template and add an href to your view. After that you create a normal form in which you do your processing
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to free up resources in the new MVVMLight V4 I would like to know which is the best way to clean up resources in the newly fashioned ViewModelLocator for MVVM-Light V4. As far as I know, until version 3, the method ViewModelLocator.Cleanup() invoked the rest of the viewmodels' Cleanup() methods.
In version 4, with the new ViewModel Templates the Cleanup() methods are not included, nor they are generated when added to the ViewModelLocator. As I read in other similar questions related to V3, V4 was planned to centralize cleaning resources, so how can it be achieved?
Thank you.
Eddie
A: They are gone from the templates but are still a good standard practice (they may come back yet as V4 is still a beta)
Basically just implement the clean up method your self and ensure that it is called at the appropriate time on existing / clean-up of the app.
The clean-up function isn't called by the MVVM framework itself as it is, you have to call it manually. (shoot me if I'm wrong in that statement there :D)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Count down numbers Using C# (no Javascript) I want to display the numbers 10 to 1 one after the other. Each number should be displayed for 10 seconds.
Can anyone help in this.
Regards,
Vivek
A: You could have a meta-refresh for 10 seconds that refresh every 10 seconds. You could put the number in the query string and print it out to the page.
A: Take a look at the Timer
<asp:ScriptManager runat="server" id="ScriptManager1" />
<asp:Timer ID="Timer1" runat="server" Interval="10000"
OnTick="Timer1_Tick">
</asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1"
EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label1" runat="server" ></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
code behind
int counter=1;
protected void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text =1++;
}
for more info:
http://msdn.microsoft.com/en-us/library/bb398865.aspx
A: Without javascript (update panel etc) you could reload the page with a thread sleep delay:
string currentValue = Convert.ToString(Request.QueryString["val"]);
label.Text = currentValue;
if (Convert.ToInt32(currentValue) != 0)
{
currentValue = Convert.ToString(Convert.ToInt32(currentValue) - 1);
Thread.Sleep(10000);
Response.Redirect("Default.aspx?val=" + currentValue);
}
And kick things off by loading the page with a querystring: Default.aspx?val=10
A: Here:
test.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string t = Request.Params["t"] ?? "10";
string html = "<html><head><meta http-equiv=\"refresh\" content=\"10; url=http://localhost:3687/website/test.aspx?t=NEXT\"><head><body>NOW</body></html>";
html = html.Replace("NOW", t);
int next = (int.Parse(t) - 1);
if (next == 0) next = 1;
html = html.Replace("NEXT", next+"");
Response.ContentType = "text/html";
Response.Write(html);
Response.End();
}
test.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>
As @Mark Byers suggested, you can use meta refresh for this... and it works. Just change http://localhost:3687/website/test.aspx in html var to the URL of your ASPX page.
So you just need to open http://localhost:3687/website/test.aspx, that will generate the page with the next meta refresh URL and its parameter t set to the next lower value, and so on until it gets to 1.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: perl escape character in function calls When I use a perl statement like,
$workbook = Spreadsheet::ParseExcel::Workbook->Parse(\($mechanize->content))
where $mechanize is a WWW::Mechanize object, why do we escape the $mechanize->content?
A: It's not escaping, it's referencing. Read more examples here:
As a special case, \(@foo) returns a list of references to the
contents of @foo , not a reference to @foo itself. Likewise for %foo ,
except that the key references are to copies (since the keys are just
strings rather than full-fledged scalars).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using a Viewflipper with Gridview I've created a calendar which works fine, using a GridView which has an OnClickListener.
Now I wrapped the two GridViews in a ViewFlipper. The ViewFlipper has an OnTouchListener which also works fine, I can change the view by using ontouch when dragging. The problem is though that I have to drag on the EMTPY space in the Activity in order to use the ViewFlipper. When I drag on the GridView, nothing happends at all. But I can click on the GridView for OnClickListener.
xml:
<ViewFlipper android:id="@+id/details"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<GridView
android:id="@+id/weeks"
android:numColumns="1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="8">
</GridView>
<GridView
android:id="@+id/calendar"
android:numColumns="7"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</GridView>
</LinearLayout>
android code:
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// Get the action that was done on this touch event
switch (arg1.getAction())
{
case MotionEvent.ACTION_DOWN:
{
// store the X value when the user's finger was pressed down
downXValue = arg1.getX();
break;
}
case MotionEvent.ACTION_UP:
{
// Get the X value when the user released his/her finger
currentX = arg1.getX();
// going backwards: pushing stuff to the right
if (currentX - downXValue < -(arg0.getWidth()/3))
{
mdh.nextMonth();
calendar.add(Calendar.MONTH, 1);
currentMonth.setText(new SimpleDateFormat("MMMM yyyy").format(calendar.getTime()));
cAdapter.notifyDataSetChanged();
updateWeeks();
// Set the animation
vf.setInAnimation(arg0.getContext(), R.anim.push_left_in);
vf.setOutAnimation(arg0.getContext(), R.anim.push_left_out);
// Flip!
vf.showPrevious();
}
// going forwards: pushing stuff to the left
if (currentX - downXValue > arg0.getWidth()/3)
{
mdh.previousMonth();
calendar.add(Calendar.MONTH, -1);
currentMonth.setText(new SimpleDateFormat("MMMM yyyy").format(calendar.getTime()));
cAdapter.notifyDataSetChanged();
updateWeeks();
// Set the animation
vf.setInAnimation(arg0.getContext(), R.anim.push_right_in);
vf.setOutAnimation(arg0.getContext(), R.anim.push_right_out);
// Flip!
vf.showNext();
}
break;
}
A: gridview.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
return detector.onTouchEvent(event);
}
});
A: I had the same issue with a ViewFlipper and ScrollViews.
Try adding the onTouchListener to your GridView aswell and it should work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is the C++ boost binary serialization library backward/foward compatible?
Possible Duplicate:
Boost Serialization Library upgrade
I am trying to find a serialization solution for a C++ application. I would really like to be able to use boost binary serialization. If I were to serialize an object using an older version of the boost binary serialization library, will an application that is using a newer version of the boost library always be able to read it? What about vice versa? What is boost's philosophy on backward/compatibility on the serialization library?
A: They do it by incrementing the version in the header. So yes, it's compatible in a sense that you will get a graceful failure if you try to read binary data serialized with incompatible version as 1.45.0 release notes tend to indicate. Moreover there are bugs in 1.42 and 1.43 that break it!
Native binary archives created under versions 1.42 and 1.43 suffer from a serious problem. It's likely they won't be readable by this latest version. This due to the fact that 1.42 made some changes in the binary format of some types. Normally this could be addressed by detecting the library version number written into the archive header. Unfortunately, this library version number was not incremented at 1.42 as it should have been. So now we have two different binary archive versions with the same library version number.
I personally would put more faith in Google Protocol Buffers, it explicitly maintains backwards compatibility:
You can add new fields to your message formats without breaking backwards-compatibility; old binaries simply ignore the new field when parsing.
However it requires a bit more effort on the build system side as it involves using auto-generated code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: browser view zcml for="IPloneSiteRoot" returns 404 I wonder if anyone else has seen this before:
I have the following ZCML:
<browser:page
for="*"
name="workflow_action"
class=".bika_listing.WorkflowAction"
permission="zope.Public"
/>
When I try to visit siteroot/workflow_action, Plone tells me "This page does not seem to exist…"
The ZCML is being read - if I cause an error in the ZCML, Plone fails to start.
I've tried for="Products.CMFPlone.interfaces.IPloneSiteRoot" with the same result.
The code in WorkflowAction is not being invoked at all - if I place a pdb in __call__, it does not fire.
I have two similar ZCML definitions for different contexts, which work fine and look something like this:
<browser:page
for="bika.lims.interfaces.IAnalysisRequest"
name="workflow_action"
class=".analysisrequest.WorkflowAction"
permission="zope.Public"
/>
If I remove these other views, leaving only one view in the system with name="workflow_action", (the one for IPloneSiteRoot or "*"), the result is the same.
This seems like a very simple view - I don't know what other information I can put here?
Using Plone 4.0.7.
it must be me!?
A: Most likely your browserview raises an exception in the __init__() method and so the exception is ignored and never displayed, and the result usually is a 404 error.
A: I have a similar issue when add a Solgema.NavigationPortlet portlet on a Private state folder, then I found the browser:page navTreeitem in navigation.py raised a KeyError, which cause a 404 response for client browser.
Thanks for Giacomo's answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Passing PHP session to external ASP app I have been asked by a client if it was possible to build a PHP site which will pass sessions to an other app located on a different server which uses ASP.
I was wondering if any of you had a prior experience with this ? And if so how problematic can this task be? Is there any resources that you would recommend about that topic ?
Thanks a bunch for your insights.
A: The session is nothing but an identifier which points to some data on the server.
You can use session_save_handler and friends to manage how these are saved (e.g. store in a database instead of default files used by PHP) and parse/use the data connected to the session from you ASP code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Will an application built for Windows Phone 7.0 work with 7.1? I have built my app for WP7.0 - will it still work on WP7.1?
Do I need to rebuild it using WP7.1 sdk? If yes, how can i rebuild my current app to 7.1 mango?
A: Your 7.0-built application will work as expected in 7.1, but the fast application switching (multitasking) experience may not be optimal.
To rebuild/optimise your application for Mango:
*
*Install the updated tools (currently RC)
*In the Properties pane of the application, change "Target Windows Phone OS Version" to "Windows Phone OS 7.1"
*Update your code in App_Activated to only process the state if ActivatedEventArgs.IsApplicationInstancePreserved is false
Keep in mind that, for the next few weeks, you cannot release a bug fix for users with 7.0 once you release a 7.1 build.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Issues submitting form with jquery I have been trying to submit a form with jquery ajax but have been having issues.
When i check through firebug i see the value posted but it shows error from the url. I have this html
<form method="post" name="tForm" id="tForm">
<table>
<tr>
<td>Age</td>
<td><input name="age" id="age" value="" /></td>
</tr>
<tr>
<td><input type="button" id="submit" value="submit"/></td>
</tr>
</table>
</form>
</body>
My js file that submits the form has this piece of code
$(document).ready(function() {
$('#tForm').submit(function(){
var age = $('#age').val();
var msg ='';
$.ajax({
url:'testp.php',
type:'post',
data: {age:age},
beforeSend:function(){
alert(age);
},
success:function(data){
msg=data;
alert(msg);
},
complete:function(){
alert(msg);
}
})
})
});
My testp.php file just has this
<?php
echo 'ok';
?>
A: You need to stop the event from propogating. Your form attempts to submit in the standard method and since your form doesn't have an action you receive the error.
$(document).ready(function() {
$('#tForm').submit(function(){
var age = $('#age').val();
var msg ='';
$.ajax({
url:'testp.php',
type:'post',
data: {age:age},
beforeSend:function(){
alert(age);
},
success:function(data){
msg=data;
alert(msg);
},
complete:function(){
alert(msg);
}
})
return false;
})
});
A: Use $('#tForm').submit(function(e){ ... and then call e.preventDefault(); to prevent the form from being submitted in a regular (non-ajax) request.
However, I'd suggest you to have a look at the jQuery form plugin which saves you some work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Segmentation error in Xcode, debugger cant help me I have been going crazy trying to figure out what is done wrong. I admit I am inexperienced when it comes to C, but I don't know what is wrong. Is the way that I am accessing/using the struct incorrect?
EDIT: I keep getting EXC_BAD_ACCESS in debugger.
#include <stdio.h>
#include <string.h>
#define MAX_STRING 20
#define MAX_PLYR 16
typedef struct {
char pname[MAX_STRING];
int runs;
char *s;
} Team_t;
int
main(void)
{
Team_t *team_data[MAX_PLYR];
int i;
char *p;
char name[MAX_STRING];
FILE *inp;
inp = fopen("teamnames.rtf", "r");
for (i = 0; i < MAX_PLYR;) {
while ((fgets(name, MAX_STRING, inp) != NULL));
printf("Name(i): %s\n", name);
strcpy(team_data[i]->pname, name);
i++;
}
fclose(inp);
return(0);
}
Edit: Here's what's changed, still getting Segmentation Error
#include <stdio.h>
#include <string.h>
#define MAX_STRING 20
#define MAX_PLYR 16
typedef struct {
char pname[MAX_STRING];
int runs;
char s;
} Team_t;
int
main(void)
{
Team_t team_data[MAX_PLYR];
char name[MAX_STRING];
int i;
FILE *inp;
inp = fopen("teamnames.rtf", "r");
for (i = 0; i < MAX_PLYR; i++) {
((fgets(name, MAX_STRING, inp)));
if (feof(inp)) {
printf("End of stream\n");
i = MAX_PLYR;
}
else {
if (ferror(inp)) {
printf("Error reading from file\n");
}
printf("Name(i): %s\n", name);
strcpy(team_data[i].pname, name);
}
}
fclose(inp);
return(0);
}
A: You declare team_data but you don't allocate it; therefore it's pointing off into random memory, as are the imaginary contents of the array. You need to actually create the array, something like
Team_t *team_data[MAX_PLYR] = (Team_t**) malloc(MAX_PLYR * sizeof(Team_t *));
A: Use structs, not pointers (or if you insist using pointers the allocate space for those structs)
Team_t team_data[MAX_PLYR];
fgets(team_data[i].pname, MAX_STRING, inp)
A: when you write
Team_t *team_data[MAX_PLYR];
you are not allocating any memory for the actual Team_t records, instead you are setting up an array of pointers to records.
If instead you would write
Team_t team_data[MAX_PLYR];
you would have allocated the records. When you then want to copy into the team_data array you write instead
strcpy( team_data[i].name, name );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting some data from a PHP (json_encode) and now need to access it within the javascript? I am currently using Phonegap and XUI to create web app.
I am retrieving some data from an external domain using a http request via XUI.
This is working correctly and I receive the JSON data back correctly, see the data format below:
({"first":"John","last":"Smith","HighScore":"75"})
So now I want to be able to access the individual assets of the data using javascript.
x$('#test').xhr(URL,function() {
loggedin = this.responseText; // This is the data that has been received from the PHP file
if(loggedin != '1') // If not 1 then will let them in
{
alert(loggedin); // Alerts with the data recieved
}
else // Login incorrect
{alert('Sorry you login details were incorrect please try again.');}
});
I know its probably simple to do but I just can't seem to figure it out so any help would be much appreciated.
Thanks,
Kane
A: JSON object accessor syntax is object.key, so if this.responseText is {"first":"John","last":"Smith","HighScore":"75"} then you'd display Smith with this.responseText.last
An example usage for your alert could be:
alert('Hello ' + this.responseText.first + ' ' this.responseText.last + '! You currently have a high score of ' + this.responseText.HighScore + ' points! Play again!');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JScrollPane - CrossBrowser Scrollbars - Inconsistent and Crashing Using the JQuery plugin JScrollPane I have created a series of scrollable divs styled to look like those from the iPhone.
In theory it is all working but there are 3 fundamental problems.
*
*The plugin appears to be operating slowly and arbitrarily not scrolling certain content, tinning it up and breaking the scrollable panel. see example page http://www.golfbrowser.com/WebObjects/course-pack.html
*The scrolling is jerky and static, not smooth at all
*Also due to the nature of the site it could do with some elasticity. This is not a major priority though unlike the other two.
Any ideas?
Marvellous
A: You can set options for animated scrol :
$('selector').jScrollPane({
animateScroll : true,
animateDuration : 1000,
animateEase : 'swing'
});
More info about the plugin here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you keep a program running after Standby? I wrote a very simple .Net windows application that sits in the system tray and queries a db every 15 minutes. It works great without any issues, except when the computer goes into standby mode. After the user wakes the computer back up, the icon in the system tray is gone, and the program is no longer running.
How can I make it so that the program continues running after a standby or hibernate? I have very little control over the box settings since this is a corporate environment, but I could make changes to the program itself if there is a way to do this through code.
The OS is XP - some will be upgraded to Windows 7 soon.
Im using Visual Studio 2005.
A: It already runs after a system suspension, if it was running during the suspend! Probably, you application exits after having started the wake up or just before the suspension.
It could be a crash, but this would show an informative error message.
You need to track the application execution (i.e. A log system), then find the problem and fix it. Maybe the network connnection could be the point of failure, but not sure: the DB connection is still valid after a standby?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Remove an option from a Zend Radio Form Element An easy question.
I have a Zend_Form_Element_Radio element in my form with multioptions.
I'd like to remove an option in my controller.
I've found how to disable an option ...
$element = $membershipForm->getElement('myElement');
$element->setAttrib('disable', array('value'));
But how can I remove it?
With removing some decorators? Or is there a better way?
Thanks in advance!
A: Since every FormElement has a unique identifier it is pretty simply to remove it.
$form->removeElement($id); // most likely when removing from within the controller
$this->removeElement($id); // when removing from within the form object
$selectElement->removeMultiOption('value'); // To remove a single option from a select
That's all you need ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: backbone.js model.save doesn't set the id I've inherited a backbone js based app. I really like backbone and i'm just starting to get my head around it. From my understanding when model.save is called on a new entity it should post that to the server, the server should return the same json but with an id alloted and backbone should persist that id to the model so that further saves result in a PUT with the ID for update.
However, when I call model.save() and then try to get the model.id property, it's null.
Is this because I'm not doing it with a call back? So the property hasn't been set yet?
How would I set the success callback? calling model.save({success: function(){...}})doesn't work?
here is the actual call:
model.save(null, {
success: function () {
alert('success');
},
error: function () {
alert('error');
}
});
A: Something feels odd about this. Setting silent: true only makes it so none of the events get fired. Everything else should happen normally. In other words, don't assume that setting slient: true is the right answer here...
I suspect you are actually throwing an exception some place (probably with validation or something like that) and somehow, setting silent: true is causing everything to flow through.
I would strongly suggest that you remove this option and check your console or run with the debugger... I suspect you have a bug lurking around there some place.
Some suggestions: Take a look at the annotated source for the model.set function. It gets called before your success callback will get called. Inside of that function, there are several things that will happen if silent is false. These include validation, individual property change triggers, and a global change trigger. I would bet money that either the validation is failing or something that is listening to the changes is throwing an exception.
A: i needed to set the silent: true on the save:
model.save(null, {
silent: true,
success: function () {
alert('success');
},
error: function () {
alert('error');
}
});
A: I had the same issue, turned out to be because my custom parse was failing
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: WebView cocoa reloading webpage I have created a mac application using the WebView. But issue is that webView is reloading when
[webView mainFrameUrl] == newURL
why this problem is happening?? how to solve it.
A: Never compare strings with == You always use NSString's isEqualToString: method to check if the 2 strings are equal.
[[webView mainFrameURL] isEqualToString: newURL]
A: Besides the fact that the answer of theAmateurProgrammer is the correct one I want to give you another suggestion if it didn't solve your problem (since you didn't accept it).
Don't call mainFrameUrl frequently. Call it once and store it in another variable in the delegate method - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails help with devise Hey I was trying to make an association in devise so a user can just have a link to his association (like he can just click new post and he can make it) but i cant make it in devise like regular rails, it seems really common but no one seems able to help me (or they dont know what im talking about), I tried manually making come controllers and views but i get a problem (500 internal server error) heres my log file
https://github.com/Kevin-Mohamed/mygit
any other information needed let me know
A: OK, so this is off the top of my head, so YMMV. There's plenty of ways to go around this, but here's one way... Don't try to get devise to do more than it should.
class User
#devise links go here
has_many :pictures
end
class Picture
belongs_to :user
end
#routes
namespace :my do
resources :pictures
end
class ApplicationController
# current_user gets set here by devise
end
class PicturesController
def create
@picture = current_user.pictures.build(params[:picture])
end
end
#In your view you'd have the following, which would post to /my/pictures
=form_for(my_pictures_path(@picture)) do |f|
... etc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Setup IIS for automated webpage installation I have an installer which places the root folder of my webpage into the inetpub/wwwroot/ directory. I have three issues:
1.) The actual webpage as is it seen in IIS is an application using the DefaultAppPool with classic .net. When it is added to IIS, it is set up as an application, but there is no application name.
2.) On certain machines, the ASP.NET v1.1.4322 web service is not added to IIS. I'm not sure I can add this through code.
3.) My web app requires three ASP.NET web services, two of which are installed by default (v2.0.50727 and v4.0.30319). Once v1.1.4311 is added, the status of all three must be changed to allow. Again, I am unsure if this can be done through code.
All of the above issues are seen in Windows Server 2003 running IIS 6.0. MSDN's page on IIS is rather meek when it comes to these issues, so any help here would be appreciated, even if its a pointer to another forum. Thanks to all in advance!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to import a project to eclipse using jcraft ftp plugin NOTE: I am a new user so I'm not allowed to post images nor more than two links. Since my problem is quite silly I provided screenshots. If you have the time you can download a zip with the pngs here: http://dl.dropbox.com/u/1517193/images.zip
I'm trying to create a project by importing it with the remote system explorer and jcraft sftp plugin.
The project is a php one but I think this is not relevant
I start by creating a new project (image 1)
Then I right click on the project and choose import to project (image 2)
Then I select remote file systems as my source (image 3)
I have an already working sftp connection (image 4)
I browse to the folder where I have my project and I select it. By doing this I should have everything needed (image 5)
But it keeps saying "enter or select a source folder" and the finish button is greyed out.
I've selected a source folder. It should be the field in "from directory".
I've tried all combinations without success. I should be making some silly mistake because no one else is complaining about this.
Could you point me out to what I'm missing?
Thanks!
A: I got the same problem as you did.
Interestingly, I waited for a while (like 30 sec or so), the button becomes available by itself. Probably it was checking something about the source/destination folders on background.
Hope this help.
A: The solution of waiting work for me, but I have another one information.
In the bottom of the screen at the right I can see a little progress-bar with "Querying all". So i think there is really a script behind which is running.
Edit : Two hours after, the progress bar was always at the same state, so waiting wasn't à Solution for me…
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: I can't make my simple Selenium test work on any browser I have a very simple and classic installation:
*
*Windows 7
*WampServer with PEAR (PHP 5.3.5)
*PHPUnit and Selenium installed from PEAR
*Netbeans plugin "Selenium Module for PHP"
I'm trying to run the following test:
<?php
require_once 'PHPUnit/Extensions/SeleniumTestCase.php';
class WebTest extends PHPUnit_Extensions_SeleniumTestCase
{
protected function setUp()
{
$this->setBrowser('*googlechrome');
$this->setBrowserUrl('http://www.google.com');
}
public function testTitle()
{
$this->open('http://www.google.com');
}
}
*
*With *googlechrome, I get the error : "Cannot call method 'indexOf' of undefined".
*With *firefox, I get no error but a blank firefox page, and nothing happens.
*With *opera, it's almost fine : the page "google.com" is opened but does not loaded completely (missing one element of five) and the test fails after 30 seconds
*With *safari, the test starts (Safari and the Selenium window are opened) but that's it...
*I don't even want to try on Internet Explorer...
A: You could try defining the path to the browser.
For example
"*firefox C:\\Program Files\\Mozilla Firefox\\firefox.exe"
instead of just
"*firefox"
A: I finally understood my (stupid) error !
I just, somehow, installed a quite old version of the Selenium Server, absolutely unable to deal with recent browsers. The solution is obvious then : I updated my Selenium Server (by downloading the most recent .jar file there : http://seleniumhq.org/download/) and it all worked well !
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Making smarter jQuery code I was wondering if anyone has any idea on how I could rewrite this simple jquery code to be more efficient. It's of course working fine now but I imagine adding say 10 more items would make the code really big. I thought maybe I could add the classes to arrays and use some kind of loop? Not sure if that's the right approach though.
Here it is on jsfiddle:
http://jsfiddle.net/QVS9X/42/
and here's a sample of it:
JS:
$(".image1").mouseout(function() {
$(".default").show();
$(".cat1").hide();
}).mouseover(function() {
$(".default").hide();
$(".cat1").show();
});
$(".image2").mouseout(function() {
$(".default").show();
$(".cat2").hide();
}).mouseover(function() {
$(".default").hide();
$(".cat2").show();
});
HTML:
<div class="image1 image">
<p>Hover for cat 1</p>
</div>
<div class="image2 image">
<p>Hover for cat 2</p>
</div>
<div class="image3 image">
<p>Hover for cat 3</p>
</div>
<div class="default">
<p>Default Text</p>
</div>
<div id="cats">
<p class="cat1">Category 1 text</p>
<p class="cat2">Category 2 text</p>
<p class="cat3">Category 3 text</p>
</div>
A: If you can put a class of image on the divs that current have image1, image2 etc, then you can do this:
$(".image").hover(function() {
$(".default").toggle();
$("#cats p").eq($(this).index()).toggle();
});
This assumes that the image divs will be in the same order as the p tags inside #cats.
http://jsfiddle.net/QVS9X/44/
Example using data attributes:
JS:
$(".image").hover(function() {
$(".default").toggle();
$($(this).data('id')).toggle()
});
HTML:
<div class="image" data-id="#cat1">
<p>Hover for cat 1</p>
</div>
<div id="cats">
<p id="cat1">Category 1 text</p>
</div>
http://jsfiddle.net/QVS9X/55/
A: var myDefault = $(".default");
var myCat1 = $(".cat1");
var myCat2 = $(".cat2");
and then
$(".image1").mouseout(function() {
myDefault.show();
myCat1.hide();
}).mouseover(function() {
myDefault .hide();
myCat1 .show();
});
$(".image2").mouseout(function() {
myDefault.show();
myCat2.hide();
}).mouseover(function() {
myDefault.hide();
myCat2.show();
});
will reduce dom traversal, and improve performance
A: http://jsfiddle.net/QVS9X/45/
for example
<div class="image" data-id="1">
<p>Hover for cat 1</p>
</div>
<div class="image" data-id="2">
<p>Hover for cat 2</p>
</div>
<div class="image" data-id="3">
<p>Hover for cat 3</p>
</div>
<div class="default">
<p>Default Text</p>
</div>
<div id="cats">
<p class="cat1">Category 1 text</p>
<p class="cat2">Category 2 text</p>
<p class="cat3">Category 3 text</p>
</div>
$(document).ready(function() {
$(".image").mouseout(function() {
$(".default").show();
$(".cat"+$(this).data('id')).hide();
}).mouseover(function() {
$(".default").hide();
$(".cat"+$(this).data('id')).show();
});
});
A: First, I'd wrap the target divs in a parent div if they aren't already contained - like such:
<div id="images">
<div class="image1">
<p>Hover for cat 1</p>
</div>
etc..
</div>
Then you can bind a single event handler to handle all your cases -
$('#images').delegate('div[class^=image]', 'mouseenter mouseleave', function(e) {
$('.default').toggle(e.type === 'mouseleave');
$('#cats p').eq($(this).index()).toggle(e.type !== 'mouseleave');
});
EDIT
You can actually clean it up much further by removing the "image1", "image2", "image3" and just name the class "image". You can also remove the class from the <p> in #cats
See here for the revised example - http://jsfiddle.net/QVS9X/50/
EDIT 2
Someday, you'll add a cat div dynamically and wonder why the event handler isn't working... then you'll revisit my answer :) And be like... John really had a 100% complete solution. =p
A: Something along the lines of this should work:
<div class="default">Content</div>
<img class="image" data-ref="1" />
<div class="cat" data-ref="1">Cat 1</div>
<img class="image" data-ref="2" />
<div class="cat" data-ref="2">Cat 2</div>
$('.image').hover(function() {
$('.default, .cat[data-ref='+$(this).data('ref')+']').toggle();
});
http://jsfiddle.net/cugmj/2/
A: I would say you should make use of two things
*
*Use of data- attributes and jQuery's .data method
*A generic class used to identify all images that you want to have this behaviour
Then your code for all those items becomes:
$(".image").mouseout(function() {
$(".default").show();
$(".cat" + $(this).data('id')).hide();
}).mouseover(function() {
$(".default").hide();
$(".cat" + $(this).data('id')).show();
});
Live example: http://jsfiddle.net/sW8mZ/
A: Here is my code. http://jsfiddle.net/QVS9X/47/
examples:
$(document).ready(function() {
$('.image').hover(
function(){
$('.default p').html($(this).children('p').html());
},
function(){$('.default p').html('Default Text')});
});
Get rid of all the cat divs, have 1 div with default text, and then just update this text.
A: Here's my attempt, moving the category text to the div elements makes things a little easier.
http://jsfiddle.net/HV8vq/
* {
font-size: 20px;
text-align: center;
}
.image-cat-hover {
float: left;
width: 150px;
border: thin solid #CCC;
margin-bottom: 20px;
}
#cats, .default {
width: 450px;
}
<div class="image-cat-hover" data-category="Category 1 text">
<p>Hover for cat 1</p>
</div>
<div class="image-cat-hover" data-category="Category 2 text">
<p>Hover for cat 2</p>
</div>
<div class="image-cat-hover" data-category="Category 3 text">
<p>Hover for cat 3</p>
</div>
<div class="default">
<p id="placeholder">Default Text</p>
</div>
$(document).ready(function() {
var defaultText = $(".default").text();
$(".image-cat-hover").mouseout(function() {
$(".default").text(defaultText);
}).mouseover(function() {
$(".default").text($(this).data("category"));
});
});
Edit
I have to say I've learned alot answering and reading the other answers to this question. Here is an updated response:
http://jsfiddle.net/HV8vq/3/
<div>
<p id="defaultText">Default Text</p>
<p id="placeholder" style="display:none;"></p>
</div>
$(document).ready(function() {
$(".image-cat-hover").hover(function() {
$("#defaultText").toggle();
$("#placeholder").toggle().text($(this).data("category"));
});
});
A: Something like this
http://jsfiddle.net/QVS9X/51/
$(document).ready(function() {
var defaultCat = $(".default");
var cat1 = $(".cat1");
var cat2 = $(".cat2");
var cat3 = $(".cat3");
$(".image").mouseout(function() {
cat1.hide();
cat2.hide();
cat3.hide();
defaultCat.show();
});
$(".i1").mouseover(function() {
cat1.show();
defaultCat.hide();
});
$(".i2").mouseover(function() {
cat2.show();
defaultCat.hide();
});
$(".i3").mouseover(function() {
cat3.show();
defaultCat.hide();
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: iphone - replaceScene error:Terminating app due to uncaught exception 'NSRangeException',reason:'***-[NSMutableArray replaceObjectAtIndex:withObject:] I made a loading screen, where the program goes through a list of words, picks a six-letter word, and derives a list of words from the letters of that word.
Problem is, after all the initialization, when it gets to trying to change the scene, it spits out the error:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray replaceObjectAtIndex:withObject:]: index 4294967295 beyond bounds for empty array'
I have tried changing replaceScene to pushScene as well as runWithScene, but all of them spit out errors and do not proceed to the game scene.
Here's the stack:
2011-09-28 20:28:57.890 WordSearchPuzzleManiaIPhone[3524:207] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray replaceObjectAtIndex:withObject:]: index 4294967295 beyond bounds for empty array'
*** Call stack at first throw:
(
0 CoreFoundation 0x014f75a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x0164b313 objc_exception_throw + 44
2 CoreFoundation 0x014f0626 -[__NSArrayM replaceObjectAtIndex:withObject:] + 326
3 WordSearchPuzzleManiaIPhone 0x00028cc4 -[CCDirector replaceScene:] + 308
4 WordSearchPuzzleManiaIPhone 0x000d6a9f -[LoadingScene powerSetForArray] + 4031
5 WordSearchPuzzleManiaIPhone 0x000d58da -[LoadingScene init] + 842
6 WordSearchPuzzleManiaIPhone 0x000406d1 +[CCNode node] + 81
7 WordSearchPuzzleManiaIPhone 0x000d554d +[LoadingScene scene] + 93
8 WordSearchPuzzleManiaIPhone 0x000c1faf -[AppDelegate applicationDidFinishLaunching:] + 1583
9 UIKit 0x00749ce2 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1252
10 UIKit 0x0074bd88 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 439
11 UIKit 0x00756617 -[UIApplication handleEvent:withNewEvent:] + 1533
12 UIKit 0x0074eabf -[UIApplication sendEvent:] + 71
13 UIKit 0x00753f2e _UIApplicationHandleEvent + 7576
14 GraphicsServices 0x02012992 PurpleEventCallback + 1550
15 CoreFoundation 0x014d8944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
16 CoreFoundation 0x01438cf7 __CFRunLoopDoSource1 + 215
17 CoreFoundation 0x01435f83 __CFRunLoopRun + 979
18 CoreFoundation 0x01435840 CFRunLoopRunSpecific + 208
19 CoreFoundation 0x01435761 CFRunLoopRunInMode + 97
20 UIKit 0x0074b7d2 -[UIApplication _run] + 623
21 UIKit 0x00757c93 UIApplicationMain + 1160
22 WordSearchPuzzleManiaIPhone 0x000c191f main + 127
23 WordSearchPuzzleManiaIPhone 0x000025a5 start + 53
24 ??? 0x00000001 0x0 + 1
)
terminate called after throwing an instance of 'NSException'
Here's the file if anyone needs it: http://www.mediafire.com/?z4ef1zutwb544gt
Hope someone can help me out with this.
Thank you so much!
~Kazuo
EDIT:
Solved it myself! Just used the onEnter() of the LoadingScene scene.:)
A: Your this call is [CCTransitionCrossFade transitionWithDuration:1 scene:[GameScene node]] returning some invalid values, that is not there in the range. So it is crashing.
Naveen
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Oracle order by undetermined I'm trying to add pagination to a simple select query, like
select rownum rownum_,t.* from (select id,name from table) t
where rownum <=4
However the above query behaves differently when where condition is there and where condition is not there. But on removing the name column, the behaviour is consistent. Can anyone tell why?
I understand rownum is determined when query is run, what I'm not able to understand is that a where condition with rownum <=n , changes the order
A: You have to understand that rownum is a pseudo column.
The rownum column in your query indicates the order ( first record, second, third... )
Then the records order returned by
select id,name from table
is not guaranteed. In your request, the rownum associated to the first record will be always 1 despict the fact that the first record might be different every time.
In conclusion, always use ORDER BY when you want a specific order.
A: The table might have an index on rownum that it's using when you restrict with rownum <= 4. The order will then likely be defined by the index. This is the way it works in MySQL at least. If you want a specific ordering, always use ORDER BY.
A: When you exclude the name column from your query, the id's values are fetched from an index, not from table, so you get another order.
The second issue I bet is because the Optimizer uses parallel for getting more rows. Parallel threads allways return a 'mess order' because they retrieve data in parallel not sequential.
Try with a hint /*+ NO_PARALLEL(table) */
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: What is a good website to check when a javascript object/method appeared across browsers? Where can I check when was a specific javascript object or method introduced to all major browsers?
E.g. I just though I had a horrible production bug for a week because the Safari I just downloaded fails on JSON.stringify(), but then discovered I had somehow download an ancient Safari version, and the latest Safari versions do support it. Where can I find when exactly did Safari add JSON.stringify()?
Bonus: This is how I got lured into download a Safari version from three years ago. WTF?
A: http://caniuse.com is also a great source of such information.
A: Well there's http://www.quirksmode.com
(Much more general but covering many more browsers is http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Browser_features)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Best practice for handling add/edit/delete forms i'm a little stuck of how i should approach forms in my zend-application. Right now i'm creating two separate forms for addAction() and editAction() for each object i need. My delete-formular is always the same, i simply change some attributes on those.
What i'm wondering about: What is a best-practice here?
Personally i think it could be better just have Forms like "Object1, Object2" instead of "Object1Add, "Object1Edit, Object2Add, Object2Edit"
The reson i ask is because i clearly need two different forms. Some elements are NOT to get changed at all, so i don't want the user to see them.
A Method could be to $form->removeElement('X') inside the controllers editAction()
Why am i thinking this?
Well simple errors - i may add one field here and forget it in the second form or display fields with tag 'disabled=0' in one form but don't have that query on the other one.
Hope i'm making myself clear enough :)
Thank you in advance!
A: I assume that you do extend the form class. I'd add functions called edit or add to your class that does the corresponding logic. This way you keep your form-logic in your form and not in your controller.
A: I would exactly do what you said : 1 form with all elements. Then depending on the case, just use removeElement method on the form to remove the elements that you don't need.
A: This is a perfect time to use the Factory Design Pattern. Don't create the form using the contructor, use factory methods instead. Here is a quick pseudocode layout:
static createAdd()
form = new self()
call form->initCommon
call form->initAdd
return form
static createEdit()
form = new self()
call form->initCommon
call form->initEdit
return form
initComon()
add the common+validators elements
initAdd()
add the elements+validators only used in Add
initEdit()
add the elements+validators only used in Edit
Makes sense?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Quartz.NET trigger: run once in a specified interval I'm using the Quartz.NET library in a Windows service to run a daily job among others. I'm using AdoJobStore. Basically I want my job to be executed once any time between midnight and 1AM for example. So if the service was stopped at midnight and someone starts it at 00:30 I want the job to be executed then (only once) but if the service is started at 2AM I don't want the job to be executed that day.
How can a trigger be configured to run only once in a specified interval?
A: It looks like you need a custom 'misfire' behavior. From Quartz docs:
Misfire Instructions
Another important property of a Trigger is its "misfire instruction".
A misfire occurs if a persistent trigger "misses" its firing time
because of the scheduler being shutdown, or because there are no
available threads in Quartz's thread pool for executing the job. The
different trigger types have different misfire instructions available
to them. By default they use a 'smart policy' instruction - which has
dynamic behavior based on trigger type and configuration. When the
scheduler starts, it searches for any persistent triggers that have
misfired, and it then updates each of them based on their individually
configured misfire instructions. When you start using Quartz in your
own projects, you should make yourself familiar with the misfire
instructions that are defined on the given trigger types, and
explained in their JavaDoc. More specific information about misfire
instructions will be given within the tutorial lessons specific to
each trigger type.
Unfortunately the behavior that you need is not supported out of the box. You would need to schedule your job to execute exactly at midnight and then implement custom misfire. It should be possible to use ITriggerListener.TriggerMisfired.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it possible to add different views inside a scrollview in android? I am not able add different views inside a scrollview. How can I add a textView and a editText inside a scrollView
A: Yes you can add. But use a Layout and put your components there.
Example <ScrollView><LinearLayout> *Views* </LinearLayout></ScrollView>
A: Sample Code
<ScrollView
android:id="@+id/scroll"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="@+id/innerly1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/heading1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/background_light"
android:gravity="center"
android:scrollbars="vertical"
android:textColor="#FF0000" />
<ImageView
android:id="@+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/desc1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/background_light"
android:gravity="center"
android:scrollbars="vertical"
android:textColor="#FF0000" />
</LinearLayout>
</ScrollView>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Pinch to zoom with Osmdroid I've written a mapping application which has two activities, one activity displays a Google Maps view, the other displays the equivalent view using osmdroid 3.0.5 jar.
Until now I've been testing on emulators only and the functionality is completely identical in terms of area shown and overlay data. Now I have run the app on a real Gingerbread device, I notice that the Google Maps activity seems to support pinch to zoom, whilst the Osmdroid one doesn't.
I haven't written any code specific to pinch to zoom for the Google side or for Osmdroid. Both activities implement OnTouchListener. Both activities just have a stub for OnTouch like:
@Override
public boolean onTouch(View v, MotionEvent e) {
// chain it for now
return false;
}
My mapview in the Osmdroid activity is of the class: org.osmdroid.views.MapView
Does anybody know how to make pinch to zoom work with osmdroid or know of a sample application using osmdroid that I could study and adapt into my app?
A: Osmdroid has the functionality to zoom. You will need to setup a gesturelistener to check for the pinch action, at which point you should call the zoom function in osmdroid. I believe in osmdroid 3.0.5 it is something like
mOsm.getController.setZoomLevel(someNumber) (mOsm is an instance of the map view).
I have the zoom function working for the opposite pinch (you fingers start close together and then expand). I suggest using a MotionEvent (like you are currently doing) and doing something like this:
boolean finished = false;
@Override
public boolean onTouch(View v, MotionEvent e) {
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
finished = false;
break;
case MotionEvent.ACTION_MOVE:
finished = false;
break;
case MotionEvent.ACTION_UP:
//action is finishing at this point, so now I can do my refreshActionOnMap();
if (!finished)
refreshActionOnMap();
break;
}
return true;
}
The code I have added deals with the pinch - the finished boolean is something I implemented in my program to figure out when to refresh the map. That should help you out more.
Here is a further explanation of this.
If you are looking for something different, then try reading here. Android has been supporting the pinch action since June 2010 apparently.
A: MapView.setBuiltInZoomControls(true);
MapView.setMultiTouchControls(true);
A: Is it possible not to zoom to the map center but to the middle of users two finger.
A: As shameus.burp said, the codeline-
mapView.setMultiTouchControls(true);
Is working for me in order to pinch for zoom (check at 2021).
Notice that the function that shows zoom-controller (basically it is buttons of (-) and (+)) -
MapView.setBuiltInZoomControls(true);
is deprecated by osmdroid.
So instead, you can use the code line -
mapView.getZoomController().setVisibility(CustomZoomButtonsController.Visibility.ALWAYS);
By default (without adding the last code line) osmdroid is set the zoom-controller to show and fade. Equivalent to
CustomZoomButtonsController.Visibility.SHOW_AND_FADEOUT
option.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Specific image dimensions generated by PHP As we know, if we specify width and height attributes in <img /> element, browser can immidiately locate image in rendered layout. It's not a really big boost of speed, but it's really nice optimisation practice.
Ok, but sometimes image has different dimensions. So we can get it by PHP getimagesize() function.
And here is the question, if we don't have specific dimensions is it worthwhile to use PHP? Of course, we have to write additional code, but if we cope with gallery we anyhow use PHP, so in that case it's only 2 lines of code.
What is your opinion?
A: It depends on what you're trying to do. The benefits of having the dimensions on the <img/> tag are:
*
*Browser knows the space to reserve for the image as it's downloaded. This means your layout won't jump around as the images load.
*It saves the browser from performing a reflow and repaint once the images load (speed optimization).
*You'll have the dimensions available to any Javascript processing as soon as the HTML is finished loading.
On the other hand, adding the dimensions will increase your page size and cause you to use more bandwidth.
A: You have to realize that getimagesize causes an I/O read (unless you're doing blob reads from db, then it's okay). So, then you have doubled your I/O reads just for loading images. Computers are generally fast enough that computing width and height of images for browsers, is not really much of an issue.
Then again, you have other venues of optimization:
*
*sprites
*putting assets in CDNs instead of app
*validate your code
I think generally, it's impractical to implement this, because it creates more inefficiencies that it optimizes.
A: Well I never bother. And frankly most of the websites don't bother as well. The thing is that browser doesn't need to download the whole image to get it's dimensions. Most of the image formats have the image size in a header of the file. so once browser got first few bytes of the file it already knows what the dimensions are.
A: Function getimagesize() tries to parse image size from the file every time your PHP is called. So basically instead of one disk seek you have two (plus parsing - if you parse some huge video file instead of image it could be literally seconds).
I personally have a CMS that reads image size only on image upload and then saves it in DB with other data, so no extra disk access is needed. Of course this might be overkill for you - YMMV.
Best advice: test it. It is a simple test and it will give you the most relevant answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to read/scan Barcode? how can I be able to implement read/scan bar code in my iphone application. I also would like to know how to implement it into the iphone application. If possible suggest me the links and example source code and applications to understand how it works.
A: I'm using the Zbar framework that is available here
http://zbar.sourceforge.net/
Check out the documentation it is well explained on how to implement it
edited: tutorial for implement Zbar: http://zbar.sourceforge.net/iphone/sdkdoc/tutorial.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: .htaccess subdomain to directory issue I am currently working on a website for a client, the website I'm creating is then to be sold on to other companies to use and is done so like this:
*
*Payment is recieved
*Admin logs into 123-reg control panel and creates a new database.
*Admin then logs into a website control panel and begins to create a new instance of the website.
*The source filesare copied over to a new directory /new-instance/ for example.
*The user should be able to access it from new-instance.website.co.uk
Now due to some issues such as the fact after 100 sub domains they have to pay more money to 123-reg I suggested we simply set up a set of .htaccess rules to redirect the user from new-instance.website.co.uk to website.co.uk/new-instance/
Now the issues I face are that
*
*I have no idea on the rewrite rule I should be using, I'm currently using this one found here
*123-reg seems to have catch-all sub-domains enabled, I have no access to the 123-reg panel so I don't know if they are able to turn it off, but due to this fact typing in any sub-domain that has not been set up in their control panel just shows the websites main page, therefore I have no idea if catch-all is stopping .htaccess working or if its the rules within the .htaccess file.
All relevant answers are much appreciated. Thanks.
A: The below support article explains how to setup sub domains via DNS.
The stand alone subdomain product is not what you require.
How can I point a subdomain to an IP address?
http://www.123-reg.co.uk/support/answers/Domains/Domain-Configuration/how-can-i-point-a-subdomain-to-an-ip-address-2173/
All you need to do is setup the as described in the article above and then code the htaccess file accordingly.
Any problems please let me know the support ticket number.
http://www.123-reg.co.uk/support/
Ricky
A: I work on behalf of 123-reg.
You do NOT need to pay for sub domain DNS hosting.
You can add DNS entries via the Manage DNS section of the control panel
Regards,
Ricky
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7583289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.