text
stringlengths 8
267k
| meta
dict |
---|---|
Q: commenting in asp.net Ok..so here's the problem..i want to have facebook commenting on my productsDescription page..there are many products so when we click on a particular product it redirects to the productDescription page with the itemID in query string..now what i want is all the products have there own specific comment box.Now when i use the below code , with different itemID in query string the same comment box opens.
For Eg: If a user comments on a mobile(www.tc.com/gyjd.aspx?itemID=55) , and then navigates to view a laptop(www.tc.com/gyjd.aspx?itemID=77) he sees the comments he gave for the mobile. But what i want is with different itemID in query string the comment box should be new.Hope am not confusing.
<div id="fb-root"></div>
<script> (function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
} (document, 'script', 'facebook-jssdk'));</script>
<div class="fb-comments" data-href="tc.com/gyjd.aspx" data-num-posts="5" data-width="500"></div>
A: I've solved that by doing a div called fbBtns.
Then I set it's innerHtml property on page behind:
fbBtns.InnerHtml = "";
A: Simply add the proper querystring to the data-href attribute:
<div class="fb-comments" data-href="tc.com/gyjd.aspx?itemID=<%=Request.QueryString["itemID"]%>" data-num-posts="5" data-width="500"></div>
For VB.NET:
<div class="fb-comments" data-href="tc.com/gyjd.aspx?itemID=<%=Request.QueryString("itemID")%>" data-num-posts="5" data-width="500"></div>
A: You need to have unique urls for the page (Facebook ignores the query string). You could tell Facebook to use fake urls by setting the data-href to be something like "tc.com/qyjd/4" etc. With .net 4, you can easily set up page routes.
to do this as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Caching dynamic Acts_as_tree category list I have a Category model which uses acts_as_tree
class Category < ActiveRecord::Base
acts_as_tree :order=>"name"
end
When I display my category tree I use recursion, and an almost identical partial is generated each time (apart from some checkboxes being checked or not), requiring a large number of database calls.
I would like to cache this, but at the minute the only thing I can think of is by dumping Category.all in to a new non-ActiveRecord data structure to reduce the number of calls. Is there a better way?
index.html.erb
<%= render :partial=> "/categories/category_checkboxes", :locals=>{:select_categories=>@categories_ids} %>
_category_checkboxes.html.erb
<% @categories.each do |category| %>
<h3><a href="#"><%=category.name%></a></h3>
<div>
<% category_children = category.children %>
<%= render :partial => "/categories/category_checkbox_children",
:locals => { :child_categories => category_children,
:chk_class=>chk_class,
:select_categories=>select_categories } unless category_children.empty? %>
</div>
<% end %>
_category_checkboxes_children.html.erb
<ul>
<% child_categories.each do |category| %>
<li class= "category_check_box">
<%=check_box_tag("category#{category.id}", 1, select_categories.index(category.id)%>
<%=label_tag("category#{category.id}" ,"#{category.name}")%>
<%= render :partial => "/categories/category_checkbox_children", :locals => {
:child_categories => category.children,
:select_categories=>select_categories} unless category_children.empty? %>
<% end %>
</li>
</ul>
A: The acts_as_tree gem is rather out of date. The last version (0.1.1) is from February 2010, and its functionality pretty limited.
I recommend you take a look at ancestry, a gem that provides similar functionality, and has added much more. Specifically, take a look at the section on Selecting nodes by depth.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jquery auto-change a drop down span I am using wxtiles for Google Maps. These are weather overlay tiles for Google Maps. This source includes a DateTimestamp in an HTML select that, when changed, will update the overlay tiles for weather forecasting.
I am wanting to create a function that on page load, will automagically place these DateTimestamp values in an array and every 3 seconds, auto change this value which will then change the overlay tile.
In short these weather overlays then 'behave' like animated KML files on google maps.
Here is an example from wxtiles:
http://www.wxtiles.com/
Here is the timestamp which comes from wxtiles:
var wxoverlay=new WXTiles();
wxoverlay.addToMap(map);
document.getElementById('tSelect').appendChild(wxoverlay.getTSelect());
And the HTML to display these timestamps.
<span id="tSelect"></span>
Is this idea possible due to the fact that these values always change, and come from a thirdparty?
Thanks,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Memory leak when using json-data on a map I've the following problem:
I'm accessing foursquares Venue API and get a JSON string back. I parse this string with this json-framework. After that I'm saving the dictionaries and arrays for accessing further information about the venues (in special I'm using the explore API). So the venue information is saved deeply (for my experience) in the json-structure tree. And after getting the needed information (venue name & coordinates) I put a corresponding pin on a map with the same coordinates and with the venue's name as the pin's name.
And exactly at the point where I want to set the pin's name, I get a memory leak. So something get's wrong here. If I don't set any title, all works fine. So the memory leak occurs only when I'm setting the name of the venue to the pin.
Here is the corresponding code fragment:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//Parse JSON string
// Store incoming data into a string
NSString *jsonString = [[NSString alloc] initWithData:self.fetchedJSONData encoding:NSUTF8StringEncoding];
[self.fetchedJSONData setLength:0];
// Create a dictionary from the JSON string
NSDictionary *results = [NSDictionary dictionaryWithDictionary:[jsonString JSONValue]];
[jsonString release];
NSDictionary *response = [NSDictionary dictionaryWithDictionary:[results objectForKey:@"response"]];
NSArray *groups = [NSArray arrayWithArray:[response objectForKey:@"groups"]];
NSDictionary *groupsDic = [groups lastObject];
NSArray *items = [NSArray arrayWithArray:[groupsDic objectForKey:@"items"]];
for (int i=0; i<[items count]; i++)
{
CLLocationCoordinate2D annotationCoord;
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
NSDictionary* oneItemDoc = [NSDictionary dictionaryWithDictionary:[items objectAtIndex:i]];
NSDictionary *singleVenue = [NSDictionary dictionaryWithDictionary:[oneItemDoc objectForKey:@"venue"]];
/*
* Leak here in the next two lines!
*
*/
NSString *titleName = [[[singleVenue objectForKey:@"name"] copy] autorelease];
annotationPoint.title = titleName;
NSDictionary *locationOfVenue = [NSDictionary dictionaryWithDictionary:[singleVenue objectForKey:@"location"]];
annotationCoord.latitude = [[locationOfVenue objectForKey:@"lat"] doubleValue];
annotationCoord.longitude = [[locationOfVenue objectForKey:@"lng"] doubleValue];
annotationPoint.coordinate = annotationCoord;
[self.mapView addAnnotation:annotationPoint];
[self.annotationsArray addObject:annotationPoint];
[annotationPoint release];
}
}
So the leak occurs when I want to set the title for the annotationPoint.
For each venue fetched with JSON I get the following leak trace (blurred libraries are my own libraries):
Has anybody a suggestion how to solve this problem? I tried many, many things. So the key issue seems to be how to "hand over" the [singleVenue objectForKey:@"name"] correctly. I first tried to set it without a copy and an autorelease, but then I get a zombie object. So I don't know how to do this. I think the problem are not these two lines, but some lines above them. Am I right? I also have the suggestion, that my 3rd party json parser is forcing this problem (cf. leak trace).
So I hope someone can help me to fix this problem. Would be really great!
Update: The problem seems to be independent of the corresponding JSON parser. I've testet my code with another parser, same problem there. So it has to do something with my code itself.
I think I know what's the problem. So the leak occurs after closing the map. So after dealloc. So it might be, that I've missed something there. I have a mapview and I also release it in dealloc and set it to nil in viewDidUnload. I also release all the other Arrays etc. in dealloc. Is there something else (specific about the map and view) which I need to release? I think this might be the problem!
Update: Solved the problem: I had to set all Foursquare pins' title and subtitle to nil in the dealloc method, because a value (accessed via a JSON parser) was retained by the map view somehow. Now all works fine!
A: Solved the problem: I had to set all Foursquare pins' title and subtitle to nil in the dealloc method, because a value (accessed via a JSON parser) was retained by the map view somehow. Now all works fine!
A: Had a similar situation, annotation's (MKPointAnnotation) title not being released properly. Solved it by simply setting mapView to nil just before releasing it.
I think this is quite safer than calling an extra [title release], which also does work, but if mapView is fixed internally it would cause a problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Determine what ids were removed from array in Rails after_save callback? I am trying to figure out how i can tell what has changed in an array in the after save callback. Here is an example of code i am using:
class User < ActiveRecord::Base
has_many :user_maps, :dependent => :destroy
has_many :subusers, :through => :user_maps, :dependent => :destroy
has_many :inverse_user_maps, :class_name => "UserMap", :foreign_key => "subuser_id"
has_one :parent, :through => :inverse_user_maps, :source => :user
after_save :remove_subusers
def remove_subusers
if self.subuser_ids_were != self.subuser_ids
leftover = self.subuser_ids_were - self.subuser_ids
leftover.each do |subuser|
subuser.destroy
end
end
end
end
class UserMap < ActiveRecord::Base
belongs_to :user
belongs_to :subuser, :class_name => "User"
end
I am removing the subusers with the after_save callback because i could not get the dependent destroy feature to work through user_maps. Does anyone have any ideas on a way to do this?
Thanks!
A: although not strictly the answer to your question, I think you maybe able to get :dependent => :destroy working if you try the following...
class User < ActiveRecord::Base
has_many :user_maps, :dependent => :destroy
has_many :subusers, :through => :user_maps # removing the :dependent => :destroy option
end
class UserMap < ActiveRecord::Base
belongs_to :user
belongs_to :subuser, :class_name => "User", :dependent => :destroy # add it here
end
By moving the :dependent => :destroy option to the belongs_to association in the UserMap model you set up a cascading delete via the UserMap#destroy method. In other words, calling User#destroy will call UserMap#destroy for each UserMap record, which will in turn call sub_user.destroy for its sub_user record.
EDIT
Since the solution above didn't work, my next suggestion would be to add a callback to the user_maps association, however this comes with a warning that I will add after
class User < ActiveRecord::Base
has_many :user_maps, :dependent => :destroy, :before_remove => :remove_associated_subuser
def remove_associated_subuser(user_map)
user_map.subuser.destroy
end
end
WARNINGS
1) Using a before_remove callback will mean that the user_map.destroy function won't be called if there is an error with the callback
2) You will have to destroy your UserMap record using the method on the User class for example...
# this will fire the callback
u = User.first
u.user_maps.destroy(u.user_maps.first)
# this WONT fire the callback
UserMap.first.destroy
All things considered, this would make me nervous. I would first try modifying your code to make the associations a little less coupled to the same tables, so the :dependent => :destroy option can work, and if you can't do that, add a cascade delete constraint on to the database, at least then your associations will always be removed regardless of where / how you destroy it in your rails app.
A: You can use the Dirty module accessors http://ar.rubyonrails.org/classes/ActiveRecord/Dirty.html as suggested in Determine what attributes were changed in Rails after_save callback?
In your case the handler you have for after_save will have access to subusers_change which is an array of two elements, first being the previous value and second being the new value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Ensure that an image is displayed on browser How to be sure that an image is displayed on browser before further action?
I want to load some images in certain sequence because i want to be sure that an image will be always as background. I write the following code:
// load the view
final IView bgView = new StaticImgView(Constants.BG_CLASS, "Background", bgPath);
this.dPanel.add(bgView);
bgView.addErrorHandler(new ErrorHandler() {
@Override
public void onError(ErrorEvent event) {
GWT.log("No Background-View.");
loadLogoView();
}
});
bgView.addLoadHandler(new LoadHandler() {
@Override
public void onLoad(LoadEvent event) {
GWT.log("Background-View loaded.");
GWT.log("> " + TicketViewer.this.dPanel.getWidgetCount());
loadLogoView();
}
});
But the 'Logo' image is not displayed upon the background..(?).
*
*bgView extends Image.
*loadLogoView contains similar code to load another image.
*Note that the background image is 800x600, while all the other images are smaller 104x100.
A: It depends on what constitutes further action. A general purpose scenario is if you are using JQuery, you can do this:
$('#imageId').load(function() { //Do Something })
Where imageId corresponds to the id in your img tag.
<img src="test.jpg" id="imageId" />
A: Add a LoadHandler to the image (Image.addLoadHandler(LoadHandler)).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Selecting the newest record of a hasMany relationship I have 2 basic models in my CakePHP application: User and Login. A user has a hasMany relation with Logins (i.e., a new login record is created everytime the user logs in).
Now, I want to make 2 relations from the User model to the Login model:
User hasMany Login
and
User hasOne lastLogin
This last relation should only include the last record of the Login model for the selected user.
I tried this as follows:
var $belongsTo = array
(
'LastLogin' => array
(
'className' => 'Login',
'order' => 'LastLogin.created DESC',
'limit' => 1
)
);
However, this doesn't work. Any ideas on how to get this working?
A: UPDATED ANSWER IN RESPONSE TO COMMENTS
With a belongsTo relationship, the foreign key should be in the current model.
This means that if you want to have a relationship where User belongsTo LastLogin, the users table should have a last_login_id field.
In your case you probably want to use a hasOne relationship instead, and you're going to have to use the MAX() SQL function in the fields key. Note that getting the last_login works completely independently of your User hasMany Login relationship. So if all you want is the last login you can remove the hasMany relationship and just leave the hasOne.
With the example code below you'll get this:
Output of /users/index:
Array
(
[User] => Array
(
[id] => 1
[name] => user1
[last_login] => 2011-05-01 14:00:00
)
[Login] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[created] => 2011-05-01 12:00:00
)
[1] => Array
(
[id] => 2
[user_id] => 1
[created] => 2011-05-01 13:00:00
)
[2] => Array
(
[id] => 3
[user_id] => 1
[created] => 2011-05-01 14:00:00
)
)
)
If you don't use the Model::afterFind() callback your results will look more like this (Login array snipped to save space):
Array
(
[User] => Array
(
[id] => 1
[name] => user1
)
[0] => Array
(
[last_login] => 2011-05-01 14:00:00
)
)
Example code:
users table:
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
logins table:
CREATE TABLE `logins` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
)
User model:
class User extends AppModel {
var $name = 'User';
var $hasMany = array('Login');
var $hasOne = array(
'LastLogin' => array(
'className' => 'Login',
'fields' => array('MAX(LastLogin.created) as last_login')
)
);
// This takes the last_login field from the [0] keyed array and puts it into
// [User]. You could also put this into your AppModel and it would work for
// all find operations where you use an SQL function in the 'fields' key.
function afterFind($results, $primary=false) {
if (!empty($results)) {
foreach ($results as $i => $result) {
if (!empty($result[0])) { // If the [0] key exists in a result...
foreach ($result[0] as $key => $value) { // ...cycle through all its fields...
$results[$i][$this->alias][$key] = $value; // ...move them to the main result...
}
unset($results[$i][0]); // ...and finally remove the [0] array
}
}
}
return parent::afterFind($results, $primary=false); // Don't forget to call the parent::afterFind()
}
}
Users controller:
class UsersController extends AppController {
var $name = 'Users';
function index() {
$this->autoRender = false;
pr($this->User->find('all'));
}
}
A: I had a similar situation but mine was
Product hasMany Price
I wanted a Product hasOne CurrentPrice with the CurrentPrice defined as the top most record found if sorted by created in desc order.
I solved mine this way. But I am going to use your User and LastLogin instead.
class User extends AppModel {
var $name = 'User';
var $hasMany = array('Login');
var $hasOne = array(
'LastLogin' => array(
'className' => 'Login',
'order' => 'LastLogin.created DESC'
)
);
If you think about it, created and id has the same meaning. so you could also use id in descending order.
I am assuming that your table schema is similar to the one suggested by mtnorthrop.
i.e.
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
logins table:
CREATE TABLE `logins` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: git-svn clone a single module I have a repository like:
trunk/a/b/c
branches/V1/a/b/c
branches/V2/a/b/c
tags/T1/a/b/c
tags/T2/a/b/c
I'd like to work on module 'c', not checking out any other module. What is the git-svn command to do that?
A: *
*Do git svn init with whatever options e.g.,
$ git svn init http://svn.example.com/ -T trunk/a/b/c -t tags/T1/a/b/c \
-b branches/V1/a/b/c
*Edit your .git/config as shown below
*Make get svn fetch
git-svn manual page says that you may use in your .git/config to fetch all branches and tags:
[svn-remote "project-c"]
url = http://server.org/svn
fetch = trunk/a/b/c:refs/remotes/trunk
branches = branches/*/a/b/c:refs/remotes/branches/*
tags = tags/*/a/b/c:refs/remotes/tags/*
Or to select only a few branches:
[svn-remote "project-c"]
url = http://server.org/svn
fetch = trunk/a/b/c:refs/remotes/trunk
branches = branches/{V1,V2}/a/b/c:refs/remotes/branches/*
tags = tags/{T1,T2}/a/b/c:refs/remotes/tags/*
A: I'm not sure that this is possible... You can check only the module in the trunk using the complete url to the folder:
git svn clone url/trunk/a/b/c
You can try using the --branches --tags parameters but i don't think that this will work
git svn clone --trunk=/trunk/a/b/c --branches=/branches --tags=/tags url
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: xfbml support for diazo I'm trying to use collective.simplesocial on my diazo-themed site (Plone 4.1),
and notice the like button was broken.
The <fb:like> tag was transformed to <like> (the prefix is stripped). All other xfbml tags suffered the same problem.
I've tried to add xmlns:fb="http://www.facebook.com/2008/fbml" to html tag but it didn't work either.
Any idea to overcome this ?
A: This should work for the plusone button (see comment for answer to your original question):
<xsl:template match="plusone">
<xsl:element name="g:{local-name()}" xmlns:g="http://base.google.com/ns/1.0">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Core Data - Add object to a relationship without firing a fault When I try to add a new ManagedObject to an existing relationship of an entity using the Core Data generated method "addArticleObject", a fault is fired for the articles relationship. Is it possible to add an object to a relationship without causing a fault to fire for the existing objects in the relationship?
A: I'm not sure I'm understanding your question exactly, but if you modify your core data model, as long as you go on the simulator and delete your app, then rerun it (so it regenerates everything), then you should be fine. You also might have to delete and recreate your NSManagedObject classes, but that's a quick thing also.
A: If you've altered the structure of your Core Data model, unless you've done so with a migration you'll need to clear the previous version from the Simulator and any handsets you're testing on. The error which occurs if you don't isn't particularly helpful.
Use the 'Reset contents & settings' option in the Simulator, and delete and reinstall the app on a phone. Simply rerunning the app isn't enough.
A: It seems that it is not possible to add objects to a many-to-many inverse relationship in Core Data without having both objects in the relationship in memory. I'm sure there must be a good reason for that requirement, which I would like to know. This has however caused me to have to refactor the database and all associated code
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: guide me to find the best android programming pdf What the best android programming education pdf to learn fast and easily android programming?please guide me,thank you.
A: "Best" is very subjective, so it is hard to accurately answer your question.
However, the official Android documentation is probably a good place to start; check out the Hello, World app (it's a website, rather than a pdf though...).
A: I suggest you to see this videos :
http://www.youtube.com/user/edu4java#grid/user/301ACBB31D739F72
They has it in spanish also , and have another list for android game program.
P.D: No pdf , but faster to learn about.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding multiple spritesheets in cocos2d I have the following code to set up my spritesheets and batch node:
CGSize screenSize = [[CCDirector sharedDirector] winSize];
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"soldier-test.plist"];
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"soldier-running.plist"];
batchNode = [CCSpriteBatchNode batchNodeWithFile:@"soldier-test.png"];
self.player = [Player spriteWithSpriteFrameName:@"shooting s0000.bmp"];
[batchNode addChild:self.player];
[player setPosition:ccp(screenSize.width/2, screenSize.height/2)];
[self addChild:batchNode];
However, when I try to have player (a subclass of CCSprite) perform an action using frames from the second spritesheet, I get assertion errors related to the texture files. Do I need to combine the sheets into one, or is there a way to span one CCSprite over multiple spritesheets?
A: A SpriteBatchNode can only have children that all use the same texture. Your player needs to use the texture soldier-test.png if you want to add it to your batchNode.
With a TextureAtlas you can put multiple different textures into one big image.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hashing raw audio data I'm looking for a solution to this task: I want to open any audio file (MP3,FLAC,WAV), then proceed it to the extracted form and hash this data. The thing is: I don't know how to get this extracted audio data. DirectX could do the job, right? And also, I suppose if I have fo example two MP3 files, both 320kbps and only ID3 tags differ and there's a garbage inside on of the files mixed with audio data (MP3 format allows garbage to be inside) and I extract both files, I should get the exactly same audio data, right? I'd only differ if one file is 128 and the other 320, for example. Okay so, the question is, is there a way to use DirectX to get this extracted audio data? I imagine it'd be some function returning byte array or something. Also, it would be handy to just extract whole file without playback. I want to process hundreds of files so 3-10min/s each (if files have to be played at natural speed for decoding) is way worse that one second for each file (only extracting)
I hope my question is understandable.
Thanks a lot for answers,
Aaron
A: Use http://sox.sourceforge.net/ (multiplatform). It's faster than realtime as you'd like, and it's designed for batch mode much more than DirectX. For example, sox -r 48k -b 16 -L -c 1 in.mp3 out.raw. Loop that over your hundreds of files using whatever scripting language you like (bash, python, .bat, ...).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: is there way to view a Swing app remotely? I want to show my app conveniently without the hassle of carrying a laptop or distributing an obfuscated Java app.
Is there an easy way to view my Swing app in a browser. I do not necessarily need the command buttons to work (but it would be nice if they did), I just want to see the pixels from anywhere on the internet. I have graphs built from JChart2D.
Edit: The screen updates after a configurable period and 15 seconds is typical but if the desktop updates every 15 seconds and the browser image at a much slower rate, say, 1 minute, that would be okay.
Edit: What I have is primarily a desktop app in that it being a desktop app satisfies 98% of the requirements but if I can see it or use it remotely without a re-write that would give me the extra 2% (see it 1%, use it 1%).
A: For that purpose, the recent Webswing may be perfect. It seems fully functional. There are some glitches and I miss the cursors. Alas, the remote applications are displayed on the server, too, whether you want it or not.
A: There is not many solutions for it but this easisest way is JNLP.
JNLP is an XML-based technology for launching Java executables over the Web. Just imagine that you could specify the classpath resources in your application (images, JAR files, properties, files, etc.), scattered over the Web and giving their URLs, instead of relying on the local file system as normal Java applications do. This feature would give you the capability of deploying your application automatically (that is, installing needed application files and launching them properly) just by declaring where your files are on the Web. And it is far easier than Applets which can create a lot of troubles to you because of strict permissions at browser.
An example of JNLP is here and here.
A: I don't think I would recommend this (because it has security implications and firewall issues) but it is possible to run a Java / Swing application using a remote X11 server.
Here are some relevant links:
*
*Remote X Apps mini-HOWTO
*X Over SSH2 - A Tutorial
but there is probably more uptodate information in your Linux documentation.
Another idea is to make a demonstration movie.
A: One other possibility (not necessarily a good one, but easy to implement) might be to use the java.awt.Robot class.
Using this class, you could periodically take a snapshot of the screen, using #createScreenCapture(...), and write this out to disk using javax.imageio.ImageIO.
It would then be straightforward to create an HTML page that displayed this image, and auto-refreshed periodically. A little bit complicated and circuitous, but may let you re-use existing infrastructure.
A: VNCj (official page, SourceForge) is an older project which provides an implementation of AWT on a VNC server. Swing runs on top of that. Unlike WebSwing, no UI appears on the server when running VNCj.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How can I debug JS code added into DOM by an AJAX call? I have a webpage which loads properly formatted html forms using AJAX calls. This HTML also loads javascript code along with it and it is not working. As I am using jQuery I tried to add live() but it didn't help me. Now I need to debug this. How can I set breakpoints or watch on this code using firebug? I am using jQuery1.3 and can not deviate from it.
TIA
A: I'm uncertain from reading your question as to whether or not you have access to and can modify the dynamically loaded script, but if you do, add this statement:
debugger;
where you want your breakpoint.
Also note that although Firebug is perfectly capable of displaying dynamically loaded scripts, I think it hides them by default.
Also, if you have the option of using Chrome or Safari, you can just throw an exception from the point where you want to break, then set the Chrome or Safari debugger option to break on any exception. For example:
try {
throw new Error("");
}
catch () {}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Calculating x position using .css('left') I have a issue finding the center of the screen. I have jQuery code:
arr[i].css('left')=='560px';
which will animate the html obj(arr[i]) when it's in the center of the screen.
I have posted my sample, if you can have a look at this link: http://kashi.9f.com/Carousel/index.html
On hitting the left and right key the objects starts moving onto the respective sides. My objective is to highlight the 'letter' which is at center of the screen. Some times when I hit left/right key, the html obj at '560px' don't always animate. It will be either the next or the previous item other than item at '560px' which gets animated.
Please can anybody help me how I can make this work so that only the center obj animates.
If you need, you can take a look at the js (script.js) and css (style.css) file which is in the same directory as that of html.
A: The problem is that you're checking the element's coordinates left position before jQuery has finished moving it. Add your function as a callback to animate.
http://api.jquery.com/animate/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Missing builder(org.maven.ide.eclipse.maven2Builder) I'm using Eclipse Indigo and have the following in my .project file:
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>new project</name>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
</buildCommand>
<buildCommand>
<name>org.maven.ide.eclipse.maven2Builder</name>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.maven.ide.eclipse.maven2Nature</nature>
</natures>
</projectDescription>
I have the m2e - Maven Integration for Eclipse installed. But I am getting Missing builder(org.maven.ide.eclipse.maven2Builder) under the Builders properties and I am getting a java.lang.ClassNotFoundException: when I try to running a class file from my project.
I guess I am missing something in the config somewhere or a plugin?
Thanks
A: It is most likely a mismatch between the declared builder class and your m2e plugin.
Try this:
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>new project</name>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>
Please note the different org.eclipse.m2e.core namespace.
A: While changing to the newer m2e plugin might work, it may not. You can install the older m2e plugin version which uses the old tag in Indigo. See http://m2eclipse.sonatype.org/installing-m2eclipse.html. Unfortunately, you can't have both the old and new installed at once, so if you managed to install the new one, you will have to uninstall it before installing the older version.
A: @LucaGeretti's answer was exactly my problem, fixing it in Eclipse Indigo can be done easily from the IDE:
*
*Right click on your project.
*Select 'Configure'.
*Click 'Convert to Maven Project'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Sending Parameters to the Function called by a thread in C#? Sending Parameters to the Function called by a thread in C#,
this is my code:
myThread = new Thread(new ThreadStart(myfunc));
myThread.Start(i);
public void myfunc(int i)
{
...
}
I get error:
No overload for 'installDrivers' matches delegate
'system.Threading.ThredStart'
A: You can use a ParameterizedThreadStart.
Thread myThread = new Thread(new ParameterizedThreadStart(myfunc));
myThread.Start(i);
And your function
public void myfunc(object i)
{
int myInt = Convert.ToInt32(i);
}
A: Another option, utilizing lambdas makes it easy to call functions with any number of parameters, it also avoids the rather nasty conversion from object in the one parameter case:
int paramA = 1;
string paramB = "foo";
var myThread = new Thread(() => SomeFunc(paramA, paramB));
myThread.Start();
public void SomeFunc(int paramA, string paramB)
{
// Do something...
}
A: use this:
myThread = new Thread(new ParameterizedThreadStart(myfunc));
myThread.Start(i);
public void myfunc(object i) {... }
it might be usefull for your issue
A: Unless you are using C# < 2.0, you don't need to create a delegate. You can let the compiler implicitly create it for you.
myThread = new Thread(myfunc);
myThread.Start(i);
public void myfunc(object i)
{
int i2 = (int)i; // if i is an int
}
but note that the Thread constructor accepts only two types of delegates: one that is parameterless (ThreadStart) and one that accepts an object parameter (ParameterizedThreadStart). So here we are using the second one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Parent View Controller and Model View Controller dismissal detection not working I have a UIViewController called ShowListViewController that uses a Modal View Controller to push another view onto the stack:
AddShowViewController *addShowViewController = [[AddShowViewController alloc] init];
[addShowViewController setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
[self presentModalViewController:addShowViewController animated:YES];
I would then like to call my method populateTableData of the ShowListViewController class when the addShowViewController disappears.
I would think that the answer found here would work, but it doesn't. My method populateTableData is not detected as an optional method to use.
Essentially my questions is: How do I detect when a Modal View Controller disappears so as to call a method within the class that pushed it on the stack?
A: OK so it appears that in Apple's template for Utility App's they ignore what the docs for [UIViewController][1] say and actually go out of their way to call dismissModalViewControllerAnimated: from the UIViewController that pushed the modal view onto screen.
The basic idea in your case will be
*
*Define a protocol for AddShowViewControllerDelegate
*Make ShowListViewController implement this protocol
*Call a method on the delegate to ask it to dimiss the modal view controller
For a full example just create a new project with Utility template and look at the source for FlipsideViewController and MainViewController
Here is an example adapted for your needs:
AddShowViewController.h
@class AddShowViewController;
@protocol AddShowViewControllerDelegate
- (void)addShowViewControllerDidFinish:(AddShowViewController *)controller;
@end
@interface AddShowViewController : UIViewController
@property (nonatomic, assign) id <AddShowViewControllerDelegate> delegate;
- (IBAction)done:(id)sender;
@end
AddShowViewController.m
- (IBAction)done:(id)sender
{
[self.delegate addShowViewControllerDidFinish:self];
}
ShowListViewController.h
@interface ShowListViewController : UIViewController <AddShowViewControllerDelegate>
{
...
}
ShowListViewController.m
- (void)addShowViewControllerDidFinish:(AddShowViewController *)controller
{
[self dismissModalViewControllerAnimated:YES];
[self populateTableData];
}
A: This may not be a best solution, but can do what you want at this time.
In your showlistcontroller add an instance variable like
BOOL pushedView;
@implementation ShowListViewController
and before you do the modal presentation set its values as YES like
pushedView = YES;
[self.navigationController presentModalViewController:popView animated:YES];
in the viewWillAppear of ShowListViewController you can detect whether it is appearing because pop getting dismissed or not like
if (pushedView) {
NSLog(@"Do things you would like to on pop dismissal");
pushedView = NO;
}
A: I think you would like something like this.
You make a delegate inside ur modalVC like this:
@protocol ModalViewDelegate <NSObject>
- (void)didDismissModalView;
@end
and implement it in your MainVC like this:
@interface MainViewController : UIViewController <ModalViewDelegate>
{
Then u will make a delegate property in your modalVC like this:
@interface ModalShizzle : UIViewController
{
id<ModalViewDelegate> dismissDelegate;
}
You set the dismissDelegate of your ModalVC to your MainVC and then you make the delegate method. Before you dismiss it however you will call the ModalVC to do one last thing. (which is populate your table). You will call for the data inside your MainVC and then do whatever you feel like it, just before you dismissed your modalVC.
-(void)didDismissModalView
{
//call ModalVC data here...
//then do something with that data. set it to a property inside this MainVC or call a method with it.
//method/data from modalVC is called here and now u can safely dismiss modalVC
[self dismissModalViewControllerAnimated:YES];
}
Hope it helps ;)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Generating random number from 0 to 10 including both I heard of some Math.random() but I'm not sure about using it correctly. Number must be whole, so I suppose I'll need some rounding function.
A: Math.random produces a pseudo random number between [0;1[ (0 included, but 1 excluded)
To have an evenly distributed probability for all numbers between 0 and 10, you need to:
var a : int = Math.floor( Math.random() * 11 )
A: Math.round(Math.random()*10); maybe?
A: Math.random() returns a number between 0 - 1. Multiply it with 10 an round it using an int.
// random number between 1- 10
var randomRounded : int = Math.round(Math.random() * 10);
Edit: more accurate version
// more accurate
var randomRounded : int = Math.floor(Math.random() * 11);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: autofac instance initialization notification Is there a way to determine when Autofac has completed an initialization of an instance?
You may need it if you have Lazy dependencies, or you inject dependencies via properties.
Possible solution might look like this:
public class Component : IKeepMeInformed {
private readonly IOtherComponent otherComponent;
public class Component(Lazy<IOtherComponent> otherComponent) {
this.otherComponent = otherComponent;
}
void IKeepMeInformed.InitializationCompleted() {
// Do whatever you need with this.otherComponent.Value
}
}
A: Not directly tied to Lazy components, but Autofac exposes events that lets you hook into the lifetime of instances. Listening for the OnActivated event will enable you to do stuff immediately after an instance have been created. E.g.:
builder.RegisterType<OtherComponentImplementation>().As<IOtherComponent>()
.OnActivated(e => InitializationCompleted(e.Instance));
Update: actually, in the context of your Component class, you should "know" when the instance is initialized. It will be whenever you access the Lazy<>.Value property first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to remove/clear previously drawn lines before redrawing new lines in Qt? I am drawing few lines using paintEvent(QPaintEvent * event). Sometime later if I want to draw new lines then the previously drawn lines are not cleared/removed. How could I draw the new lines only, by removing/clearing old lines. Is there any property to clear the previously drawn lines.Please let me know.
void QGraphWidget::paintEvent(QPaintEvent * event)
{
const QRect & rect = event->rect();
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
drawLines(painter, rect);//calling painter.drawLine() inside
}
Thanks...
A: In my opinion, the correct approach is to clear the area before drawing new lines. This can be achieved either by using the autoFillBackground property as proposed by Stephen Chu, or by calling manually the QPainter::eraseRect() before drawing your lines in the QGraphWidget::paintEvent method.
void QGraphWidget::paintEvent(QPaintEvent * event)
{
const QRect & rect = event->rect();
QPainter painter(this);
painter.eraseRect(rect);
painter.setRenderHint(QPainter::Antialiasing);
drawLines(painter, rect);
}
Another option is to draw "negatively" the lines from the previous call to QGraphWidget::paintEvent. If you store the coordinate of your old lines, you might first draw lines using the background brush and then draw your new lines using the foreground brush. See code sample that might fit into you drawLines method. Note that if you draw something else in your widget, drawing the lines negatively might erase some of the other graphics which is why the first approach, erasing all the GraphWidget area, is better.
// save the current brush
QBrush currentBrush = painter.brush();
// draw the old line with the background brush
painter.setBrush(background());
painter.drawLine(oldLine);
// draw the new line with the current brush
painter.setBrush(currentBrush);
painter.drawLine(newLine);
A: You want to fill your widget with window background color before redraw. Set autoFillBackground to true after you create the widget and Qt will handle this for you
A: I don't think there is a specific call to remove the line. If you're repainting the entire area each time paintEvent() function is called you shouldn't see previous lines. If you're not repainting the area, you'll have to draw over the line yourself. This code for instance is drawing a line in a different position each time the method is invoked:
QPainter painter(this);
painter.setBrush(QBrush(Qt::red));
painter.drawRect(rect());
painter.setPen(QPen(Qt::yellow));
static int i = 0;
painter.drawLine(QPointF(i, i), QPointF(i, height() - i));
i++;
but "previous lines" are cleared completely. If you want to keep those you'll have to repaint only a specific area or you'll have to repaint those.
A: This is one way to delete whole line from QT.
me->setFocus();
int pos;
QTextCursor tc= me->textCursor();
pos=tc.columnNumber();
tc.select(QTextCursor::LineUnderCursor);
QString str=tc.selectedText();
tc.removeSelectedText();
tc.movePosition(QTextCursor::NextBlock,QTextCursor::MoveAnchor);
tc.insertText(str);
tc.insertBlock();
tc.movePosition(QTextCursor::PreviousBlock,QTextCursor::MoveAnchor);
tc.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
me->setTextCursor(tc);
return true;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Create a FileReader from an XMLResponse? I'm trying to create a FileReader (not a Document) from an XMLResponse like this :
// Parse XML Response
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(XMLResponse));
Document doc = db.parse(inStream);
But I don't know how to use the InputSource to create it ?
A: You can't create a FileReader, because the response may not be coming from a file. But, as it seems, you can obtain a Reader, which is the proper way to refer to readers.
If a method requires specifically a FileReader, the method is not designed properly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Convert NSString to C string, increment and come back to NSString I'm trying to develop a simple application where i can encrypt a message. The algorithm is Caesar's algorithm and for example, for 'Hello World' it prints 'KHOOR ZRUOG' if the increment is 3 (standard).
My problem is how to take each single character and increment it...
I've tried this:
NSString *text = @"hello";
int q, increment = 3;
NSString *string;
for (q = 0; q < [text length]; q++) {
string = [text substringWithRange:NSMakeRange(q, 1)];
const char *c = [string UTF8String] + increment;
NSLog(@"%@", [NSString stringWithUTF8String:c]);
}
very simple but it doesn't work.. My theory was: take each single character, transform into c string and increment it, then return to NSString and print it, but xcode print nothing, also if i print the char 'c' i can't see the result in console. Where is the problem?
A: First of all, incrementing byte by byte only works for ASCII strings. If you use UTF-8, you will get garbage for glyphs that have multi-byte representations.
With that in mind, this should work (and work faster than characterAtIndex: and similar methods):
NSString *foo = @"FOOBAR";
int increment = 3;
NSUInteger bufferSize = [foo length] + 1;
char *buffer = (char *)calloc(bufferSize, sizeof(char));
if ([foo getCString:buffer maxLength:bufferSize encoding:NSASCIIStringEncoding]) {
int bufferLen = strlen(buffer);
for (int i = 0; i < bufferLen; i++) {
buffer[i] += increment;
if (buffer[i] > 'Z') {
buffer[i] -= 26;
}
}
NSString *encoded = [NSString stringWithCString:buffer
encoding:NSASCIIStringEncoding];
}
free(buffer);
A: first of all replace your code with this:
for (q = 0; q < [text length]; q++) {
string = [text substringWithRange:NSMakeRange(q, 1)];
const char *c = [string UTF8String];
NSLog(@"Addr: 0x%X", c);
c = c + increment;
NSLog(@"Addr: 0x%X", c);
NSLog(@"%@", [NSString stringWithUTF8String:c]);
}
Now you can figure out your problem. const char *c is a pointer. A pointer saves a memory address.
When I run this code the first log output is this:
Addr: 0x711DD10
that means the char 'h' from the NSString named string with the value @"h" is saved at address 0x711DD10 in memory.
Now we increment this address by 3. Next output is this:
Addr: 0x711DD13
In my case at this address there is a '0x00'. But it doesn't matter what is actually there because a 'k' won't be there (unless you are very lucky).
If you are happy there is a 0x00 too. Because then nothing bad will happen. If you are unlucky there is something else. If there is something other than 0x00 (or the string delimiter or "end of string") NSString will try to convert it. It might crash while trying this, or it might open a huge security hole.
so instead of manipulating pointers you have to manipulate the values where they point to.
You can do this like this:
for (q = 0; q < [text length]; q++) {
string = [text substringWithRange:NSMakeRange(q, 1)];
const char *c = [string UTF8String]; // get the pointer
char character = *c; // get the character from this pointer address
character = character + 3; // add 3 to the letter
char cString[2] = {0, 0}; // create a cstring with length of 1. The second char is \0, the delimiter (the "end marker") of the string
cString[0] = character; // assign our changed character to the first character of the cstring
NSLog(@"%@", [NSString stringWithUTF8String:cString]); // profit...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JDBC Connection Link Failure - How to fail over? I have a stand-alone Java windows application developed based on Swing. It connects to a MySQL database for data storage. In case the database connection fails, I am getting a link failure exception from the MySQL JDBC driver (MySQLNonTransientConnectionException). I don't want to re-instantiate my database connection object or the whole program in case such a link failure issue happens. I just want to tell the user to try again later without having to restart the entire application. If the user is asked to restart the entire application, that would probably give a negative impression on the quality of the program. What do you think would be the preferred way for a standard java application to fail-over after such a database link failure without having to re-instantiate all the communication objects? Thanks in advance.
A: Use a Connection Pool (such as C3PO or DBCP). Your application takes the Connections from the pool, executes the statement(s) and puts the Connection back into the pool. The pool can be configured to test the JDBC Connections. For example, if they become stale, they can be automatically reinstantiated by the pool.
If your application takes the Connection from the pool, it will be a valid Connection. Let the pool handle the management of valid/invalid/stale JDBC Connections.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Wrap panel with "kind of" two way wraping So I have a wrappanel which is wrapped vertically. The items are added at run-time, but all those items (user controls) have different widths and because the wrappanel is wrapped vertically, it stacks them dowm and when they cover the vertical space they wrap to the next column. BUT what I need is "kind of" two way wrapping, i.e. I added a first item which is 200px in width, then I added a second item which is like 50px in width, but when I add a third item which is like 100px in width I want it to not to go to the next row, but place itself in that free spot the 50px control left there depending on that 200px control on top (that leaves a 150px space and a 100px control clearly fits). Of course when it doesn't fit, it wraps to the next row, and that's all OK.
Here's an images to clarify this (Can't upload'em here):
That's what happens:
image 1
And that's what I want:
image 2
Sorry for my english, it's not my primary language. I hope you'll understand my question.
A: You definitely can't use a single panel to accomplish that! You can use a stackpanel where to insert multiple and dynamic wrappanel with horizontal orientation to have "column" behavior you need
A: Well, I did it. Just wrote a custom wrappanel with the behavior I wanted.
Here it is:
public class TwoWayWrapPanel : Panel
{
int _rowCount = 0;
public int RowCount
{
get { return _rowCount; }
set { _rowCount = value; }
}
protected override Size MeasureOverride(Size availableSize)
{
Size resultSize = new Size(0, 0);
double columnWidth = 0;
double usedSpace = 0;
double nullX = 0;
double currentX = 0;
double currentY = 0;
bool isFirst = true;
int row = 0;
foreach (UIElement child in Children)
{
child.Measure(availableSize);
if (isFirst)
{
columnWidth = child.DesiredSize.Width;
resultSize.Width += columnWidth;
currentY += child.DesiredSize.Height;
row++;
isFirst = false;
}
else
{
if (columnWidth >= usedSpace + child.DesiredSize.Width & _rowCount > 1)
{
currentX = nullX + usedSpace;
usedSpace += child.DesiredSize.Width;
}
else
{
row++;
if (row + 1 > _rowCount | child.DesiredSize.Width > columnWidth)
{
row = 0;
currentX = nullX + columnWidth;
nullX = currentX;
usedSpace = 0;
columnWidth = child.DesiredSize.Width;
currentY = child.DesiredSize.Height;
row++;
resultSize.Width += columnWidth;
}
else
{
currentY += child.DesiredSize.Height;
currentX = nullX;
usedSpace = child.DesiredSize.Width;
}
}
}
}
return resultSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
double columnWidth = 0;
double usedSpace = 0;
double nullX = 0;
double currentX = 0;
double currentY = 0;
bool isFirst = true;
int row = 0;
foreach (UIElement child in Children)
{
//First item in the collection
if (isFirst)
{
child.Arrange(new Rect(currentX, currentY, child.DesiredSize.Width, child.DesiredSize.Height));
columnWidth = child.DesiredSize.Width;
currentY += child.DesiredSize.Height;
row++;
isFirst = false;
}
else
{
//Current item fits so place it in the same row
if (columnWidth >= usedSpace + child.DesiredSize.Width & _rowCount > 1)
{
currentX = nullX + usedSpace;
child.Arrange(new Rect(currentX, currentY, child.DesiredSize.Width, child.DesiredSize.Height));
usedSpace += child.DesiredSize.Width;
}
else
{
row++;
//The row limit is reached or the item width is greater than primary item width. Creating new column
if (row + 1 > _rowCount | child.DesiredSize.Width > columnWidth)
{
row = 0;
currentY = 0;
currentX = nullX + columnWidth;
nullX = currentX;
usedSpace = 0;
child.Arrange(new Rect(currentX, currentY, child.DesiredSize.Width, child.DesiredSize.Height));
columnWidth = child.DesiredSize.Width;
currentY += child.DesiredSize.Height;
row++;
}
//Item doesn't fit. Adding to the new row in the same column
else
{
usedSpace = 0;
currentY += child.DesiredSize.Height;
currentX = nullX;
child.Arrange(new Rect(currentX, currentY, child.DesiredSize.Width, child.DesiredSize.Height));
usedSpace += child.DesiredSize.Width;
}
}
}
}
return finalSize;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I save my image as BMP format? I know that I should use the compress method for saving a bitmap file.
FileOutputStream fos = new FileOutputStream(imagefile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
but I want to save my image as bmp format while "Bitmap.CompressFormat" only supports PNG and JPEG. How can I save my image file as BMP format?
Thanks,
A: you can use copyPixelsToBuffer
to store the bitmap pixel into a buffer and, than wrote your buffer into the sd.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to look through multiple arrays? I have an array that looks like this?
Array ( [0] => 15 [id] => 15 )
Array ( [0] => 16 [id] => 16 )
I was wondering how can I know one from each other, if I want to echo the values separately?
$getid = mysql_query($query);
while ($get_id = mysql_fetch_array($getid)){
print_r($get_id);
}
any ideas?
edit:
If I echo $get_id['id'].', '; I will get 15, 16. What I want is to be able to echo them separately.
or the arrays to become:
Array ( [0] => 15 [id] => 15 )
Array ( [1] => 16 [id] => 16 )
edit 1: I figured it out:
$i = 0;
$getid = mysql_query($query);
while ($get_id = mysql_fetch_array($getid)){
$test[$i] = $get_id;
$i++;
}
A: You need
$get_id['id']
or eventually
$get_id[0];
A: i figure it out
$i = 0;
$getid = mysql_query($query);
while ($get_id = mysql_fetch_array($getid)){
$test_time[$i] = $get_id;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: How to Optimize this Image convolution filter Method in MonoTouch? After having realized that no realtime graphics effect library exists for MonoTouch, I decided to write my own. After some research I've written a convolution method that works perfectly but, even using unsafe code, is VERY SLOW.
What I'm doing wrong? Is there some optimization that I'm missing?
Here is my c# class, any suggestion, not matter how small, is welcome!
using System;
using System.Drawing;
using MonoTouch.CoreGraphics;
using System.Runtime.InteropServices;
using MonoTouch.UIKit;
using MonoTouch;
namespace FilterLibrary
{
public class ConvMatrix
{
public int Factor { get; set; }
public int Offset { get; set; }
private int[,] _matrix = { {0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0}
};
public int[,] Matrix
{
get { return _matrix; }
set
{
_matrix = value;
Factor = 0;
for (int i = 0; i < Size; i++)
for (int j = 0; j < Size; j++)
Factor += _matrix[i, j];
if (Factor == 0)
Factor = 1;
}
}
private int _size = 5;
public int Size
{
get { return _size; }
set
{
if (value != 1 && value != 3 && value != 5 && value != 7)
_size = 5;
else
_size = value;
}
}
public ConvMatrix()
{
Offset = 0;
Factor = 1;
}
}
public class ConvolutionFilter
{
public ConvolutionFilter ()
{
}
public static CGImage GaussianSmooth (CGImage image)
{
ConvMatrix matr = new ConvMatrix ();
matr.Matrix = new int[5, 5] {
{ 1 , 4 , 7 , 4 , 1 },
{ 4 ,16 ,26 ,16 , 4 },
{ 7 ,26 ,41 ,26 , 7 },
{ 4 ,16 ,26 ,16 , 4 },
{ 1 , 4 , 7 , 4 , 1 }
};
return Filter.ImageConvolution (image, matr);
}
public static CGImage MotionBlur (CGImage image)
{
ConvMatrix matr = new ConvMatrix ();
matr.Size = 7;
matr.Matrix = new int[7, 7] {
{ 1 , 0 , 0 , 0 , 0 , 0 , 0},
{ 0 , 1 , 0 , 0 , 0 , 0 , 0},
{ 0 , 0 , 1 , 0 , 0 , 0 , 0},
{ 0 , 0 , 0 , 1 , 0 , 0 , 0},
{ 0 , 0 , 0 , 0 , 1 , 0 , 0},
{ 0 , 0 , 0 , 0 , 0 , 1 , 0},
{ 0 , 0 , 0 , 0 , 0 , 0 , 1}
};
return Filter.ImageConvolution (image, matr);
}
public static CGBitmapContext ConvertToBitmapRGBA8 (CGImage imageRef)
{
// Create an empty bitmap context to draw the uiimage into
CGBitmapContext context = NewEmptyBitmapRGBA8ContextFromImage (imageRef);
if (context == null) {
Console.WriteLine ("ERROR: failed to create bitmap context");
return null;
}
RectangleF rect = new RectangleF (0.0f, 0.0f, imageRef.Width, imageRef.Height);
context.ClearRect (rect); //Clear memory area from old garbage
context.DrawImage (rect, imageRef); // Draw image into the context to get the raw image data in our format
return context;
}
public static CGBitmapContext NewEmptyBitmapRGBA8ContextFromImage (CGImage image)
{
CGBitmapContext context = null;
CGColorSpace colorSpace;
IntPtr bitmapData;
int bitsPerComponent = 8; //Forcing only 8 bit formats for now...
int width = image.Width;
int height = image.Height;
int bytesPerRow = image.BytesPerRow;
int bufferLength = bytesPerRow * height;
colorSpace = CGColorSpace.CreateDeviceRGB ();
if (colorSpace == null) {
Console.WriteLine ("Error allocating color space RGB");
return null;
}
// Allocate memory for image data
bitmapData = Marshal.AllocHGlobal (bufferLength);
//Create bitmap context forcing Premultiplied Alpha as required by Apple iOS
if (image.AlphaInfo == CGImageAlphaInfo.PremultipliedFirst || image.AlphaInfo == CGImageAlphaInfo.First) {
context = new CGBitmapContext (bitmapData,
width,
height,
bitsPerComponent,
bytesPerRow,
colorSpace,
CGImageAlphaInfo.PremultipliedFirst); // ARGB
} else {
if (image.AlphaInfo == CGImageAlphaInfo.PremultipliedLast || image.AlphaInfo == CGImageAlphaInfo.Last) {
context = new CGBitmapContext (bitmapData,
width,
height,
bitsPerComponent,
bytesPerRow,
colorSpace,
CGImageAlphaInfo.PremultipliedLast); //RGBA
} else {
Console.WriteLine ("ERROR image format non supported: " + image.AlphaInfo);
throw new Exception ("ERROR image format non supported: " + image.AlphaInfo);
}
}
if (context == null) {
Console.WriteLine ("Bitmap context from BitmapData not created");
}
return context;
}
public static CGImage ImageConvolution (CGImage image, ConvMatrix fmat)
{
//Avoid division by 0
if (fmat.Factor == 0)
return image;
//Create a clone of the original image
CGImage srcImage = image.Clone ();
//init some temporary vars
int x, y, filterx, filtery, tempx, tempy;
int s = fmat.Size / 2;
int a, r, g, b, tr, tg, tb, ta;
int a_div;
float a_mul;
//Compute pixel size (bytes per pixel)
int pixelSize = image.BitsPerPixel / image.BitsPerComponent;
//Create bitmap contexts
CGBitmapContext imageData = ConvertToBitmapRGBA8 (image);
CGBitmapContext srcImageData = ConvertToBitmapRGBA8 (srcImage);
// Scan0 is the memory address where pixel-array begins.
IntPtr scan0 = srcImageData.Data;
// Stride is the width of each row of pixels.
int stride = srcImageData.BytesPerRow;
unsafe {
byte* tempPixel;
for (y = s; y < srcImageData.Height - s; y++) {
for (x = s; x < srcImageData.Width - s; x++) {
a = r = g = b = 0;
a_div = 0;
a_mul = 0.0f;
//Convolution
for (filtery = 0; filtery < fmat.Size; filtery++) {
for (filterx = 0; filterx < fmat.Size; filterx++) {
// Get nearby pixel's position
tempx = x + filterx - s;
tempy = y + filtery - s;
// Go to that pixel in pixel-array
tempPixel = (byte*)scan0 + (tempy * stride) + (tempx * pixelSize);
if (srcImageData.AlphaInfo == CGImageAlphaInfo.First) {
// The format is ARGB (1 byte each).
ta = (int)*tempPixel;
tr = (int)*(tempPixel + 1);
tg = (int)*(tempPixel + 2);
tb = (int)*(tempPixel + 3);
a += fmat.Matrix [filtery, filterx] * ta;
r += fmat.Matrix [filtery, filterx] * (tr);
g += fmat.Matrix [filtery, filterx] * (tg);
b += fmat.Matrix [filtery, filterx] * (tb);
}
if (srcImageData.AlphaInfo == CGImageAlphaInfo.Last) {
// The format is RGBA (1 byte each).
tr = (int)*tempPixel;
tg = (int)*(tempPixel + 1);
tb = (int)*(tempPixel + 2);
ta = (int)*(tempPixel + 3);
a += fmat.Matrix [filtery, filterx] * ta;
r += fmat.Matrix [filtery, filterx] * (tr);
g += fmat.Matrix [filtery, filterx] * (tg);
b += fmat.Matrix [filtery, filterx] * (tb);
}
if (srcImageData.AlphaInfo == CGImageAlphaInfo.PremultipliedFirst) {
// The format is premultiplied ARGB (1 byte each).
ta = (int)*tempPixel;
tr = (int)*(tempPixel + 1);
tg = (int)*(tempPixel + 2);
tb = (int)*(tempPixel + 3);
// Computing alpha
a += fmat.Matrix [filtery, filterx] * ta;
a_div = (ta / 255);
// Computing rgb
if (a_div == 0) {
r += fmat.Matrix [filtery, filterx] * (tr);
g += fmat.Matrix [filtery, filterx] * (tg);
b += fmat.Matrix [filtery, filterx] * (tb);
} else {
r += fmat.Matrix [filtery, filterx] * (tr / a_div); // "Dividing the premultiplied value by the
g += fmat.Matrix [filtery, filterx] * (tg / a_div); // alpha value to get the original color
b += fmat.Matrix [filtery, filterx] * (tb / a_div); // value before matrix multiplication"
}
}
if (srcImageData.AlphaInfo == CGImageAlphaInfo.PremultipliedLast) {
// The format is premultiplied RGBA (1 byte each). Get em
tr = (int)*tempPixel;
tg = (int)*(tempPixel + 1);
tb = (int)*(tempPixel + 2);
ta = (int)*(tempPixel + 3);
// Computing alpha
a += fmat.Matrix [filtery, filterx] * ta;
a_div = (ta / 255);
// Computing rgb
if (a_div == 0) {
r += fmat.Matrix [filtery, filterx] * (tr);
g += fmat.Matrix [filtery, filterx] * (tg);
b += fmat.Matrix [filtery, filterx] * (tb);
} else {
r += fmat.Matrix [filtery, filterx] * (tr / a_div); // "Dividing the premultiplied value by the
g += fmat.Matrix [filtery, filterx] * (tg / a_div); // alpha value to get the original color
b += fmat.Matrix [filtery, filterx] * (tb / a_div); // value before matrix multiplication"
}
}
}
}
// Remove values out of [0,255]
a = Math.Min (Math.Max ((a / fmat.Factor) + fmat.Offset, 0), 255);
r = Math.Min (Math.Max ((r / fmat.Factor) + fmat.Offset, 0), 255);
g = Math.Min (Math.Max ((g / fmat.Factor) + fmat.Offset, 0), 255);
b = Math.Min (Math.Max ((b / fmat.Factor) + fmat.Offset, 0), 255);
// Premultiplying color value by alpha value if needed by image format
if (srcImageData.AlphaInfo == CGImageAlphaInfo.PremultipliedFirst || srcImageData.AlphaInfo == CGImageAlphaInfo.PremultipliedLast) {
a_mul = (a / 255.0f);
r = (int)(r * a_mul);
g = (int)(g * a_mul);
b = (int)(b * a_mul);
}
// Finally compute new pixel position (in new image) and write the pixels.
if (srcImageData.AlphaInfo == CGImageAlphaInfo.PremultipliedFirst || srcImageData.AlphaInfo == CGImageAlphaInfo.First) {
// The format is ARGB (1 byte each)
byte* newpixel = (byte*)imageData.Data + (y * imageData.BytesPerRow) + (x * pixelSize);
*newpixel = (byte)a;
*(newpixel + 1) = (byte)r;
*(newpixel + 2) = (byte)g;
*(newpixel + 3) = (byte)b;
}
if (srcImageData.AlphaInfo == CGImageAlphaInfo.PremultipliedLast || srcImageData.AlphaInfo == CGImageAlphaInfo.Last) {
// The format is RGBA (1 byte each)
byte* newpixel = (byte*)imageData.Data + (y * imageData.BytesPerRow) + (x * pixelSize);
*newpixel = (byte)r;
*(newpixel + 1) = (byte)g;
*(newpixel + 2) = (byte)b;
*(newpixel + 3) = (byte)a;
}
}
}
}
return imageData.ToImage ();
}
}
}
A: Well, there's lots that can be done to improve that code, like moving all those decisions out of the main loop; do them outside, use them to provide a method for that loop to call.
However, the main thing would be to find out if you can wrap Core Image, which ought to be very fast indeed, as it will do it using shaders on the GPU.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: m2eclipse can't find any dependencies I have created a new Maven project in eclipse, using the Nexus Indexer Archetype.
I am trying to add dependencies to this project via Maven -> Add Dependency. But whenever I search for anything, no dependencies are found.
I have tried setting my Maven -> Installations, to both Embedded and to External (where External points to my M2_HOME directory), but no results from either.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Pack setup files to single executable setup I have an old setup of the old program written on c++ which contains multiple installation files files.
_SETUP.1
_SETUP.DLL
_INST32I.EX_
_ISDEL.EXE
SETUP.EXE
DISK1.ID
SETUP.INI
SETUP.INS
_SETUP.LIB
SETUP.PKG
I want to combine all that in to single executable file and i want to execute SETUP.EXE when user would run that single executable. Is it possible to achieve somehow?
The easiest way is simple create archive and say to user to to unpack that and to run SETUP.EXE but i am just wondering may be i can create setup like i describe above.
A: IExpress.exe is ideal for your job. Google for samples. It is included in your Windows installation. Just open a Command Prompt and type iexpress.exe - this starts a wizard that helps you getting started.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: border-radius on . No border rounding I have css looks like that:
#caltable th {
border: solid 1px #333;
border-radius: 7px;
background: #f00;
}
But this is what i've got in browser (Chrome/FF):
The question is how to get black line also rounded?
A: Change border-collapse:collapse to border-collapse:separate on the <table>.
You should also add support for browsers which are not at the newwest version:
-moz-border-radius: 7px;
-o-border-radius: 7px;
-ms-border-radius: 7px;
-webkit-border-radius: 7px;
A: You do not need to. It's done automatically
http://sandbox.phpcode.eu/g/e9ab8
http://phpcode.eu/images/1317547931.png
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Parse a large file - OutOfMemory - Android I'm trying to parse a large file in android.The xml file size exceeds 2Mb.
I'm using this code:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(XMLResponse));
Document doc = db.parse(inStream);
I got an outofmemory error and I dont know how to fix this problem!
I'm working on a Xperia arc device!
A: Parsing an XML file using a DOM tree requires a lot of memory because the parser needs to retain a lot of information about your file. I did a few experiments with DOM trees a while ago, and found that parsing a file of size n requires 7n memory space.
You can try to reduce the memory footprint of your program by removing the DOM parser and using a SAX parser instead. SAX psrsers are fundamentally different and require a lot less memory when running.
A: If the document is big then better use XMLReader if you can, that way you don't need to store the whole document in memory at once. Usually that would save me in the past as you rarely need all the xml. More frequently you just need to fetch some content strings and attributes from the document and that saves a lot of memory. You just run through the doc and throw it out while retaining all the useful stuff.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Are preferences persistent across updates Whilst in the debugging stage and using Eclipse I install myappv1. Then later I install myappv2 (both have the same package name). Because the name is different Android installs them side by side. Will the preferences established by myappv1 be available to myappv2? I see that if I just install a later version off myappv1 it replaces the original and the prefs seem to persist.
A: Yes, application preferences are persistent across updates. However, you need to understand how Android application signing and versioning works in order to ensure that updates to your application are treated as such.
In short...
When you release an update to your app, you must sign it with the same key as you used on all earlier versions (that way Android knows it's the same app). To let Android know that the version has changed, increment the value of the android:versionCode value in AndroidManifest.xml (You should also update the user-displayable android:versionName value).
For more details, check out http://developer.android.com/guide/publishing/app-signing.html and http://developer.android.com/guide/publishing/versioning.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Building a 1,000M row MySQL table reposted on serverfault
Questions
Question 1: as the size of the database table gets larger how can I tune MySQL to increase the speed of the LOAD DATA INFILE call?
Question 2: would using a cluster of computers to load different csv files, improve the performance or kill it? (this is my bench-marking task for tomorrow using the load data and bulk inserts)
Goal
We are trying out different combinations of feature detectors and clustering parameters for image search, as a result we need to be able to build and big databases in a timely fashion.
Machine Info
The machine has 256 gig of ram and there are another 2 machines available with the same amount of ram if there is a way to improve the creation time by distributing the database?
Table Schema
the table schema looks like
+---------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+------------------+------+-----+---------+----------------+
| match_index | int(10) unsigned | NO | PRI | NULL | |
| cluster_index | int(10) unsigned | NO | PRI | NULL | |
| id | int(11) | NO | PRI | NULL | auto_increment |
| tfidf | float | NO | | 0 | |
+---------------+------------------+------+-----+---------+----------------+
Benchmarking so far
First step was to compare bulk inserts vs loading from a binary file into an empty table.
It took: 0:09:12.394571 to do 4,000 inserts with 5,000 rows per insert
It took: 0:03:11.368320 seconds to load 20,000,000 rows from a csv file
Given the difference in performance I have gone with loading the data from a binary csv file, first I loaded binary files containing 100K, 1M, 20M, 200M rows using the call below.
LOAD DATA INFILE '/mnt/tests/data.csv' INTO TABLE test;
I killed the 200M row binary file (~3GB csv file) load after 2 hours.
So I ran a script to create the table, and insert different numbers of rows from a binary file then drop the table, see the graph below.
It took about 7 seconds to insert 1M rows from the binary file. Next I decided to benchmark inserting 1M rows at a time to see if there was going to be a bottleneck at a particular database size. Once the Database hit approximately 59M rows the average insert time dropped to approximately 5,000/second
Setting the global key_buffer_size = 4294967296 improved the speeds slightly for inserting smaller binary files. The graph below shows the speeds for different numbers of rows
However for inserting 1M rows it didn't improve the performance.
rows: 1,000,000 time: 0:04:13.761428 inserts/sec: 3,940
vs for an empty database
rows: 1,000,000 time: 0:00:6.339295 inserts/sec: 315,492
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: HTMLPurifier Youtube <?php
require_once '/library/HTMLPurifier/HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
$config->set('Filter.YouTube', true);
$purifier = new HTMLPurifier($config);
?>
(^ This is my only settings for HTMLPurifier)
It should <span class="youtube-embed">nto6EvPFO0Q</span> make this in to a Youtube embbeded video. But it's not working. (Nothing happens simply)
But loading like this works:
<object width="425" height="350">
<param name="movie" value="http://www.youtube.com/v/nto6EvPFO0Q />
<param name="wmode" value="transparent" />
<embed src="http://www.youtube.com/v/nto6EvPFO0Q"
type="application/x-shockwave-flash"
wmode="transparent" width="425" height="350" />
</object>
(Is this a security issue? ^)
A: Use UTF-8. All other character sets are obsolete and should never be used except in legacy applications where you have no other choice.
Edit (after update of question):
First, you should use this:
<iframe class="youtube-player" type="text/html" width="640" height="385"
src="http://www.youtube.com/embed/XXXXIDXXXX" frameborder="0"></iframe>
Instead since it works on smart phones and the flash version doesn't.
Second, according to their documentation you need to download and include YouTube.php from http://repo.or.cz/w/htmlpurifier.git?a=blob;hb=HEAD;f=library/HTMLPurifier/Filter/YouTube.php (and when you do so update it to the new type of embed code).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to read an xml file from R.java I have an xml file inside the res folder under the xml forlder. I want to parse it with SAX. I know there are lots of example but I want to understand InputStream, InputSource, File deeply. I can reach the file writing R.xml.hippo (hippo is the name of the xml file).
But how can I give this resource as a stream?
I know when I write R.xml.hippo to anywhere it will be reference(int) but I want give it as a source. What is and how converting an int to starting point of stream?
A: You can read XML from assets folder as well as from res/raw folder.
To read from assets folder
AssetManager manager = getAssets();
InputStream inputStream = manager.open("your_xml.xml");
To read from raw folder
InputStream inputStream = getResources().openRawResource(R.raw.your_xml);
And parse this inputStream to your XML Parser.
A: You should place the file inside the raw folder. Then you can access it via Resources.openRawResource(). For more information refer to Android Developer's page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: "DEPRECATION WARNING: class_inheritable_attribute is deprecated...." when executing rake db:create When I follow the Spree Guides, I got an error message ,
yulong@ubuntu:~/mystore$ rake db:create
rake db:create
DEPRECATION WARNING: class_inheritable_attribute is deprecated, please use class_attribute method instead. Notice their behavior are slightly different, so refer to class_attribute documentation first. (called from <top (required)> at /home/yulong/mystore/config/application.rb:7)
DEPRECATION WARNING: class_inheritable_attribute is deprecated, please use class_attribute method instead. Notice their behavior are slightly different, so refer to class_attribute documentation first. (called from <top (required)> at /home/yulong/mystore/config/application.rb:7)
DEPRECATION WARNING: class_inheritable_attribute is deprecated, please use class_attribute method instead. Notice their behavior are slightly different, so refer to class_attribute documentation first. (called from <top (required)> at /home/yulong/mystore/config/application.rb:7)
DEPRECATION WARNING: class_inheritable_attribute is deprecated, please use class_attribute method instead. Notice their behavior are slightly different, so refer to class_attribute documentation first. (called from <top (required)> at /home/yulong/mystore/config/application.rb:7)
rake aborted!
Fixtures is not a class
yulong@ubuntu:~/mystore$ rails g spree:site
DEPRECATION WARNING: class_inheritable_attribute is deprecated, please use class_attribute method instead. Notice their behavior are slightly different, so refer to class_attribute documentation first. (called from <top (required)> at /home/yulong/mystore/config/application.rb:7)
DEPRECATION WARNING: class_inheritable_attribute is deprecated, please use class_attribute method instead. Notice their behavior are slightly different, so refer to class_attribute documentation first. (called from <top (required)> at /home/yulong/mystore/config/application.rb:7)
DEPRECATION WARNING: class_inheritable_attribute is deprecated, please use class_attribute method instead. Notice their behavior are slightly different, so refer to class_attribute documentation first. (called from <top (required)> at /home/yulong/mystore/config/application.rb:7)
DEPRECATION WARNING: class_inheritable_attribute is deprecated, please use class_attribute method instead. Notice their behavior are slightly different, so refer to class_attribute documentation first. (called from <top (required)> at /home/yulong/mystore/config/application.rb:7)
[DEPRECATION WARNING] Nested I18n namespace lookup under "activerecord.attributes.checkout" is no longer supported
create lib/spree_site.rb
remove public/index.html
append public/robots.txt
append db/seeds.rb
A: Please go through following link, which will help you to fix this issue in rails 3.1
http://martinciu.com/2011/07/difference-between-class_inheritable_attribute-and-class_attribute.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: RoR - password protected model I want to create password protected model. For example Post on the blog. I want to store this password in the database. And if user wants to see password protected post he needs to write this password. If there is no password in database everyone can see this post, each post can have its own pass. How can I create something like this in RoR? I
I only have found basic HTTP auth:
before_filter :authenticate
#protected
def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == "foo" && password == "bar"
end
end
but probably there is better solution for this? Do you have any ideas?
A: Something like this ?
def show
@post = Post.find(...)
if params[:post][:password].nil?
# Show a form with a password asked
elsif params[:post][:password] == @post.password
# Show post
else
flash[:error] = "Bad password"
# Render password form
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Conditional Comments within CSS I am currently developing a theme for a homepage but ran into a few problems. For whatever reason I have no access to editing the html code itself, and I need to write custom .css for IE (specifically versions below IE9).
I have "two" issues. First one is dual backgrounds. Versions below IE9 can't seem to render them flawlessly. If IE skips the element, this is fine but since the graphic in this element co-works with another element (for a smooth graphical transition), it makes the other element look weird. The graphic in this second element is a background within a div-box. I want this background to be another custom background that's only rendered if the user is using IE as browser; and if possible, I want this to only apply to versions below IE9 (site is rendered with dual backgrounds just fine in IE9).
http://patrikarvidsson.com/project/sohelp/illustration.jpg
CSS is as follows (#mainframe is the part under the header navigation box). The lower image is how it is rendered in IE8. IE7 shows the same. First one is FF/Chrome/Safari and IE9.
#mainframe {
background: url('img/bg2.png') no-repeat,
url('img/bg1.png') repeat-y !important;
}
I've searched quite a lot on the net, also been asking friends and this does not seem to be working without writing conditional comments within the html markup. Am I missing something? Is this doable somehow with only the use of .css files?
Site is using jquery. I don't know this stuff, but I thought I'd mention it just in case.
A: You might want to look into this article which explains how to use conditional comments to set classes on the html element. You can then use that class to target specific browsers in your stylesheet, in a clean way.
Your html tag would look something like this:
<!--[if lt IE 7]> <html class="ie6"> <![endif]-->
<!--[if IE 7]> <html class="ie7"> <![endif]-->
<!--[if IE 8]> <html class="ie8"> <![endif]-->
<!--[if IE 9]> <html class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html> <!--<![endif]-->
Edit 2
Since the announcement that IE10 will not support conditional comments I though it would be nice to update this answer. I tested the type of comments it will support and it seems that the above will still work, but if you want to target higher than 10 or only 10 you will be out of luck. As suggested by Microsoft themselves on their blog (link in comments @MarcoDemaio) you should use feature detection.
Then you can do something like this in your css:
.somestyle {
background: transparent url('derp.jpg') no-repeat;
}
/* ie6 fallsback class */
.ie6 .somestyle {
background: #eee;
}
Read the article, and good luck ;)
Edit 2:
Since IE7 isn't my greatest concern anymore and IE9 is pretty consistent in its behaviour I can get away wil just the following code (which will add a class only for IE versions less than IE9):
<!--[if lt IE 9]><html class="lte9"><![endif]-->
<!--[if gt IE 8|!IE]><!--><html><!--<![endif]-->
Edit 1:
Ok I managed to miss your "can't edit html" comment.
In that case you can only use browser specific hacks, I think they're dirty as hell but hey, if you have no other option......
Somthing like this:
.someclass {
*color: blue; /* IE 7 and below */
_color: blue; /* IE 6 */
}
/* IE6, IE7 - asterisk hack */
.someclass { *color: blue; }
/* IE8 - winning hack */
.someclass { color: blue\0/; } /* must be last declaration in the selector's ruleset */
A: I had this problem in my CMS application so...
Create a container div have it's class the browser name and version to be looks like
<div class="ie_6_0">
<div class="your_custom_elements">
///////
</div>
</div>
and do you CSS classes like
.your_custom_elements{common styles between versions}
.ie_6_0 .your_custom_elements{do somthink for old versions}
.ie_9_0 .your_custom_elements{do somthink for new versions}
UPDATE 1
or like
<div id="mainframe" class="ie_6_0">
///
</div>
and CSS like
#mainframe{common styles between versions}
#mainframe.ie_6_0{do somthink for old versions}
#mainframe.ie_9_0{do somthink for new versions}
ie_6_0: as your user browser name and version must request it and add it by code.
A: For your dual backgrounds problem, you simply need to add another containing element.
<div class="element">
...
</div>
becomes
<div class="container">
<div class="element">
...
</div>
</div>
I'm not sure why you wouldn't be able to manually edit the HTML, but if you have access to a javascript file and you're using jQuery, you can add the class like so:
$('.element').wrap('<div class="container" />');
You can use CSS hacks to avoid using conditional comments. CSS hacks aren't as commonly used now since the average user uses a browser that doesn't require any hacks to display properly, but it is still a completely valid and reliable way to avoid using HTML conditional statements. Depending on the specificity you want, you have a bunch of different hacks that you can use to only target specific versions of IE:
* html .element { color: #fff; /* IE6 only */ }
html .element { _color: #333; /* IE7 only */
*+html .element { color: #999; /* IE7 only */ }
html .element { *color: #000; /* IE7 and below */
html .element { color: #ccc\9; /* IE8 and below */ }
So:
#container { background: url(img/bg1.png) repeat-y\9; }
#container #mainframe {
background: url('img/bg2.png') no-repeat, url('img/bg1.png') repeat-y !important;
background: url('img/bg2.png') no-repeat\9; }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to create map tiles from OpenStreetMap offline, display it on Android? What I want is to display a simple offline map using OpenStreetMap. I cannot find in the web the right tools to create map tiles and use it to display a map in Android. I have downloaded different resources but it seems that I don't have any idea where to start. I want to integrate images from OpenStreetMap using JOSM but i don't know if I can use it on Android.
Can I use Mapnik? Your help will a great thank you.
A: Here is a step by step solution:
In brief:
1- You must download map tiles using Mobile Atlas Creator. I have explained the steps HERE
2- Move the resulting zip-file to /mnt/sdcard/osmdroid/ on your device.
3- Adding osmdroid-android-XXX.jar and slf4j-android-1.5.8.jar into build path your project
4- Adding MapView: You can add a MapView to your xml layout
<org.osmdroid.views.MapView
android:id="@+id/mapview"
android:layout_width="match_parent"
android:layout_height="match_parent"
tilesource="Mapnik"
/>
Or create a MapView programmatically:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
mResourceProxy = new ResourceProxyImpl(inflater.getContext().getApplicationContext());
mMapView = new MapView(inflater.getContext(), 256, mResourceProxy);
return mMapView;
}
Don't forget to add these permissions to your Manifest:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This is a good Sample Project.
Hope it Helps ;)
Important
As @Scai mentioned: recently Open Street Map announced that this tool is not good and had some problems:
This tool results in heavy traffic for the OSM tile servers and is likely to be blocked.
Please don't use it.
A: I'm currently developing (my first) Android application using the OpenStreetMap (OSM) API, so while I can't help you with the JSOM, I can try to help with the OSM part:
Assuming that you want to create a new activity in your android application that simply displays a OSM map, you might start with something like this:
package example.stackoverflow.osmdroid;
import android.app.Activity;
import android.os.Bundle;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
public class YourMap extends Activity {
// The MapView variable:
private MapView m_mapView;
// Default map zoom level:
private int MAP_DEFAULT_ZOOM = 15;
// Default map Latitude:
private double MAP_DEFAULT_LATITUDE = 38.535350;
// Default map Longitude:
private double MAP_DEFAULT_LONGITUDE = -121.753807;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Specify the XML layout to use:
setContentView(R.layout.osm_map);
// Find the MapView controller in that layout:
m_mapView = (MapView) findViewById(R.id.mapview);
// Setup the mapView controller:
m_mapView.setBuiltInZoomControls(true);
m_mapView.setMultiTouchControls(true);
m_mapView.setClickable(true);
m_mapView.setUseDataConnection(false);
m_mapView.getController().setZoom(MAP_DEFAULT_ZOOM);
m_mapView.getController().setCenter(
new GeoPoint(MAP_DEFAULT_LATITUDE, MAP_DEFAULT_LONGITUDE));
m_mapView.setTileSource(TileSourceFactory.MAPNIK);
} // end onCreate()
} // end class YourMap
Where your osm_map.xml layout may look something like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<org.osmdroid.views.MapView
android:id="@+id/mapview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:enabled="true"
android:clickable="true"
/>
</RelativeLayout>
As for the actual map tiles, there is a really cool program called Mobile Atlas Creator, which allows you to generate the necessary map tiles for the offline Android map implemented above.
Once you have the application installed, and you want to create a new atlas, you'll be asked to select your "desired altas format." When this pops up, select "Osmdroid zip."
Once everything loads, select a region on the map that you would like to create tiles for, select the zoom levels you want tiles for, and hit the "Add Selection" button in the column on the left, followed by "Create Atlas."
Oh, and depending on the source, you may need to check the "Create/Adjust Map tiles" checkbox to force the tiles to be exported as PNGs -- does anyone know if it's possible to use JPG with OSM?
Once the ZIP has been generated, I renamed it to "Mapnik.zip" and moved it to a newly created folder called "tiles" in my Eclipse Android project workspace. In order to get it working, I also had to open the zip file, and rename the top level folder from something like "Google Earth" (depending on the map source you used), to "Mapnik," in order for the tile to display in my Android application.
In order to actually load the tiles onto your phone, however, you'll need to use the ADB tool from the terminal. In your ADB tool directory, you'll want to run something like this (each line is a new command):
./adb shell rm -r /sdcard/osmdroid/
./adb shell mkdir /sdcard/osmdroi/
./adb push ~/path/to/your/mapnik.zip /sdcard/osmdroid
Depending on the size of the map and the speed of the phone's memory bus, this last step may take a several minutes to an hour to complete. Once done, your map should work -- I hope!
As I mentioned, this is the first time I've used the OSM API, so I'm by no means an expert on it, and I can only comment on what worked for me.
Hope this will help you get started!
EDIT:
I didn't have a chance to actually run the code that I wrote up yesterday, so I didn't catch a few of the errors. I just created a new project in Eclipse, dumped my code in there, fixed a few things and got it up and running. All changes that I made are reflected in the code above! I forgot several of the basic import statements, and I forgot to add permissions to the manifest.xml file.
The last few lines of my manifest.xml now look like this:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
And you also might want to add this to the manifest, although certainly not critical:
<supports-screens
android:anyDensity="true"
android:resizeable="false"
android:largeScreens="true"
android:normalScreens="true"
/>
Add this right after the <uses-sdk ... /> part.
Furthermore, be sure to import the following two JAR libraries:
osmdroid-android-3.0.3.jar // Or whatever version you're using...
and
slf4j-android-1.5.8.jar // Or whatever the latest version is...
Without this last JAR, my code kept crashing until I remembered to include it.
Make sure to modify the default coordinates so that they point to a location that you actually have map tiles for, otherwise you're not going to see much of anything, aside from a white canvas.
Sorry for not running the code on my end first!
A: Alternatively to map tiles you can also use vector data for your offline map, for example mapsforge or the Mapbox Android SDK. For more information consult the OSM wiki about offline OSM and Android libraries.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Create transparent form from png I have a png image that have transparent parts, how to set this png image like background image for my WinForms form and not lose transparency? i Use C#. Thanks!
A: Here I have written a code for painting the form. You can change the color and transparency according to our requirement. I used colors as background of the form. You can change it as picture as per your requirement. It is a sample code.
First you need to create a static class containing these functions
public enum FormType
{
MDI,
Child
}
public static void PaintFrom(Form frm, PaintEventArgs e, FormType formType)
{
if (formType == FormType.MDI)
{
Graphics mGraphics = e.Graphics;
Pen pen1 = new Pen(Color.FromArgb(96, 155, 173), 1);
Rectangle Area1 = new Rectangle(0, 0, frm.Width - 1, frm.Height - 1);
LinearGradientBrush LGB = new LinearGradientBrush(Area1, Color.FromArgb(96, 155, 173), Color.FromArgb(245, 251, 251), LinearGradientMode.Vertical);
mGraphics.FillRectangle(LGB, Area1);
mGraphics.DrawRectangle(pen1, Area1);
PictureBox picBox = new PictureBox();
Color backColor = Color.Transparent;
Bitmap bm = new Bitmap(ImagePath + "title_bar.png");
//frm.Controls.Add(picBox);
Point pt = new Point(0, 0);
picBox.Location = pt;
picBox.Image = bm;
picBox.Width = frm.Width - 1;
picBox.Height = 24;//frm.Height - 1;
picBox.BackColor = backColor;
picBox.BackgroundImageLayout = ImageLayout.Stretch;
PictureBox closeBox = new PictureBox();
//frm.Controls.Add(closeBox);
bm = new Bitmap(ImagePath + "close.gif");
pt = new Point(frm.Width - (bm.Width), -1);
closeBox.Location = pt;
closeBox.Image = bm;
closeBox.Width = bm.Width + 1;
closeBox.Height = bm.Width + 1;
closeBox.BackColor = backColor;
closeBox.BackgroundImageLayout = ImageLayout.Stretch;
PictureBox minBox = new PictureBox();
//frm.Controls.Add(closeBox);
bm = new Bitmap(ImagePath + "close.gif");
pt = new Point(frm.Width - (2*(bm.Width))-1, bm.Width);
minBox.Location = pt;
minBox.Image = bm;
minBox.Width = bm.Width + 1;
minBox.Height = bm.Width + 1;
minBox.BackColor = backColor;
minBox.BackgroundImageLayout = ImageLayout.Stretch;
frm.Controls.Add(picBox);
picBox.Controls.Add(closeBox);
picBox.Controls.Add(minBox);
minBox.Click+=new EventHandler(minBox_Click);
closeBox.Click += new EventHandler(closeBox_Click);
}
else
{
PaintForm(frm, e);
}
}
public static void PaintForm(Form frm, PaintEventArgs e)
{
Graphics mGraphics = e.Graphics;
Pen pen1 = new Pen(Color.FromArgb(96, 155, 173), 1);
Rectangle Area1 = new Rectangle(0, 0, frm.Width - 1, frm.Height - 1);
LinearGradientBrush LGB = new LinearGradientBrush(Area1, Color.FromArgb(96, 155, 173), Color.FromArgb(245, 251, 251), LinearGradientMode.Vertical);
mGraphics.FillRectangle(LGB, Area1);
mGraphics.DrawRectangle(pen1, Area1);
PictureBox picBox=new PictureBox();
Color backColor = Color.Transparent;
Bitmap bm=new Bitmap(ImagePath+"title_bar.png");
//frm.Controls.Add(picBox);
Point pt=new Point(0,0);
picBox.Location = pt;
picBox.Image = bm;
picBox.Width = frm.Width - 1;
picBox.Height = 24;//frm.Height - 1;
picBox.BackColor = backColor;
picBox.BackgroundImageLayout = ImageLayout.Stretch;
PictureBox closeBox = new PictureBox();
//frm.Controls.Add(closeBox);
bm = new Bitmap(ImagePath + "close.gif");
pt = new Point(frm.Width - (bm.Width), -1);
closeBox.Location = pt;
closeBox.Image = bm;
closeBox.Width = bm.Width + 1;
closeBox.Height = bm.Width + 1;
closeBox.BackColor = backColor;
closeBox.BackgroundImageLayout = ImageLayout.Stretch;
foreach (Control ctr in frm.Controls)
{
if (ctr.HasChildren)
{
if (ctr is DataGridView)
{
DataGridView dtg = ctr as DataGridView;
DataGridViewCellStyle dtstyle=new DataGridViewCellStyle();
dtstyle.BackColor = Color.FromArgb(96, 155, 173);
dtg.ColumnHeadersDefaultCellStyle = dtstyle;
}
else if (ctr is TextBox)
{
}
else if (ctr is TabControl)
{
}
else
{
ctr.BackColor = backColor;
}
}
if (ctr is Label)
{
ctr.BackColor = backColor;
}
}
frm.Controls.Add(picBox);
picBox.Controls.Add(closeBox);
closeBox.Click+=new EventHandler(closeBox_Click);
}
static void closeBox_Click(object sender, EventArgs e)
{
PictureBox close = sender as PictureBox;
PictureBox pic = close.Parent as PictureBox;
Form fm = pic.Parent as Form;
fm.Close();
}
static void minBox_Click(object sender, EventArgs e)
{
PictureBox min = sender as PictureBox;
PictureBox pic = min.Parent as PictureBox;
Form fm = pic.Parent as Form;
fm.WindowState = FormWindowState.Minimized;
}
Then you need to call a Paint Event for the form and in this event you can paint the form like this
private void frmComplaints_Paint(object sender, PaintEventArgs e)
{
UI.Common.PaintForm(this, e);
}
I have used a static class UI.Common for this function and i used an image for titlebar. In your case you can use a png image for background. The ImagePath in the code is a constant variable where you can set the path for directory where the image is saved
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: transforming a plist in another nsdictionary I'm not english, new to objective c and new to this website. But i hope you will understand my problem. I tried to use the search engine but i couldn't find a answer...
THE PROBLEM:
i have a plist file like this
<plist version="1.0">
<array>
<dict>
<key>ID</key>
<string>001</string>
<key>CAT</key>
<string>A</string>
<key>TITLE</key>
<string>AAAA01</string>
</dict>
<dict>
<key>ID</key>
<string>002</string>
<key>CAT</key>
<string>A</string>
<key>TITLE</key>
<string>AAAA02</string>
</dict>
<dict>
<key>ID</key>
<string>003</string>
<key>CAT</key>
<string>B</string>
<key>TITLE</key>
<string>BBBB01</string>
</dict>
.....
</array>
</plist>
so i have many entries like this. every entry has a category (CAT) like in my example "A" and "B".
now i need a code to transform this to the following:
NSArray
NSDictionary
CAT => "A"
VALUES => {"AAAA01","AAAA02"}
NSDictionary
CAT => "B"
VALUES => {"BBBB01", ...}
ETC.
MY SOLUTION:
i get the plist with the following code
NSString *path = [[NSBundle mainBundle] pathForResource:@"Dictonary" ofType:@"plist"];
arrayIndex = [[NSArray alloc] initWithContentsOfFile:path];
Now i have everything saved in the arrayIndex but then i dont find a way to transform the code in a new array to get my wanted result.
please can anybody help me?
THANK YOU very much!
A: This is straight programming.
It is more easily done in two steps saving trying to find an entry to add to.
// First create a dictionary of CAT and the values,
NSMutableDictionary *tempDict = [NSMutableDictionary dictionary];
for (NSDictionary *item in arrayIndex) {
NSString *cat = [item valueForKey:@"CAT"];
NSMutableArray *tempArray = [tempDict valueForKey:cat];
if (!tempArray) {
tempArray = [NSMutableArray array];
[tempDict setValue:tempArray forKey:cat];
}
NSString *v = [item valueForKey:@"TITLE"];
[tempArray addObject:v];
}
NSLog(@"tempDict: %@", tempDict);
// This may well be a good final result
// This step transforms the dictionary into a list of dictionaries
NSMutableArray *newList = [NSMutableArray array];
NSArray *keys = [[tempDict allKeys] sortedArrayUsingSelector:@selector(compare:)];
for (NSString *cat in keys) {
[newList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
cat, @"CAT",
[tempDict valueForKey:cat], @"VALUES",
nil]];
}
NSLog(@"newList: %@", newList);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: is there a uipickerview delegate method like scrollviewDidScroll? I have a customized UIPickerview and I do not want to use a datepicker. I want to implement the feature where when a user scrolls down/up the hours, the AM/PM component switches while the hour is scrolling. This means that I need to switch it before pickerView didSelectRow is called. Is there a way to do this?
Thanks
A: There is a trick to detect this but there is no delegate method/ property to detect if its scrolling or not
*
*take a property as isScrolling
*set isScrolling to true in func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? or equivalent method
*set isScrolling to false in func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
hope this helps, BTW this is what is explained in all the above mentioned answers
A: have to use this two UIPickerView delegate method for event:
DID END SCROLL:
- (void)pickerView:(UIPickerView *)pV didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSLog(@"pickerView didSelectRow %zd",row);
// DID END SCROLL: CALL YOUR HEANDLER METHOD!!
}
WILL START SCROLLING:
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
// WILL START SCROLLING: CALL YOUR HEANDLER METHOD!!
UILabel* label = (UILabel*)view;
if (!label){
label = [UILabel new];
[label setFrame:frame];
[label setBackgroundColor:[UIColor clearColor]];
[label setFont:[UIFont fontWithName:FONT_QUICKSAND_BOLD size:12]];
[label setTextAlignment:NSTextAlignmentRight];
[label setLineBreakMode:NSLineBreakByTruncatingMiddle];
[label setTextColor:UIColorFromRGB(0X2692ff)];
}
//Update labeltext here
[label setText:[NSString stringWithFormat:@"row %zd",row]];
return label;
}
obviosly except for the building of UIPickerview (firstTIME!); so u have to implement a fake didendscroll event when you finish to build you piker or ignore first willstart scroll for the visible piker row
A: Unfortunately, the above solutions (setting a flag when data source methods such as titleForRow are called and resetting it when didSelectRow is called) are sketchy and won't work in many cases. The data source methods may be called in many cases where there is no scrolling by the user - such as UI changes resulting in changing view layouts, and also may be called immediately after didSelectRow - you have no control over when these methods are called.
In relation to this particular question, these solutions may work, since these methods are always called when scrolling - just not ONLY when scrolling. However, care needs to be taken not to assume that the user MUST be scrolling in these cases. Also, if you manage a state machine with this flag (like disabling some button when scrolling and enabling it after), you'll get in trouble.
Finally, this only allows detecting a scroll (with the above caveats), but it won't tell you the speed or current values - so it would be difficult to tell when to switch the AM/PM label.
The only way I was able to reliably detect a scroll was through a mess of flags that I set when UI changes are made and other ugly hacks (like waiting 100 ms after a didSelectRow before trying to detect scrolls again, because I noticed calls to the data source immediately after didSelectRow). Adding willScroll/didScroll methods to the delegate seems like an obvious thing Apple neglected to add.
A: Use following method,
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
// put your logic here.
}
Above method is from UIPickerViewDelegate, If user selects any element using pickerview, this method is automatically triggered.
Hope it helps to you.
Edit :
I think you should use following method for detecting - in which direction user is scrolling ?
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSLog(@"scrolling to row is %@",[NSString stringWithFormat:@"index_%i",row]);
return [NSString stringWithFormat:@"index_%i",row];
}
whenever user is scrolling up/down above method is triggered automatically which is similar to UITableView. Remember UIPickerView is using UIPickerTableView which is private, so we can not detect the scrolling the way you want to have.
Let me explain the detecting the direction in pickerview.
Example. Visible rows are index_4,index_5,index_6,index_7. Now if user is scrolling down index_8 will be called. Similarly if user is scrolling to up index_3 will be called.
I hope this trick will solve your problem. Even-though let me know your feedback on this.
A: I just found a way to achieve "pickerDidScroll",it work fine. The key point is add KVO to the row view. Here is my code:
//picker view delegate
- (UIView*)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
if (!view) {
view = [[RatchetScrollUnit alloc] initWithFrame:CGRectZero];
//
[((RatchetScrollUnit*)view) addRatchetObserver:self];
}
return view;
}
//KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if (self.ratchet) {
NSInteger row = [self.ratchet selectedRowInComponent:0];
if (row != _lastRow) {
_lastRow = row;
if (self.delegate && [self.delegate respondsToSelector:@selector(ratchetScrollerDidRatchetedToTooth:)]) {
[self.delegate ratchetScrollerDidRatchetedToTooth:row];
}
}
}
}
The "RatchetScrollUnit" class :
@interface RatchetScrollUnit ()
@property (nonatomic,assign) BOOL observed;
@property (nonatomic,weak) NSObject *myObserver;
@end
@implementation RatchetScrollUnit
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
_observed = NO;
self.backgroundColor = [UIColor clearColor];
}
return self;
}
- (void)dealloc {
if (self.observed) {
[self removeObserver:self.myObserver forKeyPath:@"frame" context:nil];
}
}
- (void)addRatchetObserver:(NSObject*)observer {
if (self.observed) {
return;
}
self.observed = YES;
self.myObserver = observer;
//
[self addObserver:observer
forKeyPath:@"frame"
options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew
context:nil];
}
Have a try
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: heapsort implementation in c++ i have following code for heapsort
#include <iostream>
using namespace std;
void exch(int a[],int i,int j){
int s=a[i];
a[i]=a[j];
a[j]=s;
}
void sink(int a[],int k,int n){
//int n=sizeof(a)/sizeof(int);
while(2*k<=n){
int j=2*k;
if (j<n && (a[j]<a[j+1])) j++;
if (a[k]>=a[j]) break;
exch(a,k,j);
k=j;
}
}
void heapsort(int a[]){
int n=sizeof(a)/sizeof(int);
for (int k=n/2;k>=1;k--)
sink(a,k,n);
while(n>1){
exch(a,1,n--);
sink(a,1,n);
}
}
int main(){
int a[]={12,3,5,1,67,10,9.20};
int n=sizeof(a)/sizeof(int);
heapsort(a);
for (int i=0;i<n;i++){
cout<<a[i]<<" ";
}
return 0;
}
but result it shows me looks like this
12 3 5 1 67 10 9 Press any key to continue . . .
also look that in my array total number is 8 and here it shows me 7 as output, i think core of this problem should be this
1>c:\users\datuashvili\documents\visual studio 2010\projects\heap\heap\heap.cpp(36): warning C4244: 'initializing' : conversion from 'double' to 'int', possible loss of data
it seams that possible loss of data while converting from double to int force code works incorrectly,am i correct or wrong?please help me
A: You wrote a . instead of a , between the 9 and 20:
int a[]={12,3,5,1,67,10,9.20};
This results in 7 numbers, the last of which is the double 9.20 which gets converted to an int.
Additionally, this code is wrong:
void heapsort(int a[]){
int n=sizeof(a)/sizeof(int);
Array arguments are actually passed as pointers, so sizeof(a) won't give you the correct result. You should pass in the array size as an additional parameter instead.
A: One problem I can see immediately is here:
void heapsort(int a[]){
int n=sizeof(a)/sizeof(int);
You cannot pass an entire array as a parameter to a function in C/C++. The parameter syntax int a[] is, of course, confusing, but in fact it's equivalent to int* a. heapsort() can't know the size of the array to which a points. You have to pass the size in as a separate parameter.
A: In addition to all the other comments (sizeof(a), passing [] as arguments, having a . in the init-list), you want to write C++-code, right? But it looks quite C'ish, except for the iostream. Thereore:
*
*use std::vector<int> from #include <vector> (add elements with push_back for example)
*pass it as as a reference, i.e. void heapsort(std::vector<int> &a)
*consider using std::swap( a[i], a[j] ); instead of exch
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: GetValue by reflection i want to get each ToolStripMenuItem of my MDI form's value by looping through them and using reflection as following:
FieldInfo[] menuitems = GetType().GetFields(BindingFlags.GetField |
BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var item in menuitems )
if (item.FieldType.Equals(typeof(ToolStripMenuItem)))
MessageBox.Show(
item.FieldType.GetProperty("Tag").GetValue(item, null).ToString());
but i got "Object does not match target type" error, i am confused and don't know what object to specify as the source object to get value of.
please guide me through...
thank you in advance.
A: This is not a case for reflection.
To get the menuitems, you should first get a reference to your ToolStrip and from there iterate over its Controls collection.
code would then look something like this:
foreach(Control ctrl in _myToolStrip.Controls)
{
MessageBox.Show(ctrl.Tag);
}
A: use something like GetProperty("Tag").GetGetMethod().Invoke (item, null).ToString() .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Automatic Formbuilder for Mongoid 2.0 ? Rails Is there a formbuilder for Mongoid 2.0 ?
Which generates automatically a form from a model.
Thanks
A: Why not just use Rails sacffolding?
A: https://github.com/mcasimir/document_form
gem document_form
It's a fork from https://github.com/justinfrench/formtastic i've made, just moved to Mongoid 2.
Model
class Person
include Mongoid::Document
include Mongoid::MultiParameterAttributes
validates_presence_of :name
field :name
field :secret, :private => true
field :birthday, :type => Date
field :department_number, :type => Integer, :range => 1..10
field :description, :long => true
end
View
<% document_form_for @object do |f| %>
<%= f.inputs %>
<%= f.buttons %>
<% end %>
This is a basic example: here the form builder will render the fields in the same order they are declared, skipping those who have :private => true.
If you are not in a hurry and you want something more flexible you can always specify fields ad options using the same syntax as formtastic, something like this:
<% f.inputs do %>
<%= f.input :title %>
<%= f.input :published, :label => "This post is published" %>
<%= f.input :section_id %>
<%= f.input :image_filename, :hint => "540x300" %>
<% end %>
If you'll decide to give it a try it i will appreciate any sort of feedback.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# custom json serialization This class
class X{
public string a{get;set}
public string b{get;set}
}
is serialized like
{..., inst:{a:"value", b:"value"}, ...}
I need object of my class to be serialized like this:
{..., inst: x, ...}
Where x is a+b
How can I customize JSON serialization process from my class?
A: Checkout Newton-softs JSON serializer. Its pretty sweet.
Have you tried making a and b private, and then have something like
public string x { get { return a + b; } }
A: Try it like this
class X{
public string a{private get;set;}
public string b{private get;set;}
public string x {get{ return a + b; }}
}
Having a private get removes it from serialization but still allows it to be set. The other option is to do it like this.
class X{
public string a{set;}
public string b{set;}
public string x {get{ return a + b; }}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: IEEE 754 Floating Point Add/Rounding I don't understand how I can add in IEEE 754 Floating Point (mainly the "re-alignment" of the exponent)
Also for rounding, how does the Guard, Round & Sticky come into play? How to do rounding in general (base 2 floats that is)
eg. Suppose the qn: Add IEEE 754 Float represented in hex 0x383FFBAD
and 0x3FD0ECCD, then give answers in Round to 0, \$\pm \infty\$,
nearest
So I have
0x383FFBAD 0 | 0111 0000 | 0111 1111 1111 0111 0101 1010
0x3FD0ECCD 0 | 0111 1111 | 1010 0001 1101 1001 1001 1010
Then how should I continue? Feel free to use other examples if you wish
A: If I understood your "re-alignment" of the exponent correctly...
Here's an explanation of how the format relates to the actual value.
1.b(22)b(21)...b(0) * 2e-127 can be interpreted as a binary integer shifted left by e-127 bit positions. Of course, the shift amount can be negative, which is how we get fractions (values between 0 and 1).
In order to add 2 floating-point numbers of the same sign you need to first have their exponent part equal, or, in other words, denormalize one of the addends (the one with the smaller exponent).
The reason is very simple. When you add, for example, 1 thousand and 1 you want to add tens with tens, hundreds with hundreds, etc. So, you have 1.000*103 + 1.000*100 = 1.000*103 + 0.001*103(<--denormalized) = 1.001*103. This can, of course, result in truncation/rounding, if the format cannot represent the result exactly (e.g. if it could only have 2 significant digits, you'd end up with the same 1.0*103 for the sum).
So, just like in the above example with 1000 and 1, you may need to shift to the right one of the addends before adding their mantissas. You need to remember that there's an implict 1. bit in the format, which isn't stored in the float, which you have to account for when shifting and adding. After adding the mantissas, you most likely will run into a mantissa overflow and will have to denormalize again to get rid of the overflow.
That's the basics. There're special cases to consider as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Update table SQLIte in my iPhone App I want to make it able in my app to insert data to sqlite database, and if the id for example is exist so to update this row.
i done the create with :
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
sqlite3_stmt *insertStmt = nil;
if(insertStmt == nil)
{
const char *insertSql = "INSERT INTO Category (id,name) VALUES(?,?)";
if(sqlite3_prepare_v2(database, insertSql, -1, &insertStmt, NULL) != SQLITE_OK)
NSAssert1(0, @"Error while creating insert statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_int(insertStmt, 1, 135);
sqlite3_bind_text(insertStmt, 2, [@"fds" UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(insertStmt))
NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
//NSLog("Inserted");
//Reset the add statement.
sqlite3_reset(insertStmt);
insertStmt = nil;
}
sqlite3_close(database);
A: Use the OR REPLACE qualifier:
INSERT OR REPLACE INTO Category ...
This relies on the existence of a UNIQUE constraint (usually the primary key) containing just the id column.
A: You can use following code for update:
-(void) Update:(NSString *)query {
sqlite3_stmt *statement=nil;
NSString *path = [self GetDatabasePath:DataBaseName] ;
if(sqlite3_open([path UTF8String],&databaseObj) == SQLITE_OK)
{
if(sqlite3_prepare_v2(databaseObj, [query UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
sqlite3_step(statement);
}
sqlite3_finalize(statement);
}
if(sqlite3_close(databaseObj) == SQLITE_OK){
}else{
NSAssert1(0, @"Error: failed to close database on memwarning with message '%s'.", sqlite3_errmsg(databaseObj));
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to find the most popular Foursquare venue in each category in a given city? According to Foursquare API, Venues/Explore returns a list of recommended venues near the current location, Venues/Search returns a list of venues near the current location, optionally matching the search term. So in both cases, the return-list is the collection of venues near the current location. Not the global collection for a given city. In this case, how does 'Plan my next trip' find the most suitable place for each category in a given city? Thanks!
A: You can send a geocodable string (such as the city name) as the near parameter in the Search API, leaving the ll (lat/long) parameter empty. This will search in the entire city and not rank results by distance to a specific point.
From the docs:
near Chicago, IL
required unless ll is provided. A string naming a place in the world.
If the near string is not geocodable, returns a failed_geocode error.
Otherwise, searches within the bounds of the geocode. Adds a geocode
object to the response. (Required for query searches)
A: You can specify the latitude and the longitude using the ll parameter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: execute 2 MySql query using timer in C# How can i execute 2 mysql query using ThreadingTimer?I want 1st timer update data in db and 2nd timer count how much data are updated and also show in label in windows form.Here is my code,
void PrepareTimers(List<int> _dataValues)
{
foreach (int dataValue in _dataValues)
{
timer = new ThreadingTimer (new TimerCallback(TimerAction), dataValue, 0, 2000);
timer1 = new ThreadingTimer(new TimerCallback(TimerAction1), dataValue, 0, 2000);
//Console.WriteLine("Timer " + dataValue + " created.");
}
}
void TimerAction(object flag)
{
//Console.WriteLine("Timer start "+ flag.ToString());
string myconstring = "SERVER=localhost;" + "DATABASE=alicosms;" + "UID=root;" + "PASSWORD=;";
MySqlConnection mycon = new MySqlConnection(myconstring);
string u = "UPDATED";
mycon.Open();
//Console.WriteLine("Timer " + flag.ToString() + " : " + "UPDATE sms_data_bankasia set flag= @flag * 2 , sendingstatus = '" + u + "' WHERE flag = " + flag.ToString() + " LIMIT 1");
MySqlCommand cmd = new MySqlCommand("UPDATE sms_data_bankasia set flag= @flag * 2 , sendingstatus = '" + u + "' WHERE flag = " + flag.ToString() + " LIMIT 1", mycon);
MySqlParameter param = new MySqlParameter();
param.ParameterName = "@flag";
param.Value = flag;
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
mycon.Close();
}
void TimerAction1(object flag)
{
string myconstring = "SERVER=localhost;" + "DATABASE=alicosms;" + "UID=root;" + "PASSWORD=;";
MySqlConnection mycon = new MySqlConnection(myconstring);
string sql = "SELECT count(flag) FROM sms_data_bankasia where sendingstatus='UPDATED' group by flag";
MySqlCommand comd = mycon.CreateCommand();
comd.CommandText = sql;
mycon.Open();
MySqlDataReader dtr = comd.ExecuteReader();
try
{
while (dtr.Read())
{
dict[timer] = label;
dict[timer].Text = dtr[0].ToString() + " program Updated";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
mycon.Close();
}
It provide error,"cross thread operation not valid". What should i do? Any good suggestion?
A: In Windows forms, you cannot do anything in the UI from any other thread than the UI-thread.
Your timer is running your code on a seperate thread.
You could try to use the System.Windows.Forms.Timer instead, as it will marshal the event handling back to the UI thread for you.
A: Here you can read about the solution
Just to test if it fixes your issue try wrapping your MessageBox call in code like this:
public delegate void StringDelegate(string message);
private void ShowMessageBox( string message )
{
if (this.InvokeRequired)
{
this.Invoke( new StringDelegate( ShowMessageBox, new object[] { message } ));
return;
}
MessageBox.Show( message );
}
This is written partly from memory, so it might vary a little.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery - The background is still not changing
Possible Duplicate:
jQuery - Background color not changing
I know I have posted the similar question several times, but it is really confusing me why not working.
This is my latest version of the code:
HTML
<html>
<head>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<style type="text/css">
#name{
background-color: #FFFFF2;
width: 100px;
}
</style>
</head>
<body>
<input type="button" id="bgcolor" value="Change color"/>
<div id="name">
Abder-Rahman
</div>
</body>
</html>
script.js
$("#bgcolor").click(function(){
$("#name").animate(
{backgroundColor: '#8B008B'},
"fast");}
);
I want to notice that I have a folder called: jquery-ui-1.8.16.custom, and this is where I'm putting these files in. And, I have referenced jquery-1.6.4,js as shown above which I also have it in the same folder, in addition to referencing jquery-ui-1.8.16.custom.min.js which is in the js folder in the current folder.
What am I getting wrong here? Isn't this the way to reference jQuery and jQueryUI?
EDIT
Browser used: Mozilla Firefox 6.0.2
Folder structure:
jquery-ui-1.8.16.custom/abc.html
jquery-ui-1.8.16.custom/script.js
jquery-ui-1.8.16.custom/jquery-1.6.4.js
jquery-ui-1.8.16.custom/js/jquery-ui-1.8.16.custom.min.js
Thanks.
A: Did you put it in the window or document onload function? Is this page in the same folder as your scripts?
$(document).ready(function(){
$("#bgcolor").click(function(){
$("#name").animate(
{backgroundColor: '#8B008B'},
"fast");}
);
});
A: You probably somehow fail to include jQueryUI as that is where colour animation comes from. Is your jquery-ui-1.8.16.custom.min.js inside of a folder called js? You should also include your folder structure into this question as it's unclear what's wrong otherwise. Also you might want to look into the developer console of your browser if there is such a thing there (it might tell you of files failed to load or syntax errors you have). You also should mention what browser you're on to make it easier to help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How can I make Eclipse/FDT build Main.as instead of the currently selected file? I'm using FDT, and I want Eclipse to build my Main.as file instead of the currently selected file when I click debug/run. Is there a way to do this?
A: It depends on your settings and the order you've done things...
If you right click on a file and choose 'Run As' or 'Debug As', FDT (Eclipse) will use that file to build your application around.
If you have 'Always launch the previously launched application' enabled (it should be enabled by default) then FDT will always use the last used launch configuration whenever the Run / Debug button is clicked. If none exists then it will run using the currently active file. To enable this setting, go to Preferences > Run/Debug > Launching and look at the bottom where Launch Operations is.
If you have a launch configuration already created, and it sounds like you do, you'll need to adjust the 'Main' file within that launch configuration. Do this by choosing 'Run Configurations...' via the Run button drop down.
I've written a tutorial about this. It should help you get through it.
http://fdt.powerflasher.com/docs/Launch_Configuration_Tutorial
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mac OS X Hot Corners: run a custom AppleScript? Is there a way to run a custom AppleScript or any other custom application using the "Hot Corners" of Mac OS X?
The default system settings list a number of actions (e.g. Launchpad, Mission Control, Desktop, etc.), but nothing that would allow me to launch a custom app. Maybe there's a way to "redirect" one of those to do just that?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: MySQL optimize subqueries I want to optimize this query (since subqueries aren't fast in general), but I'm lost because I cannot rewrite this using joins which will be better for performance, can you help mi with this?
SELECT id, company, street, number, number_addition, postalcode, telephone
FROM clients
WHERE (postalcode BETWEEN '1000' AND '9000') AND street = (
SELECT DISTINCT street FROM clients WHERE (postalcode BETWEEN '1000' AND '9000') AND postalcode <= (
SELECT MIN(postalcode) FROM clients WHERE street = 'Main Street' AND (postalcode BETWEEN '1000' AND '9000'))
ORDER BY postalcode DESC LIMIT 1, 1)
ORDER BY postalcode DESC, street DESC, number DESC, number_addition DESC, telephone DESC
LIMIT 1
Thanks for your time guys.
A: SELECT DISTINCT street ORDER BY postalcode doesn't make sense (and I think isn't valid ANSI SQL), unless postalcode is functionally-dependent on street—which I don't think it is, as your get-lowest-postalcode-on-Main-Street inner subselect wouldn't make sense if it was. MySQL will let you get away with it but the results will be inconsistent. What are you trying to say here?
I don't think this should be particularly slow since what you have isn't a dependent subquery; the subqueries are executed only once and not repeatedly for each outer row. You could rewrite it as three separate queries—
*
*get lowest postalcode on Main Street;
*get street with second-highest postal code lower than (1) (inconsistently);
*get details of clients on street (2).
with no difference in execution. (Indeed, it might be better to do so for clarity.)
You could rewrite these as joins, using self-left-joins-on-less-than-is-null to get the minima/maxima, but I don't think you'd gain anything by it for this example and it would get very messy given the two levels of joining and the second-highest requirement. Is this query particularly slow in practice? What does the EXPLAIN look like? Have you indexed postalcode and street?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: get device flags by device name hope you can help me:
I'm trying to determine whether the device is removable or not, all i have is device name (/dev/sdc). Actually, I need to determine when the file on removable media or on local disk by full path of this file.
I've tryed to search in the
current->fs->pwd
and all I could find is a set of flags here:
*current->fs->pwd.mnt->mnt_sb->s_bdev->bd_disk->flags*
where GENHD_FL_REMOVABLE set for removable devices
But i always get the same flags set (as i understand, s_bdev always points to the same device (/dev/sda)).
So now i get the device name (/dev/sdc) that contains my file by parsing mtab, but still can't find out, removable it or not.
Is there possible way to get block_device structure by device name?
(for example, "file" structure may be obtained by calling
fd = open("name")
fl = fged(fd)
where fl points to "file" structure)
A: You can iterate over block devices using class_dev_iter_init and class_dev_iter_next. See the code in block/genhd.c blk_lookup_devt for usage.
Once you have the device, you can use dev_to_disk to get a struct gendisk *, in which you can check the removable flag.
A: Read /sys/block/dev-name/removable as it should contain 1 if the device is removable or 0 if not. (dev-name = the device's name: sda, hda, fd0, ...)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How do I insert a value for an element of an array that is pointed by a pointer in a struct I currently have a struct that contains a pointer to an array of pointers. I am trying to give a value to an element in the array of pointers, but I get a segmentation fault.
aStruct->anArray[0]->string = test;
aStruct contains a char** anArray and char *string.
char *test = "test".
When I try to do what I did, I get a segmentation fault. Is that command not valid?
struct aStruct
{
char **anArray;
};
I used calloc to make an array of size 10.
A:
aStruct->anArray[0]->string = test;
aStruct contains a char** anArray and char *string. char *test =
"test".
Is that command not valid?
Certainly not. aStruct->anArray[0] would be char* and wouldn't have a member ->string.
Other than that, if it really compiles and you only posted the wrong code, you wouldn't get a segmentation fault if anArray was properly allocated and had the right size. So you need something like this in your program:
aStruct->anArray = malloc(size * sizeof(*aStruct->anArray));
where size is at least one for your case, but generally the number of elements you ever need to access.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ajax, PHP and Security? My question is that suppose, in my web app, I use ajax to call upon methods on the server side, isn't it creating a security hole in the app? Like, say I have an option for the user to deactivate the account, which can be done by clicking a button. This is done via Ajax.
So, can't a hacker send a request to the server to deactivate the account instead of the user?
HELP!!!
A:
My question is that suppose, in my web app, I use ajax to call upon methods on the server side, isn't it creating a security hole in the app?
From a security perspective, there is no difference between an HTTP request that involves JavaScript and one which doesn't (e.g. that uses a regular form, or is handcrafted).
… but you can't call methods from the client, you can only make requests to URIs. The server might cause a method to be called based on receiving a request to a specific URI.
So, can't a hacker send a request to the server to deactivate the account instead of the user?
They could, which is why you need (trustworthy) authentication / authorisation and CSRF protection (just like you would for a request to disable an account that didn't involve Ajax).
A: This is not a problem with AJAX alone, but with any arbitrary HTTP request that wants to authenticate/maintain a session. The user needs to be authenticated in some way in order to make requests, this is usually done with cookies. Using AJAX does not make the matter any worse though because it is still a HTTP request.
Authentication alone is not enough though, someone could always be listening on the wire and capture the authentication cookie, and thus get hold of the session - "become you". The only solution here is to encrypt the connection on a lower OSI layer level (using SSL/TLS). This is why you should always use SSL when it comes to authentication.
A: This Ruby on Rails security guide has a great explanation on how to deal with AJAX requests that could be potentially exploited. It's not specific to RoR so the concepts can apply to any platform.
One way to reduce the risk of cross site requests is to use POST for actions that modify or delete data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Converting R.java variable to URI Is this possible converting R.java variable to URI reference?
What can be URI?
PS: So silly question I know. But thanks for your kind helps..
A: Do you mean that you're storing URIs as string values in an xml file, and need to convert those into java.net.URI objects?
If so...
In an xml file called uris.xml
<resources>
<string name="stackoverflow">http://www.stackoverflow.com</string>
</resources>
And then in your Java code you can use
import java.net.URI;
URI stackoverflowUri = new URI(getResources().getString(R.uri.stackoverflow));
(you'll need to add code to catch any URISyntaxException thrown by the new URI call)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java function for int[], float[] or double[] array I want to write a Java function that will get as input either int[], float[] or double[]. The algorithm is exactly the same (some kind of a scalar product). How can I write a single function that will be able to handle all types of numeric arrays?
A: There is no easy way to handle this in Java. You can:
*
*Use Wrapper types (Integer[], Float[], Double[]) and have a function taking Number[] as an argument. Works since arrays are covariant in Java:
public static void main(String[] args) {
f(new Integer[]{1,2,3});
f(new Float[]{1,2,3});
f(new Double[]{1,2,3});
}
private static void f(Number[] numbers) {
f[0].doubleValue();
}
Note that this approach increases memory consumption significantly.
*
*Convert int[] and float[] arrays to double[] and work with doubles all along. Preferably create overloaded versions of your method where the ones taking int[] and float[] are only doing the conversion and delegate to actual double[] implementation.
*I believe Scala can handle this seamlessly as Java primitive types are semantically objects in Scala.
A: You cannot code this in Java without either:
*
*coding each case separately or,
*using reflection for all operations on the array ... which is likely to be messy, fragile and an order of magnitude slower than an optimal solution.
The only common supertype of int[] float[] and double[] is Object, so there is no possibility of a solution using polymorphism over those types. Likewise, generics require that the type parameter is a reference type, and int, float and double are not reference types.
You either need to accept that you will have duplicate code, or change the representation type for the arrays; e.g. use Integer[] / Float[] / Double[] or Number[].
A: You can write one method to do them all, however, it won't be anywhere near as readable of efficient. You have to make a choice between what is a generic or an efficient solution.
public static void main(String... args) throws IOException {
int[] nums = new int[10*1000 * 1000];
{
long start = System.nanoTime();
product2(nums);
long time = System.nanoTime() - start;
System.out.printf("Took %.3f seconds to take the product of %,d ints using an int[].%n", time / 1e9, nums.length);
}
{
long start = System.nanoTime();
product(nums);
long time = System.nanoTime() - start;
System.out.printf("Took %.3f seconds to take the product of %,d ints using reflections.%n", time / 1e9, nums.length);
}
}
public static double product(Object array) {
double product = 1;
for (int i = 0, n = Array.getLength(array); i < n; i++)
product *= ((Number) Array.get(array, i)).doubleValue();
return product;
}
public static double product2(int... nums) {
double product = 1;
for (int i = 0, n = nums.length; i < n; i++)
product *= nums[i];
return product;
}
prints
Took 0.016 seconds to take the product of 10,000,000 ints using an int[].
Took 0.849 seconds to take the product of 10,000,000 ints using reflections.
If you are only working on relatively small arrays, the generic but less efficient solution may be fast enough.
A: I see two options:
1) You can create a new class which allows int[], float[], double[] in the contructor and saves them.
2) You allow Object[] and check for int / float / double. (You have to convert them first)
A: Use java.lang.Number type or Object parameter type.
For more info read Bounded Type Parameters
A: class ArrayMath {
private ArrayMath() {
}
public static <T extends Number> double ScalarProduct(T[] a, T[] b){
double sum = 0;
for(int i=0;i<a.length;++i){
sum += a[i].doubleValue()*b[i].doubleValue();
}
return sum;
}
}
class Sample {
public static void main(String arg[]){
Integer[] v1 = { 1, -10, 3, 9, 7, 99, -25 };
Integer[] v2 = { 1, -10, 3, 9, 7, 99, -25 };
double p_int = ArrayMath.ScalarProduct(v1, v2);
Double[] v1_d = { 1.1, -10.5, 3.7, 9.98, 7.4, 9.9, -2.5 };
Double[] v2_d = { 1.1, -10.5, 3.7, 9.98, 7.4, 9.9, -2.5 };
Double p_double = ArrayMath.ScalarProduct(v1_d, v2_d);
System.out.println("p_int:" + p_int);
System.out.println("p_double:" + p_double);
}
}
A: Hope this will help you.. I have tested this code and it does what you have asked for, how to implement this logic is upto you !
public class MultiDataType {
public static void main(String[] args) {
int[] i = new int[2];
float[] f = new float[2];
double[] d = new double[2];
String str = new String();
handlingFunction(i);
handlingFunction(f);
handlingFunction(d);
handlingFunction(str);
}
public static void handlingFunction(Object o) {
String classType = null;
if (o.getClass().getCanonicalName().equals("int[]")) {
classType = "int[]";// Your handling code goes here
} else if (o.getClass().getCanonicalName().equals("float[]")) {
classType = "float[]";// Your handling code goes here
} else if (o.getClass().getCanonicalName().equals("double[]")) {
classType = "double[]";// Your handling code goes here
}else classType = o.getClass().getCanonicalName();
System.out.println("Object belongs to " + classType);
}
}
OUTPUT
Object belongs to int[]
Object belongs to float[]
Object belongs to double[]
Object belongs to java.lang.String
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Can't read an XML file with simplexml_load_string I have been trying to read the xml file, but it is giving me a strange error.
My XML is as follows
<?xml version='1.0' encoding='UTF-8'?>
<response>
<url>http://xyz.com</url>
<token>xxxxxxx<token>
</response>
To read this I am using
simplexml_load_string(variable containing xml goes here)
but it is giving me this error
Warning: simplexml_load_string() [function.simplexml-load-string]:
Entity: line 1: parser error : Start tag expected, '<' not found in
on line 47
Warning: simplexml_load_string() [function.simplexml-load-string]: 1
in on line 47
Warning: simplexml_load_string() [function.simplexml-load-string]: ^
in on line 47
A: Thanx all for the attention and replies,
But the problem lied somewhere else
In my curl request the i had not set CURLOPT_RETURNTRANSFER to true and that was causing the XML not to be recorded in the variable and was somehow was getting printed on the screen giving the illusion that it is coming from the variable but it was not.
However i set CURLOPT_RETURNTRANSFER to 1 and it is giving me correct results now.
Sorry for the silly mistake.
and thanx all.
A: The response you get from the API is not well-formed/valid XML:
<token>xxxxxxx<token>
^ missing /
As this is an API response you need to fix it prior simplexml can actually read it in. You can make use of the tidy extension Docs to solve this:
$config = Array(
'input-xml' => 1,
);
$xml = tidy_repair_string($xml, $config);
$xmlObj = simplexml_load_string($xml);
$doc = dom_import_simplexml($xmlObj)->ownerDocument;
$xpath = new DOMXpath($doc);
foreach($xpath->query('//token[not(node())]') as $node)
{
$node->parentNode->removeChild($node);
}
echo $xmlObj->asXML();
This will produce the following XML by first fixing unclosed tags and then removing empty token elements:
<?xml version="1.0" encoding="utf-8"?>
<response>
<url>http://xyz.com</url>
<token>xxxxxxx
</token>
</response>
Related:
*
*PHP SimpleXML - Remove xpath node
A: As you rightly pointed out, CURLOPT_RETURNTRANSFER set to 1 is very important!
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $postUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0 ); // set to 1 for debugging
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return from sms server
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android NDK build script ignoring main makefile I've got Application.mk file which is ignored by ndk-build for some reason.
What i've got in it:
APP_PROJECT_PATH := $(call my-dir)
APP_CPPFLAGS += -frtti
APP_CPPFLAGS += -fexceptions
APP_OPTIM := debug
APP_STL := gnustl_static
And flags on build is still:
-fno-exceptions -fno-rtti
And no gnustl includes.
What can be the problem?
A: Make sure the Application.mk is inside the jni folder, alongside the Android.mk.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Utility of managed=False option in Django models In django models we have option named managed which can be set True or False
According to documentation the only difference this option makes is whether table will be managed by django or not. Is management by django or by us makes any difference?
Is there any pros and cons of using one option rather than other?
I mean why would we opt for managed=False? Will it give some extra control or power which affects my code?
A: The main reason for using managed=False is if your model is backed by something like a database view, instead of a table - so you don't want Django to issue CREATE TABLE commands when you run syncdb.
A: Right from Django docs:
managed=False is useful if the model represents an existing table or a database view that has been created by some other means. This is the only difference when managed=False. All other aspects of model handling are exactly the same as normal
A: When ever we create the django model, the managed=True implicitly is
true by default. As we know that when we run python manage.py makemigrations the migration file(which we can say a db view) is
created in migration folder of the app and to apply that migration i.e
creates the table in db or we can say schema.
So by managed=False, we restrict Django to create table(scheme, update
the schema of the table) of that model or its fields specified in
migration file.
Why we use its?
case1: Sometime we use two db for the project for
example we have db1(default) and db2, so we don't want particular
model to be create the schema or table in db1 so we can this or we can
customize the db view.
case2. In django ORM, the db table is tied to django ORM model, It
help tie a database view to bind with a django ORM model.
Can also go through the link:
We can add our raw sql for db view in migration file.
The raw sql in migration look like: In 0001_initial.py
from future import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.RunSQL(
CREATE OR REPLACE VIEW app_test AS
SELECT row_number() OVER () as id,
ci.user_id,
ci.company_id,
),
]
Above code is just for overview of the looking of the migration file, can go through above link for brief.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Jenkins Error: 'Unable to Delete File' When Invoking Ant I'm running Jenkins 1.433 on Ubuntu 11.04 in order to perform a build which includes an Ant task. The clean portion of my Ant task, which deletes the build directory from prior builds, will work when running sudo Ant from the terminal, but fails from Jenkins with the following:
BUILD FAILED
/var/lib/jenkins/workspace/AomaTests/build.xml:47: Unable to delete directory /var/lib/jenkins/workspace/AomaTests/build
The Ant install referenced by Jenkins is the one which works from the command line (usr/bin/ant), and the Jenkins project specifically points to this instance (and not to Default). Figuring this was a permissions problem, I tried the following:
*
*chown -R the appropriate build directory, setting its owner to jenkins.
*Doing a chmod 777 on the directory.
*Temporarily allowing the jenkins username the ability to run things without a pasword (via editing the sudoers file with the line jenkins ALL = NOPASSWD:ALL).
None of these approaches workd. Should I be running ant via a different user, or perhaps passing it some properties via Jenkins?
Update: The output of ps -ef | grep "jenkins" is:
jenkins 1647 1 0 12:28 ? 00:00:00 /usr/bin/daemon --name=jenkins --inherit --env=JENKINS_HOME=/var/lib/jenkins --output=/var/log/jenkins/jenkins.log --pidfile=/var/run/jenkins/jenkins.pid -- /usr/bin/java -jar /usr/share/jenkins/jenkins.war --webroot=/var/run/jenkins/war --httpPort=8080 --ajp13Port=-1
jenkins 1660 1647 7 12:28 ? 00:00:13 /usr/bin/java -jar /usr/share/jenkins/jenkins.war --webroot=/var/run/jenkins/war --httpPort=8080 --ajp13Port=-1
mattcarp 2393 2229 0 12:31 pts/0 00:00:00 grep --color=auto jenkins
Running ls -l on the directory that fails to be deleted (when run from Jenkins) shows:
drwxr-xr-x 2 jenkins root 4096 2011-10-03 14:49 build
Many thanks for any advice!
A: As it turns out, all that was required was to set the parent directory's owner to jenkins.
Wow - that was a long way to go for such a simple answer!
A: Who is running Jenkins? That's the question. There is some user that's running the Java process that's running the Jenkins server. You need to find that user. Try this:
$ ps -ef | grep "jenkins"
and see what you get.
Knowing that your name is Matt and I see that the file that can't be deleted is in the /home/mattcarp directory, something tells me there's something screwy going on. My first guess is that Jenkins is not being executed by the user mattcarp.
*
*How is Jenkins installed? Is it installed as its own user in its own directory? That's usually how it is done. For example, you install Jenkins in /home/jenkins, and all the jobs are in /home/jenkins/jobs, and the workspace for a for job foo is in /home/jenkins/jobs/foo/workspace. Why is Jenkins looking at your $HOME directory?
*How does your Ant build.xml file work? Are you hard coding the directory /home/mattcarp/workspace/... in the build.xml file? If you are, you need to redo your build.xml to use its current directory tree and not hard code it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Custom DataGrid Silverlight I'm writing custom DataGrid control. I have one collection of column headers and other collection of rows, which has collection of cells itself. I want all the cells in the column be the same width (the width of the widest cell). How can i do it?
Solution:
Every cell knows the column which keep it. In cell's OnApplyTemplate i use Measure and assign the maximum between column's and cell's width to the colunm. When the whole DataGrid is loaded, i iterate through the cells of each row and assign the width of the column to each cell.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jasmine and node.js Have some Jasmine+Rhino combo to test the javascript code and trying to shift to node.js. However, couldn't find any setup instructions on the net (but only this link, with nearly zero instructions). Any help on how to make it true (on Ubuntu) will be highly appreciated.
A: I thought the same thing (regarding documentation) when I first tried to use jasmine-node. As it turns out, though, there's virtually nothing to set up--it works just like RSpec or other testing tools you might be used to. To use Jasmine with your Node project, do the following:
*
*Make sure jasmine-node is installed and that you can run its executable.
*Write your specs! I have a sample spec below these steps.
*Run your specs with the command jasmine-node specs/ (where specs/ points to the directory with your specs).
That's it! You may find it beneficial to use some sort of build tool, like cake for CoffeeScript or jake.
Here's a quick example of part of a spec from a small project I used jasmine-node on recently; apologies that it's in CoffeeScript. (As an aside: to run jasmine-node against CoffeeScript specs, pass it the --coffee option.)
Chess = require('../lib/chess')
Board = Chess.Board
jasmine = require('jasmine-node')
describe "A chess board", ->
beforeEach ->
@board = new Board
it "should convert a letter/number position into an array index", ->
expect(Board.squares["a1"]).toEqual(0)
expect(Board.squares["b1"]).toEqual(1)
expect(Board.squares["a2"]).toEqual(16)
expect(Board.squares["h8"]).toEqual(119)
it "should know if an array index represents a valid square", ->
expect(Board.is_valid_square 0).toBeTruthy()
expect(Board.is_valid_square 7).toBeTruthy()
expect(Board.is_valid_square 8).toBeFalsy()
expect(Board.is_valid_square 15).toBeFalsy()
expect(Board.is_valid_square 119).toBeTruthy()
expect(Board.is_valid_square 120).toBeFalsy()
expect(Board.is_valid_square 129).toBeFalsy()
expect(Board.is_valid_square -1).toBeFalsy()
it "should start off clear", ->
for i in [0..127]
if Board.is_valid_square(i)
expect(@board.piece_on(i)).toBeNull()
describe "#place_piece", ->
it "should place a piece on the board", ->
piece = jasmine.createSpy("piece")
@board.place_piece "a1", piece
expect(@board.piece_on "a1").toEqual(piece)
it "should set the piece's location to the given square's index", ->
piece = jasmine.createSpyObj(Piece, ["position"])
@board.place_piece "b5", piece
expect(piece.position).toEqual(65)
[Edit]
You can also add a spec_helper file (with the appropriate extension for your project) at the root of your specs/ directory. Here's the contents of mine, which adds a new matcher to Jasmine:
jasmine = require('jasmine-node')
beforeEach ->
this.addMatchers
toInclude: (should_include) ->
for value in @actual
return true if value == should_include
false
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: GWT 2.4.0 RequestFactory polymorphism Does GWT 2.4 support this case:
@Entity class MyBase {...}
@Entity class MyChild1 extends MyBase {...}
@Entity class MyChild2 extends MyBase {...}
...
@ProxyFor(MyBase.class) class MyBaseProxy extends EntityProxy {...}
@ProxyFor(MyChild1.class) class MyChild1Proxy extends MyBaseProxy {...}
@ProxyFor(MyChild2.class) class MyChild2Proxy extends MyBaseProxy {...}
...
@Service(ArticleBase.class)
public interface MyBaseRequest extends RequestContext {
Request<MyBaseProxy> getStuff(); // MyChild1 here
}
...
Request<MyBaseProxy> getStuffRequest = request.getStuff();
getStuffRequest.fire(new Receiver<MyBaseProxy>() {
@Override
public void onSuccess(MyBaseProxy proxy) {
button.setText(((MyChild1Proxy)proxy).getQwerty()); // HERE!
}
});
?
The problem is, I can't make it work. It's either not supported yet or I need to add some magic annotation somewhere. Everything works fine when I use concrete types, but it doesn't work if I use the base ones.
What do you think?
A: Fixed it with @ExtraTypes:
@Service(ArticleBase.class)
@ExtraTypes({MyChild1Proxy.class, MyChild2Proxy.class})
public interface MyBaseRequest extends RequestContext {
Request<MyBaseProxy> getStuff(); // MyChild1 here
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Ruby simple regex syntax error I'm new to Ruby and i'm working on a code for a server.
The code is a half year old. In the meanwhile Chrome updated versions to version 14.
So here is my code:
supported_browsers = /Chrome\/[3-9]|Firefox\/[3-9]|\sMSIE\s|Konqueror\/[4-9]|Midori|Minefield|Shiretoko|IceCat|Opera\/9.|\sAppleWebKit/
As you can see Chrome 3-9 but now when i try to change it to:
supported_browsers = /Chrome\/[3-15]|Firefox\/[3-9]|\sMSIE\s|Konqueror\/[4-9]|Midori|Minefield|Shiretoko|IceCat|Opera\/9.|\sAppleWebKit/
I get a syntax error. Help me figure out what's wrong.
A: Your error is here : [3-15] this is a character class with range of char from 3 to 1 that is not allowed.
I guees you want : [3-9]|1[0-5] that means 3 to 9 or 10 to 15
The complete regex is:
supported_browsers = /Chrome\/([3-9]|1[0-5])|Firefox\/[3-9]|\sMSIE\s|Konqueror\/[4-9]|Midori|Minefield|Shiretoko|IceCat|Opera\/9.|\sAppleWebKit/
A: [3-9] is a numeric range. It means a single digit between 3 or 9. Numeric ranges doesn't work in the way you expect: [3-15] is not a valid range.
If you simply want to match a digit range you can use [0-9]{1,2}. It matches everything between 0 and 99. Or [0-9]+ to make it less restrictive.
supported_browsers = /Chrome\/[0-9]+|Firefox\/[3-9]|\sMSIE\s|Konqueror\/[4-9]|Midori|Minefield|Shiretoko|IceCat|Opera\/9.|\sAppleWebKit/
If you really want to validate the inclusion in the range 3-15, using regular expressions is not really the best choice. In fact, using regular expression your range should be [3-9]|1[0-5] and the more restrictive you want to be, the more complicated the regexp becomes.
supported_browsers = /Chrome\/(?:[3-9]|1[0-5])|Firefox\/[3-9]|\sMSIE\s|Konqueror\/[4- 9]|Midori|Minefield|Shiretoko|IceCat|Opera\/9.|\sAppleWebKit/
A: [3-15] does not check the range. for range you have to use [3-9]|1[0-4] would match 1-14
e.g.
supported_browsers = /Chrome\/([3-9]|1[0-4])|Firefox\/[3-9]|\sMSIE\s|Konqueror\/[4-9]|Midori|Minefield|Shiretoko|IceCat|Opera\/9.|\sAppleWebKit/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dynamically updating a plot in Haskell I have a program which performs a long-going calculation where the result is shown as a plot.
I am currently using Chart-0.14 for this. I want to show the partial results, and update during calculations.
Graphics.Rendering.Chart.Gtk.updateCanvas :: Renderable a -> DrawingArea -> IO Bool seems to do that, but I do not find any way to get a DrawingArea from the plot. The function renderableToWindow :: Renderable a -> Int -> Int -> IO () does not return anything (and furthermore it does not return before the window is closed).
I would like to do something like the following:
main = do
drawingArea = forkRenderableToWindow (toRenderable $ plotLayout $
plot [0,0.1..10] sin "sin(x)") 640 480
updateCanvas (toRenderable $ plotLayout $ plot [0,0.1..10] sin "sin(x)") drawingArea
How should I do this? Would I need to reimplement the functions in Graphics.Rendering.Chart.Gtk with a version that returns the DrawingArea and in some way (how would I do this? forkIO?) returns immediately without closing the window?
A: You are looking for createRenderableWindow and then you need to use the GTK operations to work on the given Window - I don't think the Chart package exports any higher level operations on Windows.
EDIT2: So ignore the below - it doesn't work even with GUI initilization. My comment was a guess based on types.
EDIT:
Here is some example code. Understand, I'm just piecing things together based on the types. There might be better ways to do things if you ask someone who actually knows the library.
Below we use:
*
*createRenderableWindow - this was the crux of my answer
*castToDrawingArea - This is needed to get a DrawingArea from the Window type provided by GTK. These casts are taking place of C++ OO inheritance, I think.
*widgetShowAll - because we haven't actually displayed the window, we best do that. I stole this function after looking at the source for renderableToWindow.
*updateCanvas - I just saw this in the haddock documentation and figured it is why you wanted a DrawingArea in the first place.
Now for the code:
import Graphics.Rendering.Chart.Gtk
import Graphics.Rendering.Chart.Renderable
import Graphics.UI.Gtk.Misc.DrawingArea
import qualified Graphics.UI.Gtk as G
main = do
win <- createRenderableWindow emptyRenderable 400 400
let draw = castToDrawingArea win
G.widgetShowAll win
updateCanvas emptyRenderable draw
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Function to tell the user about errors wont reveal error div I have this function to validate an input field. When something is wrong it should write stuff into a div element (which it does!) and then reveal it through jQuerys $('#elementID').show('speed');.
I recently changed from checking if there was an error to checking how high the errorlevel is, solving a problem with a more complex error-reporting system.
The function looks like this:
function verifyKassaAle() {
var TOS_K_alevalue = $('#TOS_K_ale').val();
if (!(TOS_K_alevalue == "")) {
if (TOS_K_alevalue <= 100) {
if (TOS_K_alevalue > 0) {
if (TOS_K_alevalue > 2) {
var a = confirm("Kassa ale on enemmän kuin 2%, onko tämä OK?");
if (a == true) {
if(errorlevel > 0) {
errorlevel = errorlevel - 1;
}
else if(errorlevel == 0) {
errorlevel = 0;
}
} else {
if(errorlevel > 0) {
errorlevel = errorlevel - 1;
}
else if(errorlevel == 0) {
errorlevel = 0;
}
showinfo = showinfo + 1;
info = "Kassa ale on yli 2%"
}
} else {
if(errorlevel > 0) {
errorlevel = errorlevel - 1;
}
else if(errorlevel == 0) {
errorlevel = 0;
}
}
} else {
errorlevel = errorlevel + 1;
Errormsg = "Kassa ale on alle 0%";
}
} else {
errorlevel = errorlevel + 1;
Errormsg = "Kassa ale on yli 100%";
}
} else {
errorlevel = errorlevel + 1;
Errormsg = "Kassa ale on tyhjä!";
}
if(errorlevel == 0) {
$('#errormsg').html('');
$('#error').hide('fast');
$('#TOS_K_ale_valid').html('<td><div class="ui-state-default ui-corner-all" title="Valid!" style="margin-bottom:-5px;"><span class="ui-icon ui-icon-check"></span></div></td>');
} else {
$('#errormsg').html(Errormsg);
$('#error').show('fast');
$('#TOS_K_ale_valid').html('<td><div class="ui-state-default ui-corner-all" title="Not valid!" style="margin-bottom:-5px;"><span class="ui-icon ui-icon-alert"></span></div></td>');
}
if(showinfo > 0) {
$('#infotext_kale').html(info);
$('#info').show('fast');
} else {
$('#infotext_kale').html('');
$('#info').hide('fast');
}
$('#TOS_K_ale_valid').show('slow');
}
And the error/info divs look like this:
<div id="error" style="margin-top:5px;display:none;">
<div class="ui-state-error ui-corner-all" style="padding:0.7em;font-size:13px;">
<span class="ui-state-error-text">
<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;margin-bottom:-5px;"></span>
</span>
<strong>VIKA: </strong>
<span id="errormsg"></span>
</div>
</div>
<div id="info" style="margin-top:5px;display:none;">
<div class="ui-state-highlight ui-corner-all" style="padding:0.7em;font-size:13px;">
<span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;margin-bottom:-5px;"></span>
<strong>Huom: </strong>
<span id="infotext"></span>
</div>
</div>
SO, I can call $('#error').show('fast') from firebugs' console BEFORE this function has been called and it shows the div nicely. However, after I have called the function everything gets all ft up.
I have spent many hours to get this working without success.
Regards,
Akke
A: You have this jQuery selector $('#TOS_K_ale_valid') and there is no element with id="TOS_K_ale_valid" in html.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use mysql spatial with prepared statements I've got two scenarios, using the following statement:
INSERT INTO areas (name, polygon) VALUES (?, POLYGON(?,?,?,?,?,?))
Will result in errors like this:
Illegal non geometric ''58.03665463092348 14.974815566795314'' value found during parsing
What seems to be the problem here is that my lat and longitudes are quoted as texts within the POLYGON().
However,according to the WKT format I need another set of () in my statement:
INSERT INTO areas (name, polygon) VALUES (?, POLYGON((?,?,?,?,?,?)))
which will only result in the following error:
Operand should contain 1 column(s)
I'm at a loss here, how do I use prepared statements along with mysql spatial information?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Fixed GridView Header with horizontal and vertical scrolling in asp.net I want to fix(Freeze) gridview header while vertical scrolling.
I also want to fix first column while horizontal scrolling.
I want this in both chrome and IE.
A: It is possible to apply the specific GridView / Table layout via custom CSS rules (as it was discussed in the <table><tbody> scrollable? thread) to fix GridView's Header. However, this approach will not work in all browsers. The 3-rd ASP.NET GridView controls (such as the ASPxGridView from DevExpress component vendor provide this functionality.
Check also the following CodeProject solutions:
*
*Fixed header Grid
*Gridview with fixed header
*Gridview Fixed Header
A: I was looking for a solution for this for a long time and found most of the answers are not working or not suitable for my situation i also find most of the java script code for that they worked but only with the vertical scroll not with the horizontal scroll and also combination of header and rows doesn't match.
Finally i have found a solution with javascript here is the link bellow :-
scrollable horizontal and vertical grid view with fixed headers
A: You can try overflow css property.
A: // create this Js and add reference
var GridViewScrollOptions = /** @class */ (function () {
function GridViewScrollOptions() {
}
return GridViewScrollOptions;
}());
var GridViewScroll = /** @class */ (function ()
{
function GridViewScroll(options) {
this._initialized = false;
if (options.elementID == null)
options.elementID = "";
if (options.width == null)
options.width = "700";
if (options.height == null)
options.height = "350";
if (options.freezeColumnCssClass == null)
options.freezeColumnCssClass = "";
if (options.freezeFooterCssClass == null)
options.freezeFooterCssClass = "";
if (options.freezeHeaderRowCount == null)
options.freezeHeaderRowCount = 1;
if (options.freezeColumnCount == null)
options.freezeColumnCount = 1;
this.initializeOptions(options);
}
GridViewScroll.prototype.initializeOptions = function (options) {
this.GridID = options.elementID;
this.GridWidth = options.width;
this.GridHeight = options.height;
this.FreezeColumn = options.freezeColumn;
this.FreezeFooter = options.freezeFooter;
this.FreezeColumnCssClass = options.freezeColumnCssClass;
this.FreezeFooterCssClass = options.freezeFooterCssClass;
this.FreezeHeaderRowCount = options.freezeHeaderRowCount;
this.FreezeColumnCount = options.freezeColumnCount;
};
GridViewScroll.prototype.enhance = function ()
{
this.FreezeCellWidths = [];
this.IsVerticalScrollbarEnabled = false;
this.IsHorizontalScrollbarEnabled = false;
if (this.GridID == null || this.GridID == "")
{
return;
}
this.ContentGrid = document.getElementById(this.GridID);
if (this.ContentGrid == null) {
return;
}
if (this.ContentGrid.rows.length < 2) {
return;
}
if (this._initialized) {
this.undo();
}
this._initialized = true;
this.Parent = this.ContentGrid.parentNode;
this.ContentGrid.style.display = "none";
if (typeof this.GridWidth == 'string' && this.GridWidth.indexOf("%") > -1) {
var percentage = parseInt(this.GridWidth);
this.Width = this.Parent.offsetWidth * percentage / 100;
}
else {
this.Width = parseInt(this.GridWidth);
}
if (typeof this.GridHeight == 'string' && this.GridHeight.indexOf("%") > -1) {
var percentage = parseInt(this.GridHeight);
this.Height = this.Parent.offsetHeight * percentage / 100;
}
else {
this.Height = parseInt(this.GridHeight);
}
this.ContentGrid.style.display = "";
this.ContentGridHeaderRows = this.getGridHeaderRows();
this.ContentGridItemRow = this.ContentGrid.rows.item(this.FreezeHeaderRowCount);
var footerIndex = this.ContentGrid.rows.length - 1;
this.ContentGridFooterRow = this.ContentGrid.rows.item(footerIndex);
this.Content = document.createElement('div');
this.Content.id = this.GridID + "_Content";
this.Content.style.position = "relative";
this.Content = this.Parent.insertBefore(this.Content, this.ContentGrid);
this.ContentFixed = document.createElement('div');
this.ContentFixed.id = this.GridID + "_Content_Fixed";
this.ContentFixed.style.overflow = "auto";
this.ContentFixed = this.Content.appendChild(this.ContentFixed);
this.ContentGrid = this.ContentFixed.appendChild(this.ContentGrid);
this.ContentFixed.style.width = String(this.Width) + "px";
if (this.ContentGrid.offsetWidth > this.Width) {
this.IsHorizontalScrollbarEnabled = true;
}
if (this.ContentGrid.offsetHeight > this.Height) {
this.IsVerticalScrollbarEnabled = true;
}
this.Header = document.createElement('div');
this.Header.id = this.GridID + "_Header";
this.Header.style.backgroundColor = "#F0F0F0";
this.Header.style.position = "relative";
this.HeaderFixed = document.createElement('div');
this.HeaderFixed.id = this.GridID + "_Header_Fixed";
this.HeaderFixed.style.overflow = "hidden";
this.Header = this.Parent.insertBefore(this.Header, this.Content);
this.HeaderFixed = this.Header.appendChild(this.HeaderFixed);
this.ScrollbarWidth = this.getScrollbarWidth();
this.prepareHeader();
this.calculateHeader();
this.Header.style.width = String(this.Width) + "px";
if (this.IsVerticalScrollbarEnabled) {
this.HeaderFixed.style.width = String(this.Width - this.ScrollbarWidth) + "px";
if (this.IsHorizontalScrollbarEnabled) {
this.ContentFixed.style.width = this.HeaderFixed.style.width;
if (this.isRTL()) {
this.ContentFixed.style.paddingLeft = String(this.ScrollbarWidth) + "px";
}
else {
this.ContentFixed.style.paddingRight = String(this.ScrollbarWidth) + "px";
}
}
this.ContentFixed.style.height = String(this.Height - this.Header.offsetHeight) + "px";
}
else {
this.HeaderFixed.style.width = this.Header.style.width;
this.ContentFixed.style.width = this.Header.style.width;
}
if (this.FreezeColumn && this.IsHorizontalScrollbarEnabled) {
this.appendFreezeHeader();
this.appendFreezeContent();
}
if (this.FreezeFooter && this.IsVerticalScrollbarEnabled) {
this.appendFreezeFooter();
if (this.FreezeColumn && this.IsHorizontalScrollbarEnabled) {
this.appendFreezeFooterColumn();
}
}
var self = this;
this.ContentFixed.onscroll = function (event) {
self.HeaderFixed.scrollLeft = self.ContentFixed.scrollLeft;
if (self.ContentFreeze != null)
self.ContentFreeze.scrollTop = self.ContentFixed.scrollTop;
if (self.FooterFreeze != null)
self.FooterFreeze.scrollLeft = self.ContentFixed.scrollLeft;
};
};
GridViewScroll.prototype.getGridHeaderRows = function () {
var gridHeaderRows = new Array();
for (var i = 0; i < this.FreezeHeaderRowCount; i++) {
gridHeaderRows.push(this.ContentGrid.rows.item(i));
}
return gridHeaderRows;
};
GridViewScroll.prototype.prepareHeader = function () {
this.HeaderGrid = this.ContentGrid.cloneNode(false);
this.HeaderGrid.id = this.GridID + "_Header_Fixed_Grid";
this.HeaderGrid = this.HeaderFixed.appendChild(this.HeaderGrid);
this.prepareHeaderGridRows();
for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {
this.appendHelperElement(this.ContentGridItemRow.cells.item(i));
this.appendHelperElement(this.HeaderGridHeaderCells[i]);
}
};
GridViewScroll.prototype.prepareHeaderGridRows = function () {
this.HeaderGridHeaderRows = new Array();
for (var i = 0; i < this.FreezeHeaderRowCount; i++) {
var gridHeaderRow = this.ContentGridHeaderRows[i];
var headerGridHeaderRow = gridHeaderRow.cloneNode(true);
this.HeaderGridHeaderRows.push(headerGridHeaderRow);
this.HeaderGrid.appendChild(headerGridHeaderRow);
}
this.prepareHeaderGridCells();
};
GridViewScroll.prototype.prepareHeaderGridCells = function () {
this.HeaderGridHeaderCells = new Array();
for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {
for (var rowIndex in this.HeaderGridHeaderRows) {
var cgridHeaderRow = this.HeaderGridHeaderRows[rowIndex];
var fixedCellIndex = 0;
for (var cellIndex = 0; cellIndex < cgridHeaderRow.cells.length; cellIndex++) {
var cgridHeaderCell = cgridHeaderRow.cells.item(cellIndex);
if (cgridHeaderCell.colSpan == 1 && i == fixedCellIndex) {
this.HeaderGridHeaderCells.push(cgridHeaderCell);
}
else {
fixedCellIndex += cgridHeaderCell.colSpan - 1;
}
fixedCellIndex++;
}
}
}
};
GridViewScroll.prototype.calculateHeader = function () {
for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {
var gridItemCell = this.ContentGridItemRow.cells.item(i);
var helperElement = gridItemCell.firstChild;
var helperWidth = parseInt(String(helperElement.offsetWidth));
this.FreezeCellWidths.push(helperWidth);
helperElement.style.width = helperWidth + "px";
helperElement = this.HeaderGridHeaderCells[i].firstChild;
helperElement.style.width = helperWidth + "px";
}
for (var i = 0; i < this.FreezeHeaderRowCount; i++) {
this.ContentGridHeaderRows[i].style.display = "none";
}
};
GridViewScroll.prototype.appendFreezeHeader = function () {
this.HeaderFreeze = document.createElement('div');
this.HeaderFreeze.id = this.GridID + "_Header_Freeze";
this.HeaderFreeze.style.position = "absolute";
this.HeaderFreeze.style.overflow = "hidden";
this.HeaderFreeze.style.top = "0px";
this.HeaderFreeze.style.left = "0px";
this.HeaderFreeze.style.width = "";
this.HeaderFreezeGrid = this.HeaderGrid.cloneNode(false);
this.HeaderFreezeGrid.id = this.GridID + "_Header_Freeze_Grid";
this.HeaderFreezeGrid = this.HeaderFreeze.appendChild(this.HeaderFreezeGrid);
this.HeaderFreezeGridHeaderRows = new Array();
for (var i = 0; i < this.HeaderGridHeaderRows.length; i++) {
var headerFreezeGridHeaderRow = this.HeaderGridHeaderRows[i].cloneNode(false);
this.HeaderFreezeGridHeaderRows.push(headerFreezeGridHeaderRow);
var columnIndex = 0;
var columnCount = 0;
while (columnCount < this.FreezeColumnCount) {
var freezeColumn = this.HeaderGridHeaderRows[i].cells.item(columnIndex).cloneNode(true);
headerFreezeGridHeaderRow.appendChild(freezeColumn);
columnCount += freezeColumn.colSpan;
columnIndex++;
}
this.HeaderFreezeGrid.appendChild(headerFreezeGridHeaderRow);
}
this.HeaderFreeze = this.Header.appendChild(this.HeaderFreeze);
};
GridViewScroll.prototype.appendFreezeContent = function () {
this.ContentFreeze = document.createElement('div');
this.ContentFreeze.id = this.GridID + "_Content_Freeze";
this.ContentFreeze.style.position = "absolute";
this.ContentFreeze.style.overflow = "hidden";
this.ContentFreeze.style.top = "0px";
this.ContentFreeze.style.left = "0px";
this.ContentFreeze.style.width = "";
this.ContentFreezeGrid = this.HeaderGrid.cloneNode(false);
this.ContentFreezeGrid.id = this.GridID + "_Content_Freeze_Grid";
this.ContentFreezeGrid = this.ContentFreeze.appendChild(this.ContentFreezeGrid);
var freezeCellHeights = [];
var paddingTop = this.getPaddingTop(this.ContentGridItemRow.cells.item(0));
var paddingBottom = this.getPaddingBottom(this.ContentGridItemRow.cells.item(0));
for (var i = 0; i < this.ContentGrid.rows.length; i++) {
var gridItemRow = this.ContentGrid.rows.item(i);
var gridItemCell = gridItemRow.cells.item(0);
var helperElement = void 0;
if (gridItemCell.firstChild.className == "gridViewScrollHelper") {
helperElement = gridItemCell.firstChild;
}
else {
helperElement = this.appendHelperElement(gridItemCell);
}
var helperHeight = parseInt(String(gridItemCell.offsetHeight - paddingTop - paddingBottom));
freezeCellHeights.push(helperHeight);
var cgridItemRow = gridItemRow.cloneNode(false);
var cgridItemCell = gridItemCell.cloneNode(true);
if (this.FreezeColumnCssClass != null || this.FreezeColumnCssClass != "")
cgridItemRow.className = this.FreezeColumnCssClass;
var columnIndex = 0;
var columnCount = 0;
while (columnCount < this.FreezeColumnCount) {
var freezeColumn = gridItemRow.cells.item(columnIndex).cloneNode(true);
cgridItemRow.appendChild(freezeColumn);
columnCount += freezeColumn.colSpan;
columnIndex++;
}
this.ContentFreezeGrid.appendChild(cgridItemRow);
}
for (var i = 0; i < this.ContentGrid.rows.length; i++) {
var gridItemRow = this.ContentGrid.rows.item(i);
var gridItemCell = gridItemRow.cells.item(0);
var cgridItemRow = this.ContentFreezeGrid.rows.item(i);
var cgridItemCell = cgridItemRow.cells.item(0);
var helperElement = gridItemCell.firstChild;
helperElement.style.height = String(freezeCellHeights[i]) + "px";
helperElement = cgridItemCell.firstChild;
helperElement.style.height = String(freezeCellHeights[i]) + "px";
}
if (this.IsVerticalScrollbarEnabled) {
this.ContentFreeze.style.height = String(this.Height - this.Header.offsetHeight - this.ScrollbarWidth) + "px";
}
else {
this.ContentFreeze.style.height = String(this.ContentFixed.offsetHeight - this.ScrollbarWidth) + "px";
}
this.ContentFreeze = this.Content.appendChild(this.ContentFreeze);
};
GridViewScroll.prototype.appendFreezeFooter = function () {
this.FooterFreeze = document.createElement('div');
this.FooterFreeze.id = this.GridID + "_Footer_Freeze";
this.FooterFreeze.style.position = "absolute";
this.FooterFreeze.style.overflow = "hidden";
this.FooterFreeze.style.left = "0px";
this.FooterFreeze.style.width = String(this.ContentFixed.offsetWidth - this.ScrollbarWidth) + "px";
this.FooterFreezeGrid = this.HeaderGrid.cloneNode(false);
this.FooterFreezeGrid.id = this.GridID + "_Footer_Freeze_Grid";
this.FooterFreezeGrid = this.FooterFreeze.appendChild(this.FooterFreezeGrid);
this.FooterFreezeGridHeaderRow = this.ContentGridFooterRow.cloneNode(true);
if (this.FreezeFooterCssClass != null || this.FreezeFooterCssClass != "")
this.FooterFreezeGridHeaderRow.className = this.FreezeFooterCssClass;
for (var i = 0; i < this.FooterFreezeGridHeaderRow.cells.length; i++) {
var cgridHeaderCell = this.FooterFreezeGridHeaderRow.cells.item(i);
var helperElement = this.appendHelperElement(cgridHeaderCell);
helperElement.style.width = String(this.FreezeCellWidths[i]) + "px";
}
this.FooterFreezeGridHeaderRow = this.FooterFreezeGrid.appendChild(this.FooterFreezeGridHeaderRow);
this.FooterFreeze = this.Content.appendChild(this.FooterFreeze);
var footerFreezeTop = this.ContentFixed.offsetHeight - this.FooterFreeze.offsetHeight;
if (this.IsHorizontalScrollbarEnabled) {
footerFreezeTop -= this.ScrollbarWidth;
}
this.FooterFreeze.style.top = String(footerFreezeTop) + "px";
};
GridViewScroll.prototype.appendFreezeFooterColumn = function () {
this.FooterFreezeColumn = document.createElement('div');
this.FooterFreezeColumn.id = this.GridID + "_Footer_FreezeColumn";
this.FooterFreezeColumn.style.position = "absolute";
this.FooterFreezeColumn.style.overflow = "hidden";
this.FooterFreezeColumn.style.left = "0px";
this.FooterFreezeColumn.style.width = "";
this.FooterFreezeColumnGrid = this.HeaderGrid.cloneNode(false);
this.FooterFreezeColumnGrid.id = this.GridID + "_Footer_FreezeColumn_Grid";
this.FooterFreezeColumnGrid = this.FooterFreezeColumn.appendChild(this.FooterFreezeColumnGrid);
this.FooterFreezeColumnGridHeaderRow = this.FooterFreezeGridHeaderRow.cloneNode(false);
this.FooterFreezeColumnGridHeaderRow = this.FooterFreezeColumnGrid.appendChild(this.FooterFreezeColumnGridHeaderRow);
if (this.FreezeFooterCssClass != null)
this.FooterFreezeColumnGridHeaderRow.className = this.FreezeFooterCssClass;
var columnIndex = 0;
var columnCount = 0;
while (columnCount < this.FreezeColumnCount) {
var freezeColumn = this.FooterFreezeGridHeaderRow.cells.item(columnIndex).cloneNode(true);
this.FooterFreezeColumnGridHeaderRow.appendChild(freezeColumn);
columnCount += freezeColumn.colSpan;
columnIndex++;
}
var footerFreezeTop = this.ContentFixed.offsetHeight - this.FooterFreeze.offsetHeight;
if (this.IsHorizontalScrollbarEnabled) {
footerFreezeTop -= this.ScrollbarWidth;
}
this.FooterFreezeColumn.style.top = String(footerFreezeTop) + "px";
this.FooterFreezeColumn = this.Content.appendChild(this.FooterFreezeColumn);
};
GridViewScroll.prototype.appendHelperElement = function (gridItemCell) {
var helperElement = document.createElement('div');
helperElement.className = "gridViewScrollHelper";
while (gridItemCell.hasChildNodes()) {
helperElement.appendChild(gridItemCell.firstChild);
}
return gridItemCell.appendChild(helperElement);
};
GridViewScroll.prototype.getScrollbarWidth = function () {
var innerElement = document.createElement('p');
innerElement.style.width = "100%";
innerElement.style.height = "200px";
var outerElement = document.createElement('div');
outerElement.style.position = "absolute";
outerElement.style.top = "0px";
outerElement.style.left = "0px";
outerElement.style.visibility = "hidden";
outerElement.style.width = "200px";
outerElement.style.height = "150px";
outerElement.style.overflow = "hidden";
outerElement.appendChild(innerElement);
document.body.appendChild(outerElement);
var innerElementWidth = innerElement.offsetWidth;
outerElement.style.overflow = 'scroll';
var outerElementWidth = innerElement.offsetWidth;
if (innerElementWidth === outerElementWidth)
outerElementWidth = outerElement.clientWidth;
document.body.removeChild(outerElement);
return innerElementWidth - outerElementWidth;
};
GridViewScroll.prototype.isRTL = function () {
var direction = "";
if (window.getComputedStyle) {
direction = window.getComputedStyle(this.ContentGrid, null).getPropertyValue('direction');
}
else {
direction = this.ContentGrid.currentStyle.direction;
}
return direction === "rtl";
};
GridViewScroll.prototype.getPaddingTop = function (element) {
var value = "";
if (window.getComputedStyle) {
value = window.getComputedStyle(element, null).getPropertyValue('padding-Top');
}
else {
value = element.currentStyle.paddingTop;
}
return parseInt(value);
};
GridViewScroll.prototype.getPaddingBottom = function (element) {
var value = "";
if (window.getComputedStyle) {
value = window.getComputedStyle(element, null).getPropertyValue('padding-Bottom');
}
else {
value = element.currentStyle.paddingBottom;
}
return parseInt(value);
};
GridViewScroll.prototype.undo = function () {
this.undoHelperElement();
for (var _i = 0, _a = this.ContentGridHeaderRows; _i < _a.length; _i++) {
var contentGridHeaderRow = _a[_i];
contentGridHeaderRow.style.display = "";
}
this.Parent.insertBefore(this.ContentGrid, this.Header);
this.Parent.removeChild(this.Header);
this.Parent.removeChild(this.Content);
this._initialized = false;
};
GridViewScroll.prototype.undoHelperElement = function () {
for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {
var gridItemCell = this.ContentGridItemRow.cells.item(i);
var helperElement = gridItemCell.firstChild;
while (helperElement.hasChildNodes()) {
gridItemCell.appendChild(helperElement.firstChild);
}
gridItemCell.removeChild(helperElement);
}
if (this.FreezeColumn) {
for (var i = 2; i < this.ContentGrid.rows.length; i++) {
var gridItemRow = this.ContentGrid.rows.item(i);
var gridItemCell = gridItemRow.cells.item(0);
var helperElement = gridItemCell.firstChild;
while (helperElement.hasChildNodes()) {
gridItemCell.appendChild(helperElement.firstChild);
}
gridItemCell.removeChild(helperElement);
}
}
};
return GridViewScroll;
}());
//add On Head
<head runat="server">
<title></title>
<script src="client/js/jquery-3.1.1.min.js"></script>
<script src="js/gridviewscroll.js"></script>
<script type="text/javascript">
window.onload = function () {
var gridViewScroll = new GridViewScroll({
elementID: "GridView1" // [Header is fix column will be Freeze ][1]Target Control
});
gridViewScroll.enhance();
}
</script>
</head>
//Add on Body
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
// <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<%-- <Columns>
<asp:BoundField DataField="SHIPMENT_ID" HeaderText="SHIPMENT_ID"
ReadOnly="True" SortExpression="SHIPMENT_ID" />
<asp:BoundField DataField="TypeValue" HeaderText="TypeValue"
SortExpression="TypeValue" />
<asp:BoundField DataField="CHAId" HeaderText="CHAId"
SortExpression="CHAId" />
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
</Columns>--%>
</asp:GridView>
A: <script type="text/javascript">
$(document).ready(function () {
var gridHeader = $('#<%=grdSiteWiseEmpAttendance.ClientID%>').clone(true); // Here Clone Copy of Gridview with style
$(gridHeader).find("tr:gt(0)").remove(); // Here remove all rows except first row (header row)
$('#<%=grdSiteWiseEmpAttendance.ClientID%> tr th').each(function (i) {
// Here Set Width of each th from gridview to new table(clone table) th
$("th:nth-child(" + (i + 1) + ")", gridHeader).css('width', ($(this).width()).toString() + "px");
});
$("#GHead1").append(gridHeader);
$('#GHead1').css('position', 'top');
$('#GHead1').css('top', $('#<%=grdSiteWiseEmpAttendance.ClientID%>').offset().top);
});
</script>
<div class="row">
<div class="col-lg-12" style="width: auto;">
<div id="GHead1"></div>
<div id="divGridViewScroll1" style="height: 600px; overflow: auto">
<div class="table-responsive">
<asp:GridView ID="grdSiteWiseEmpAttendance" CssClass="table table-small-font table-bordered table-striped" Font-Size="Smaller" EmptyDataRowStyle-ForeColor="#cc0000" HeaderStyle-Font-Size="8" HeaderStyle-Font-Names="Calibri" HeaderStyle-Font-Italic="true" runat="server" AutoGenerateColumns="false"
BackColor="#f0f5f5" OnRowDataBound="grdSiteWiseEmpAttendance_RowDataBound" HeaderStyle-ForeColor="#990000">
<Columns>
</Columns>
<HeaderStyle HorizontalAlign="Justify" VerticalAlign="Top" />
<RowStyle Font-Names="Calibri" ForeColor="#000000" />
</asp:GridView>
</div>
</div>
</div>
</div>
A: Refer Here which is 100% working
https://stackoverflow.com/a/59357398/11863405
Static Header for Gridview Control
A: Acheived by using java script...
Copy and paste given below javascript code inside the head tag.
<script language="javascript" type="text/javascript">
function MakeStaticHeader(gridId, height, width, headerHeight, isFooter) {
var tbl = document.getElementById(gridId);
if (tbl) {
var DivHR = document.getElementById('DivHeaderRow');
var DivMC = document.getElementById('DivMainContent');
var DivFR = document.getElementById('DivFooterRow');
//*** Set divheaderRow Properties ****
DivHR.style.height = headerHeight + 'px';
DivHR.style.width = (parseInt(width) - 16) + 'px';
DivHR.style.position = 'relative';
DivHR.style.top = '0px';
DivHR.style.zIndex = '10';
DivHR.style.verticalAlign = 'top';
//*** Set divMainContent Properties ****
DivMC.style.width = width + 'px';
DivMC.style.height = height + 'px';
DivMC.style.position = 'relative';
DivMC.style.top = -headerHeight + 'px';
DivMC.style.zIndex = '1';
//*** Set divFooterRow Properties ****
DivFR.style.width = (parseInt(width) - 16) + 'px';
DivFR.style.position = 'relative';
DivFR.style.top = -headerHeight + 'px';
DivFR.style.verticalAlign = 'top';
DivFR.style.paddingtop = '2px';
if (isFooter) {
var tblfr = tbl.cloneNode(true);
tblfr.removeChild(tblfr.getElementsByTagName('tbody')[0]);
var tblBody = document.createElement('tbody');
tblfr.style.width = '100%';
tblfr.cellSpacing = "0";
tblfr.border = "0px";
tblfr.rules = "none";
//*****In the case of Footer Row *******
tblBody.appendChild(tbl.rows[tbl.rows.length - 1]);
tblfr.appendChild(tblBody);
DivFR.appendChild(tblfr);
}
//****
DivHR.appendChild(tbl.cloneNode(true));
}
}
function OnScrollDiv(Scrollablediv) {
document.getElementById('DivHeaderRow').scrollLeft = Scrollablediv.scrollLeft;
document.getElementById('DivFooterRow').scrollLeft = Scrollablediv.scrollLeft;
}
</script>
Then Copy this code and paste and place your Grid View inside DivMainContent.
HTML Code:-
<div id="DivRoot" align="left">
<div style="overflow: hidden;" id="DivHeaderRow">
</div>
<div style="overflow:scroll;" onscroll="OnScrollDiv(this)" id="DivMainContent">
<%-- ***Place Your GridView Here***
<asp:GridView runat="server" ID="gridshow" Width="100%"
AutoGenerateColumns="False"ShowFooter="True">
<Columns>
//...................
</Columns>
</asp:GridView>
--%>
</div>
<div id="DivFooterRow" style="overflow:hidden">
</div>
</div>
Then Call function MakeStaticHeader in Aspx.CS File at the time of binding Gridview and pass the Some parameters.
*
*ClientId of Gridview(Change GrdDisplay.ClientID as your gridview clientid).
*Height of Scrollable div.
*Width of Scrollable div.
*Height of Table Header Row.
*IsFooter (true/false) If you want to Make footer static or not.
-->After binding the Gridview, place below code
ScriptManager.RegisterStartupScript(Page, this.GetType(), "Key", "<script>MakeStaticHeader('" + GrdDisplay.ClientID + "', 400, 950 , 40 ,true); </script>", false);
Hope this will work for sure...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Back Button in navigation controller Its a very basic question - but i could not find the answer to it anywhere.
I would like a back button like the default one that shows up in a navigation bar, but with a image in the background.
Even with customization, how to calculate the size/length of the button as per the title?
Thanks a ton for the help,in advance!
UPDATE:
Thanks guys! but the answer that i finally implemented was this:
@implementation UINavigationBar (UINavigationBarCategory)
-(void)drawRect:(CGRect)rect
{
UIColor *color = [UIColor colorWithRed:(13.0/255.0) green:(183.0/255.0) blue:(255.0/255.0) alpha:1.0];
// use a custom color for the back button which i got using the digital color meter on my nav bar image :P
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColor(context, CGColorGetComponents( [color CGColor]));
CGContextFillRect(context, rect);
self.tintColor = color;
// use a custom background image for my navigation bar
UIImage *img = [UIImage imageNamed: Navigation_img];
[img drawInRect:CGRectMake(0,0,img.size.width,img.size.height)];
}//worked satisfactorily for me
@end
A: Use sizeWithFont: NSString method to calculate the size of the title.
See NSString UIKit Additions Reference
A: To find out the width of specific text, you may use following methods.
NSString *str=@"Back";
CGSize sizeOfBack = [str sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(30, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
Let me explain above two statements.
*
*the text that you want to have in your string.
*sizewithfont method will allow you to calculate the size.
Here, sizeOfBack.width will give me the width acquired by 14System sized string.
Hope it helps to you. let me know by comments, if you have yet doubts regarding this.
A: *
*Create a UIButton using your own UIImage to mimic the shape you want.
*The UIImage must be a stretchable type, that is, you would set the leftCapWidth to be the size of your back arrow
*Set the UIButton's title to whatever you like
*Create a new UIBarButtonItem using your new button as a custom view
*Set this to your navigationItems leftBarButtonItem property.
The button will automatically size to fit your title.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting Type Mismatch Issue while Adding parameter to XSLT using VBScript I have got below code in VBScript:
<%
Option Explicit
#importXSLT "tcm:228-190529-2048" As expandXSLT
#importXSLT "tcm:228-642694-2048" As renderXSLT
Dim xml, currentDateTime
Set xml = getNewDomDocument()
xml.loadXML TDSE.GetListPublications(3)
expandXSLT.input = xml
Call expandXSLT.addParameter("publication", Component.Publication.Id)
expandXSLT.transform
xml.loadXML(expandXSLT.output)
'WriteOut xml.xml
currentDateTime = now
renderXSLT.input = xml
Call renderXSLT.addParameter("currentPublishedDate", currentDateTime)
renderXSLT.transform
WriteOut renderXSLT.output
Set xml = Nothing
%>
You can see there is two syntax where I am adding the XSLT parameter, the first one is working fine i.e.
expandXSLT.input = xml
Call expandXSLT.addParameter("publication", Component.Publication.Id)
expandXSLT.transform
However the new requirement was that, we need to send current date time from here to the XSLT, so I have added the same logic to send the current date & time to my XSLT, below is code added by me
currentDateTime = now
renderXSLT.input = xml
Call renderXSLT.addParameter("currentPublishedDate", currentDateTime)
renderXSLT.transform
But when I am trying to run the above code its giving below error:
Type mismatch.
(source: Call renderXSLT.addParameter("publishedDate", currentDateTime)).
Please suggest!!
A: Try whether converting the currentDateTime value you have to a string first to pass that string to XSLT e.g. CStr(currentDateTime).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Time series plot with groups using ggplot2 I have an experiment where three evolving populations of yeast have been studied over time. At discrete time points, we measured their growth, which is the response variable. I basically want to plot the growth of yeast as a time series, using boxplots to summarise the measurements taken at each point, and plotting each of the three populations separately. Basically, something that looks like this (as a newbie, I don't get to post actual images, so x,y,z refer to the three replicates):
| xyz
| x z xyz
| y xyz
| xyz y
| x z
|
-----------------------
t0 t1 t2
How can this be done using ggplot2? I have a feeling that there must be a simple and elegant solution, but I can't find it.
A: Try this code:
require(ggplot2)
df <- data.frame(
time = rep(seq(Sys.Date(), len = 3, by = "1 day"), 10),
y = rep(1:3, 10, each = 3) + rnorm(30),
group = rep(c("x", "y", "z"), 10, each = 3)
)
df$time <- factor(format(df$time, format = "%Y-%m-%d"))
p <- ggplot(df, aes(x = time, y = y, fill = group)) + geom_boxplot()
print(p)
Only with x = factor(time), ggplot(df, aes(x = factor(time), y = y, fill = group)) + geom_boxplot() + scale_x_date(), was not working.
Pre-processing, factor(format(df$time, format = "%Y-%m-%d")), was required for this form of graphics.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to use javascript conditionally like CSS3 media queries, orientation? How to use javascript conditionally like CSS3 media queries, orientation?
For Example I can write css for specific
@media only screen and (width : 1024px) and (orientation : landscape) {
.selector1 { width:960px}
}
Now I want to only run some javascript if it match the same conditions
like
@media only screen and (width : 1024px) and (orientation : landscape) {
A javascript code here
}
I have a external javascript for example http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.min.js and it should be only run on specific screen size and orientation
A: You can use window.matchMedia():
Test a mobile device media query
if (matchMedia('only screen and (max-width: 480px)').matches) {
// smartphone/iphone... maybe run some small-screen related dom scripting?
}
Test landscape orientation
if (matchMedia('all and (orientation:landscape)').matches) {
// probably tablet in widescreen view
}
Currently supported in all modern browsers (more details)
Polyfill for old browsers:
https://github.com/paulirish/matchMedia.js/
A:
...I want to run a javascript only if max-width of browser is 1900px
and min-width is 768
EDIT: Actually, that was all wrong. If you're using a mobile device, use:
function doStuff(){
landscape = window.orientation? window.orientation=='landscape' : true;
if(landscape && window.innerWidth<1900 && window.innerWidth > 768){
//code here
}
}
window.onload=window.onresize=doStuff;
if(window.onorientationchange){
window.onorientationchange=doStuff;
}
A: I can think of a quick solution: Apply some styles conditionally to an invisible div, and check if they are applied with javascript:
div#test { display: none }
@media only screen and (width : 1024px) and (orientation : landscape) {
div#test { background-color: white; }
}
if(document.getElementById('test').style.backgroundColor == 'white')
mediaSelectorIsActive();
A: It's probably worth mentioning that there is the orientationchange event that you might want to hook into like so:
$('body').bind('orientationchange', function(){
// check orientation, update styles accordingly
});
I know that about this event being fired by mobile Safari, you'd have to check about other browsers.
A: You could just rewrite the media query as a javascript expression instead:
function sizehandler(evt) {
...
}
function orientationhandler(evt){
// For FF3.6+
if (!evt.gamma && !evt.beta) {
evt.gamma = -(evt.x * (180 / Math.PI));
evt.beta = -(evt.y * (180 / Math.PI));
}
// use evt.gamma, evt.beta, and evt.alpha
// according to dev.w3.org/geo/api/spec-source-orientation
...
}
window.addEventListener('deviceorientation', orientationhandler, false);
window.addEventListener('MozOrientation', orientationhandler, false);
window.addEventListener('load', orientationhandler, false);
window.addEventListener('resize', sizehandler, false);
window.addEventListener('load', sizehandler, false);
A: The simplest way I found is to get the width of our page; then to conditionally use it.
var x = document.documentElement.clientWidth;
if (x < 992) {
document.body.style.backgroundColor = "yellow";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "48"
} |
Q: Google Calendar API I have the code:
// Create a CalenderService and authenticate
CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
myService.setUserCredentials("[email protected]", "mypassword");
// Send the request and print the response
URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/allcalendars/full");
CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);
System.out.println("Your calendars:");
System.out.println();
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEntry entry = resultFeed.getEntries().get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
This code gives out the list of all calendars. At me - a box calendar, a calendar of birthdays of friends and a calendar of holidays. I need to receive all events occurring today - i.e. both my notes, and birthdays of friends, and holidays. How I am able to do it?
A: You need to execute a date range query starting and ending of that day. See
http://code.google.com/apis/calendar/data/2.0/developers_guide_java.html#RetrievingDateRange
(I'm not 100% sure , but I think with the url https://www.google.com/calendar/feeds/default/allcalendars/full you should get results for all your calendars)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQL Query - Left Join or Union? How do I write a SQL query to find out what the group ID is and then display list of Options from that Group ID.
I can do it by two queries, for example:
//Get the group ID
SELECT option_group_id FROM options WHERE id =14122
//Now get a list of OptionID from that group ID
SELECT id, name FROM options WHERE option_group_id = 999
How do I put this into 1 query?
A: You could use a subquery to retrieve the group's id:
select id
, name
from options
where option_group_id =
(
select option_group_id
from options
where id = 14122
)
A: Basically:
*
*if you want more columns => join
*if you want more rows => union
In this case:
SELECT toGetData.id
, toGetData.name
FROM options toGetId
join options toGetData on toGetData.option_group_id = toGetId.option_group_id
wHERE toGetId.id = 14122
A: Neither. You use an inner join against the same table:
select o2.id, o2.name
from options o1
inner join options o2 on o2.option_group_id = o1.option_group_id
where o1.id = 14122
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Use of HTML5 custom data attribute for AJAX response I have never used HTML5 much and so am not aware of its limitation.
But I have heard there is a useful custom data attribute which has got added. So my question is, can I use this for AJAX response handling? By that I mean, say I have coded some placeholder divs with data attributes.
Now can I parse this JSON response to fill up the div elements easily. Or is there another quicker way?
Main thing is HTML structure would be separate and json response will only contain data.
A: You should check out the jQuery.template() plugin
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Difference between variable === value and value === variable? a)
if(null === $object)
{
//take some action
}
b)
if($object === null)
{
//take some action
}
I am in habit of doing like b) but in Zend-Framework I find everywhere they have done it like a) . Is there any benefits of it ??
Thanks.
A: No, there is no difference.
The latter is supposed to help to avoid silly typos when you write $a = null instead of $a == null (or $a === null). In first case you'll get logical error, because of assignment instead of comparison, in second case - you'll get fatal error which will help you to find an issue sooner.
A: There is no difference, it is used to avoid mistakes (like setting variable to null, not comparing them), however the null === $object is often considered the Bad Way (c) to avoid typos.
A: The $object === null expression is much more human-friendly then null === $object 'cause second one breaks nature reading order which is left-to-right. That's why even if there is no much difference for interpreter but it's a bit harder to read by a human. Involving some logic - if you use if..else statement how it should sounds like? "If null equals $object.. Wait a minute, null is null, how can it be equal to something else? Oh, Gee, we actually comparing right-handed value to left-handed one, it's reversed stuff. So, if $object equals null then we should..". And your think this way every time.
My conclusion is: use $value == const every time you can! Long time ago people wrote if ($value = const) but these times have passed. Now every IDE can tell ya about such simple errors.
A: b) is way more readable than a)
And a) is considered by some overcautious people as less error prone because of possible confusing == with =.
But in case of three ='s I doubt anyone will confuse it with one.
A: This a choice by the developer to attempt to stop accidential assignment of values.
The functionality is exactly the same between the two methods of comparison but in the case of "a" it stops any accidential assignment of values as you cannot assign something to null.
A: The second method checks the value and type of variable against null, The errors should be different in tow methods.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Xcode 4.2 Warnings when dropping Nav Controller on Tab Bar in IB I'm developing an app which is iOS 4 compatible, so my deployment target is set to iOS 4.0.
Whenever I drop a UINavigationController onto a UITabBar, I get these two warnings:
*
*warning: Attribute Unavailable: Defines Presentation Context is not available prior to Xcode 4.2.
*warning: Attribute Unavailable: Defines Presentation Context on iOS versions prior to 5.0.
The UINavigationController functions as expected, in fact, the entire app runs perfectly. But these two warnings are driving me nuts!
Also, the moment I delete the UINavigationController the warnings disappear.
A: You are getting these warnings because you are using iOS 5.0 SDK features with a 4.x deployment target.
All, if not, most of the new 5.0 hotness, including ARC and Storyboards, is completely backwards compatible with iOS 4.x (I don't remember if 4.0 or 4.3 is the lowest supported version, check the docs), it will work as intended, but Xcode is going to warn you anyways.
You should be able to disable that warning if it really bothers you, but I wouldn't. That said, Apple does not currently accept applications built/archived with the Xcode 4.2 beta for submission to the App Store. This means you need to use Xcode 4.0/4.1 in a production environment.
Before we go any further, you should know that Xcode 4.2/iOS 5 is beta software, it is under NDA (you agreed to this when you joined the Apple developer program) and cannot be discussed in the public domain. This means you won't be able get much help from places in the public eye, like StackOverflow, as good as it can be. But, since I'm here and this is a very high level question, I can help :)
In the future, if you have iOS beta questions or issues, you should hit up the Apple Developer Beta Forums (an excellent resource, always search before you post), or #iphonedev on irc.freenode.net for not-beta stuff (I'll be there, say hi!)
If you're developing an application for release on the App Store:
You need to be developing with Xcode 4.0 or 4.1, Apple will not accept applications built/archived with 4.2. (I know I repeated myself, but people seem to miss this often)
And, although 4.2b7 supports developing for older frameworks better than previous Xcode betas have (by allowing you to install previous versions of the simulator), you will still find yourself accidentally using 5.0 SDK functions all over the place, as the code completion/interface builder very aggressively favors all of the new hotness. This is because the beta is for trying new things, not stable application development.
This means you need to switch back to using Xcode 4.0/4.1 for production, if you don't have it installed, or you overwrote the stable version with the beta, do not try to install 4.0/4.1 on top of the 4.2 beta, weird things will happen and both versions will start acting really weird and and Xcode will crash at least twice as often.
The best thing to do in this situation, is to follow the below steps. Make sure you don't skip anything, otherwise you'll have to restart the whole process.
*
*Make sure you have your code committed and pushed up,
uninstalling Xcode like this temporarily removes git. (This was an
issue for me at work once)
*Download the installers for Xcode 4.0/.1, and 4.2 if you intend to keep experimenting. (if you already
have both downloaded, this whole process won't take more than 5
minutes on an SSD)
*Uninstall the Xcode beta from the command line using this command:
sudo <Xcode>/Library/uninstall-devtools --mode=all (more info here)
*Restart your computer (this is important, do not skip it!!!)
*Install the most recent non-beta version of Xcode and resume development.
If you want to use both versions of Xcode (4.0/4.1 and 4.2):
You must install the beta AFTER 4.0/4.1 is installed, otherwise you will be overwriting new things with old things, and this will give you many, many obscure headaches. I also recommend restarting between installations.
You need to install 4.2 after 4.0/4.1, and to a different folder (I use /Xcode4beta/, don't put it within the folder that contains 4.0/4.1, either). I've found I learn about the new hotness best if I keep separate iOS5 branches of my work, and update what I can when I have some free time.
If you have the iOS5 beta installed on your phone, and Xcode 4.0/4.1 won't let you build to your phone:
This is because Xcode needs to grab the debug symbols from the phone before it can be used for devleopment, but only the Xcode beta can do this for an iOS5 beta device, so follow these steps:
*
*Make sure your phone is plugged in and turned on, and that your provisioning profile/certificates all check out.
*Close the project in Xcode 4.0/4.1.
*Open the project back up in Xcode 4.2, and check organizer. You should either already have a green dot next to your phone (assuming all of your provisioning is working), or it should be gathering the debug symbols. Let this finish, and then build your project. It doesn't need to be a successful build, nor do you have to install the application to the phone, sometimes you don't even need to build, Xcode can be a fickle mistress.
*Close the project in Xcode 4.2.
*Open the project back up in Xcode 4.0, you should now be able to build and install to your phone as you normally would.
*Xcode 4.0/4.1 should now be able to use your device for development until you restart the computer.
A: Just uncheck the "Defines Context" checkbox in the attributes inspector. (Double-click on MainWindow.xib, select the navigation controller, then go to View->Utilities->Attributes Inspector.) That'll get rid of the warnings.
A: Resolution is here:
How can I fix "Freeform Size simulated metrics are not available prior to Xcode 4.2" warnings?
You just need to change the development version of your xib file to Xcode 4.2 (default is Xcode 4.1)
A: View Controller and Navigation Controller setting or options name ( attributes inspector )
Define Context ( Checked ) unchecked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: python - single item tuple throws exception in for statement Im curious as to why this happens. Im using Mako templates to iterate over a tuple, that contains a number of number of dictionaries, that in turn contain link information:
links = (
{
'path' : request.route_url('home'),
'text' : 'Home'
},
{
'path' : "http://www.microsoft.com",
'text' : "Microsoft"
}
)
if i send the above to the view, everything works as expected, the links are displayed. If i remove the second link however:
links = (
{
'path' : request.route_url('home'),
'text' : 'Home'
}
)
i get an exception: TypeError: string indices must be integers, not str
if i put a comma after the end of the dictionary, things start working again. Can anyone explain what is going on?
Edit Mako template snippet
<nav>
% for link in links:
<a href="${link['path']}">${link['text']}</a>
% endfor
</nav>
A:
if i put a comma after the end of the dictionary, things start working
again. Can anyone explain what is going on?
The comma makes the tuple. Without it you just have a single value in brackets.
x = ({}) # brackets around a dict
x = {}, # a 1-tuple
x = ({},) # a 1-tuple in brackets
Often it appears that the brackets are the notation for tuples, because they appear together so often. That's only because for syntactic reasons, you often need the brackets when writing a tuple.
When you write links = ({ ... }) you have only a dictionary, not a tuple. Python loops over it's keys, so each link is a string, which you try to index by another string, resulting in the exception.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unit test a method which is on high abstraction level A similar topic has been discussed in The value of high level unit tests and mock objects
However, I'd like to describe a specific situation and ask your opinion about how I should write a unit test.
I am developing an ordinary 3-tier application, which uses Entity Framework. Above EF, I have two layers:
*
*Repositories: They directly access the EF ObjectContext and do all the CRUD work (actually, these classes are generated with a T4 template). All Repository class has an appropriate interface.
*Managers: They implement the higher level business logic, they do not access directly the ObjectContext, rather use an appropriate Repository. Managers do not know the concrete Repository-implementation, only the interface (I use dependency injection, and mocks in the unit test).
Without further description, here is the class I'd like to write unit tests for:
public class PersonManager
{
private IPersonRepository personRepository; // This is injected.
// Constructor for injection is here.
public void ComplexMethod()
{
// High level business logic
bool result = this.SimpleMethod1();
if(result)
this.SimpleMethod2(1);
else
this.SimpleMethod2(2);
}
public bool SimpleMethod1()
{
// Doing some low-level work with the repository.
}
public void SimpleMethod2(int param)
{
// Doing some low-level work with the repository.
}
}
It is really easy to unit test SimpleMethod1 and SimpleMethod2 by instantiating the PersonManager with a mock of the PersonRepository.
But I can not find any convenient way to unit test ComplexMethod.
Do you have any recommendation about how should I do that? Or that should not be unit tested at all? Maybe I should not use the this reference for the method calls in ComplexMethod, rather access the PersonManager itself via an interface, and replace that with a mock too?
Thanks in advance for any advice.
A: Guillaume's answer is good (+1), but I wanted to give an additional observation. What I see in the code you've posted is the basis for a very common question from people trying to figure out (or argue against) TDD, which is:
"How/why should I test ComplexMethod() since it depends on SimpleMethod1() and SimpleMethod2(), which are already tested and have their own behavior that I'd have to account for in tests of ComplexMethod()? I'd have to basically duplicate all the tests of SimpleMethod1() and SimpleMethod2() in order to fully test ComplexMethod(), and that's just stupid."
Shortly after, they usually find out about partial mocks. Using partial mocks, you could mock SimpleMethod1() and SimpleMethod2() and then test ComplexMethod() using normal mock mechanisms. "Sounds great," they think, "This will solve my problem perfectly!". A good mock framework should strongly discourage using partial mocks in this way, though, because the reality is:
Your tests are telling you about a design problem.
Specifically, they're telling you that you've mixed concerns and/or abstraction levels in one class. They're telling you that SimpleMethod1() and SimpleMethod2() should be extracted to another class which this class depends on. No matter how many times I see this scenario, and no matter how vehemently the developer argues, the tests are proven right in the end 100% of the time.
A: I don't see what the problem is. You can test your complex method while mocking the repository, there is no problem.
Your would need two unit-tests, each one would use the same sequence of expectations and executions that you have in your tests of the SimpleMethod1 (I assume you already have two unit-tests for SimpleMethod1, one for a return of "true", one for "false") and also the same expectations that you have for your test SimpleMethod2 with a fixed parameter 1, or 2 respectively.
Granted, there would be some "duplication" in your testing class, but that's not a problem.
Also note your tests for SimpleMethod2 should not make any assumption for the parameter passed: in "real-life" you can have only 1 or 2 as a parameter (and that's what your unit-test for ComplexMethod would have), but your unit-tests for SImpleMethod2 should test it whatever the parameter is: any int.
And finally, if ComplexMethod is the ONLY way to call SimpleMethod1 and/or SimpleMethod2, you should consider making these private, and have only unit-tests for ComplexMethod.
Does that make sense?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: is there any way to change urls is iframe? I want to show a page of my website within iframe in another page.
I mean you can see helper.html while you are navigation main.php.
but I want to change some links in helper.html regarding to some conditions set in main.php.
The regular solution is to get content of helper.html and process it in main.php, then echo it.
But it is server side, I want this process to be client side.
Is that possible with JavaScript?
A: If your files are located at the same domain, you can use the top.frames property, ro refer to the window object of named frames:
Assume the top HTML to has such a structure:
<iframe name="main" /><iframe name="helper" />
Inside main:
top.frames["helper"].document.getElementById("linkID").href = "http://newlink.com";
If you're using AJAX, you can add the previously shown code in the callback handler. If main.php reloads on change, at the code within <script> tags.
A: Try this...
var myIframe = document.getElementById('SomeIFrame');
myIframe.src = 'www.joobworld.com';
A: Yes it is possible if both frames are in same domain.
See sample function: in the help frame the id of link is assumed to be "link"
function ChangeLink()
{
var Helpframe = document.getElementById("Helpframe");
var innerDoc = Helpframe.contentDocument || Helpframe.contentWindow.document;
var link = innerDoc.getElementById("link");
link.href="http://www.google.com";
}
This solution is inspired from Javascript - Get element from within an iFrame
A: If those files are on different domains but you have a full control of them, then use the following solution:
*
*In the main page call an iframe with GET parameters. For instance:
<iframe src="foo.html?parameter=value" width="400" height="500"></iframe>
*In an iframe parse GET parameters using Javascript and show an appropriate content:
// get the current URL
var url = window.location.toString();
//get the parameters
url.match(/\?(.+)$/);
var params = RegExp.$1;
// split up the query string and store in an
// associative array
var params = params.split("&");
var queryStringList = {};
for(var i=0;i<params.length;i++)
{
var tmp = params[i].split("=");
queryStringList[tmp[0]] = unescape(tmp[1]);
}
// print all querystring in key value pairs
for(var i in queryStringList)
document.write(i+" = "+queryStringList[i]+"<br/>");
Source: http://www.go4expert.com/forums/showthread.php?t=2163
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: I don't have "Application" field in Logcat I use Eclipse with ADT and according to release notes for R14 preview now we can create filters using Application field. But it is always empty for me, for different applications, different log levels. Why? How can I use this?
A: You need to set debuggable to true
A: Clearing CatLog and restarting Eclipse helped me..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: navigationController issue I have the following:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath(NSIndexPath*)indexPath
{
audiChassisInputViewController = [[myAudiChassisInputViewController alloc] init];
[self.navigationController pushViewController:audiChassisInputViewController animated:YES];
self.navigationController.navigationBarHidden = NO;
UIBarButtonItem *retourButton = [[UIBarButtonItem alloc] initWithTitle:@"Retour" style:UIBarButtonItemStyleBordered target:self.navigationController action:@selector(popViewControllerAnimated:)];
[self.navigationController.navigationBar.topItem setLeftBarButtonItem:retourButton];
[self.navigationController.navigationBar.topItem setTitle:@"Chassis Input"];
[retourButton release];
[audiChassisInputViewController release];
}
and this workes...the new view is showed.
in the new view:
myAudiChassisInputViewController.h
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
chassisInputTextView.layer.cornerRadius = 15;
chassisInputTextView.clipsToBounds = YES;
[chassisInputTextView becomeFirstResponder];
UIBarButtonItem *okButton = [[UIBarButtonItem alloc] initWithTitle:@"OK" style:UIBarButtonItemStyleBordered target:self action:@selector(chassisOkPressed)];
[self.navigationController.navigationBar.topItem setRightBarButtonItem:okButton];
[okButton release];
}
I have no error, but there is no right bar button shown.Anyone, any idea why?
A: Change this line:
[self.navigationController.navigationBar.topItem setRightBarButtonItem:okButton];
with this line:
[[self navigationItem] setRightBarButtonItem:okButton];
The thing is, by the time viewDidLoad is executed, the top item of the navigation bar (self.navigationController.navigationBar.topItem) is still pointing to the navigation item of the back view controller.
The back view controller is the one that used to be the top view controller before the current top view controller was pushed onto the stack ([[viewControllers objectAtIndex:[viewControllers count] - 2] navigationItem]). The following snippet shows how the top item of the navigation bar is still pointing to the navigation item of the back view controller in viewDidLoad and it is for illustration purposes only:
// the view controllers currently on the navigation stack
NSArray *viewControllers = self.navigationController.viewControllers;
// The root view controller is at index 0 in the array, the back view controller is at index n-2, and the top controller is at index n-1, where n is the number of items in the array.
UIViewController *backViewController = [viewControllers objectAtIndex:[viewControllers count] - 2];
// get the navigation item of the back view controller
UINavigationItem *backNavigationItem = backViewController.navigationItem;
UINavigationItem *topItem = self.navigationController.navigationBar.topItem;
if (backNavigationItem == topItem) {
NSLog(@"This gets logged to the console");
}
A: Go to your
myAudiChassisInputViewController.m file
place following code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIBarButtonItem *retourButton = [[UIBarButtonItem alloc] initWithTitle:@"Retour" style:UIBarButtonItemStyleBordered target:self.navigationController action:@selector(popViewControllerAnimated:)];
UIBarButtonItem *itemOkey=[[UIBarButtonItem alloc] initWithTitle:@"OK" style:UIBarButtonItemStyleBordered target:self action:@selector(chassisOkPressed)];
self.navigationItem.rightBarButtonItem=itemOkey;
self.navigationItem.leftBarButtonItem=retourButton;
}
I have the valid output as follows that you want to have
Hope it helps to you.
A: If you have xib file of your class, then add the navigation controller and add the navigation bar and under that add the UIBarButton.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VBA throwing 'else without if' error I was trying out the following code and its repeatedly throwing the 'else without if' and such similar errors. I just cant figure out where the error lies, because each if is properly terminated.
Here is the code:
Sub hra_macro()
Dim city As Boolean
Dim salary As Integer
Dim varHRA As Integer
Dim mimHRA As Integer
Dim maxHRA As Integer
Dim A As Integer
Dim B As Integer
Dim Rent As Integer
city = Range("b1").Value
salary = Range("b2").Value
Rent = Range("b3").Value
If city = True Then
varHRA = 0
A = Rent - (salary / 10)
B = salary * 0.5
Do While varHRA < salary
varHRA = varHRA + 1
If (varHRA < A And varHRA < B) Then
minHRA = varHRA
End If
If (A < varHRA And A < B) Then
minHRA = A
End If
If (B < varHRA And B < A) Then
minHRA = B
End If
If minHRA > maxHRA Then
maxHRA = minHRA
End If
Exit Do
Else '<<<<<<<<<<<<<<<<<<<< PROBLEM AREA
varHRA = 0
A = Rent - (salary / 10)
B = salary * 0.4
Do While varHRA < salary
varHRA = varHRA + 1
If (varHRA < A And varHRA < B) Then
minHRA = varHRA
End If
If (A < varHRA And A < B) Then
minHRA = A
End If
If (B < varHRA And B < A) Then
minHRA = B
End If
If minHRA > maxHRA Then
maxHRA = minHRA
End If
Exit Do
End If
Range("b4").Value = maxHRA
End Sub
A: The Ifs look okay to me at first glance, but I noticed that both Dos are missing the Loop.
It should look like this:
Do While varHRA < salary
'Do Stuff
Loop
Exit Do is used to exit the loop before the condition behind the While is true, but you always need the Loop keyword.
If the problem still remains, please post the exact error message that you're getting.
EDIT:
I just tried to reproduce your problem in VBA in MS Access (I don't have Excel installed on this machine, only Access):
Public Function Test()
If 1 = 0 Then
Do While 1 = 0
Stop
Exit Do
Else
Stop
End If
End Function
This simple piece of code gives me the exact same error message that you got:
Compile error: Else without If
When I replace the Exit Do by a Loop, the error goes away and the code compiles.
So, you should replace the Exit Do by Loop in your code.
A: Looks like your using 'Exit Do' instead of 'Loop'. 'Exit Do' will exit the Do loop, is this the way you want this to behave?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to add protocol buffers support to a maven project ? How to integrate protocol buffers with a maven project ? Couldn't find any information for maven users on the protocol buffers page. I need to add PB support to my web app project with protoc compiler support as well for maven, if it is there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Process Object from Apache Commons Exec I'm using the Apache Commons Exec jars for creating processes. However I'd like to get control of the process id of processes being invoked.
Is there a way of getting the 'Process' object from the Apache Commons Exec api? I did'nt fine any public methods that returns the 'Process class.
A: See http://commons.apache.org/exec/apidocs/index.html
Interface CommandLauncher contains several exec methods that return Process.
But anyway you do not have any way to control the process ID: it is the OS responsibility. Moreover standard java API does not allow you even to retrieve the process ID. There was a trick in older java versions: the implementation of Process contained int field pid that could be retrieved using reflection. But this was changed in version 1.6.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Joomla 1.7 custom toolbar button usage I've added a custom button into my component's backend toolbar with this code:
JToolBarHelper::custom('libri.details','details.png','details.png','TOOLBAR_DETAILS',true);
This button needs that the admin checks one of the entries listed in the table.
You can see a screenshot here if you haven't understood what I'm talking about
The button is the one called "Dettagli" (no image at the moment).
I'm having some problems:
*
*How do I append the checked entry's id to the address generated from the button?
*I've put a details() method into the controller, it calls an instance of the model and a method inside it. The model's method returns to the controller the result of a query. How do I say to the controller to pass that result to a view called libro?
A: *
*All information in the page will be sent through POST to the Joomla controller (in this case, libri). In your controller, you can use JRequest::getVar('varNameHere'); to retrieve it.
*$this->setRedirect($urlOfView, $someStatusMessage)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Setting divider location on a JSplitPane doesn't work I'm trying to set the divider location of a JSplitPane but it seems not to work.
Here's an SSCCE:
import java.awt.Color;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
public class JSplitProblem extends JFrame {
public JSplitProblem(){
JPanel upperPanel = new JPanel();
upperPanel.setLayout(new BoxLayout(upperPanel, BoxLayout.X_AXIS));
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
JPanel red = new JPanel();
red.setBackground(Color.red);
leftPanel.add(red);
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
JPanel blue = new JPanel();
blue.setBackground(Color.blue);
rightPanel.add(blue);
upperPanel.add(leftPanel);
upperPanel.add(rightPanel);
JPanel bottomPanel = new JPanel();
bottomPanel.setBackground(Color.black);
JSplitPane mainSplittedPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upperPanel,bottomPanel);
mainSplittedPane.setOneTouchExpandable(true);
mainSplittedPane.setDividerLocation(0.5);
this.add(mainSplittedPane);
this.setSize(800,600);
this.setResizable(true);
this.setVisible(true);
}
public static void main(String[] args) {
new JSplitProblem();
}
}
I would like the black bottom panel to lay on a 50% of the whole area by default. What am I doing wrong?
A: nothing complicated in this case, with rules
1) PrefferedSize must returns Childs not as I wrong to set in my case too :-), then my answer isn't @kleopatra resist too
2) put everything about rezize, size, whatever for JSplitPane into invokeLater()
.
.
import java.awt.*;
import javax.swing.*;
public class JSplitProblem extends JFrame {
private static final long serialVersionUID = 1L;
private JSplitPane mainSplittedPane;
public JSplitProblem() {
JPanel upperPanel = new JPanel();
upperPanel.setLayout(new BoxLayout(upperPanel, BoxLayout.X_AXIS));
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
JPanel red = new JPanel();
red.setBackground(Color.red);
leftPanel.add(red);
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
JPanel blue = new JPanel();
blue.setBackground(Color.blue);
rightPanel.add(blue);
upperPanel.add(leftPanel);
upperPanel.add(rightPanel);
JPanel bottomPanel = new JPanel();
bottomPanel.setBackground(Color.black);
mainSplittedPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upperPanel, bottomPanel);
mainSplittedPane.setOneTouchExpandable(true);
mainSplittedPane.setDividerLocation(0.5);
add(mainSplittedPane);
setPreferredSize(new Dimension(400, 300));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(true);
setVisible(true);
pack();
restoreDefaults();
}
private void restoreDefaults() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
mainSplittedPane.setDividerLocation(mainSplittedPane.getSize().height /2);
//mainSplittedPane.setDividerLocation(mainSplittedPane.getSize().width /2);
}
});
}
public static void main(String[] args) {
JSplitProblem jSplitProblem = new JSplitProblem();
}
}
A: I'm not sure, but I think you should try to pack() your frame. And if that doesn't work, try to reset the divider location after you packed the frame.
A: If you want both halves of the split pane to share in the split pane's extra or removed space, set the resize weight to 0.5: (Tutorial)
JSplitPane mainSplittedPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upperPanel,bottomPanel);
mainSplittedPane.setOneTouchExpandable(true);
mainSplittedPane.setResizeWeight(0.5);
A: Just add the code below, and that will be fairly enough.
mainSplittedPane.setResizeWeight(0.5);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: How do I generate new source code in text form in a Scala compiler plugin? I have just finished the first version of a Java 6 compiler plugin, that automatically generates wrappers (proxy, adapter, delegate, call it what you like) based on an annotation.
Since I am doing mixed Java/Scala projects, I would like to be able to use the same annotation inside my Scala code, and get the same generated code (except of course in Scala). That basically means starting from scratch.
What I would like to do, and for which I haven't found an example yet, is how do I generate the code inside a Scala compiler plugin in the same way as in the Java compiler plugin. That is, I match/find where my annotation is used, get the AST for the annotated interface, and then ask the API to give me a Stream/Writer in which I output the generated Scala source code, using String manipulation.
That last part is what I could not find. So how do I tell the API to create a new Scala source file, and give me a Stream/Writer/File/Handle, so I can just write in it, and when I'm done, the Scala compiler compiles it, within the same run in which the plugin was invoked?
Why would I want to do that? Firstly, because than both plugins have the same structure, so maintenance is easy. Secondly, I want to open source it, and there is just no way to support every option that anyone would want, so I expect potential users to want to extend the generation with their own code. This will be a lot easier for them if they just have to do some printf(), instead of learning the AST API (this also applies to me).
A: Short answer:
It can't be done
Long answer:
You could conceivably generate your source file and push that through a parser instance within your plugin. But not in any way that's likely to be of any use to you, because you'd now have a bigger problem to contend with:
In order to grab all the type/name information for generating the delagate/proxy, you'll have to pick up the annotated type's AST after it has run through both the namer and typer phases (which are inseperable). The catch is that any attempts to call your generated code will already have failed typechecking, the compiler will have thrown an error, and any further bets are off.
Method synthesis is possible in limited cases, so long as you can somehow fool the typechecker for just long enough to get your code generated, which is the trick I pulled with my Autoproxy 'lite' plugin. Even then, you're far better off working with TreeDSL to generate code instead of pumping out raw source.
A: Kevin is entirely correct, but just for completeness it's worth mentioning that there is another alternative - write a compiler plugin that generates source. This is the approach that I've adopted in Borachio. It's not a very satisfactory solution, but it can be made to work.
Edit - I just reread your question and realised that you're actually asking about generating source anyway
So there is no support for this directly, but it's basically just a question of opening a file and writing the relevant "print" statements. There's no way to invoke the compiler "inside" a plugin AFAIK, but I've written an sbt plugin which hides most of the complexity of invoking the compiler twice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Navigation issues with jQuery My problem is as follows:
I have a simple navigation
<ul class="navigation">
<li class="heading selected">Slider images</li>
<li><a href="index.php?action=staticpages" title="">Static pages</a></li>
<li><a href="index.php?action=accomodation" title="">Accomodation</a></li>
<li><a href="index.php?action=general" title="">General</a></li>
<li><a href="index.php?action=settings" title="">Settings</a></li>
<li><a href="index.php?action=dologout" title="">Logout</a></li>
</ul>
and my "not finished" jQuery function:
$('.navigation li a').click(function(e) {
e.preventDefault();
$('.navigation li').removeClass('heading selected');
$(this).parent().toggleClass('heading selected');
});
The li element with class "heading selected" is the default/selected element.
What I want to achieve after clicking on the other li element:
<li><a href="index.php?action=sliderimages" title="">Slider images</a></li>
<li class="heading selected">Static pages</li>
in short, remove "heading selected" list class from the default one, assing this class to the newly clicked element, also, add anchor href to the default one, and remove anchor tag from the newly clicked element.
Thanks in advance guys! :)
A: To make this somewhat more simple to implement, I'd suggest you don't add/remove the a elements from the li, and simply use CSS to style the elements as 'default text', and JS to prevent the default behaviour.
You can use this as a guide:
$('.navigation li a').click(
function(){
if ($(this).is('.headingSelected')) {
return false;
}
else {
$(this)
.closest('li')
.siblings()
.removeClass('headingSelected');
$(this).closest('li').addClass('headingSelected');
return false;
}
});
JS Fiddle demo.
Note that I've concatenated your 'heading selected' class names into one single, camel-cased, 'headingSelected', also, in the linked demo, I had to guess what the URL of the first link should be. So be aware of that if you should try a direct copy/paste.
Edited to address my misconception that this was used for intra-page navigation, or Ajax interaction.
The following seems to work, but will need to be included in all pages that require the functionality (Whether in-line in the head of the document or via a linked js file):
var currentURL = "http://www.yourwebsite.com/index.php?action=staticpages";
var page = currentURL.substring(currentURL.indexOf('=') + 1);
$('.navigation a').each(
function(i){
if ($(this).text().toLowerCase().replace(' ','') == page) {
$(this).closest('li').addClass('headingSelected');
}
});
JS Fiddle demo.
If you should use the above, simply ensure that you remove the headingSelected class name from the html, and allow the script to assign the class when it runs.
More concisely, but otherwise exactly the same as the previously edited answer, you could use instead:
var currentURL = "http://www.yourwebsite.com/index.php?action=staticpages";
var page = currentURL.substring(currentURL.indexOf('=') + 1);
$('a[href$="' + page + '"]').closest('li').addClass('headingSelected');
JS Fiddle demo.
References:
*
*click().
*is().
*closest().
*siblings().
*removeClass().
*addClass().
*substring().
*indexOf().
*each().
*text().
*toLowerCase().
*attrubte$="value" attribute-ends-with selector.
A: Here you have a solution that will add/remove the a element from the li as David Thomas mentioned.
$('.navigation li a').click(function (e) {
e.preventDefault();
$('.navigation li').removeClass('heading selected');
$('.navigation li').each(function (index) {
if ($(this).children().size() == 0) {
$(this).html("<a href='index.php?action=" + $(this).text().replace(' ', '').toLowerCase() + "'>" + $(this).text() + "</a>")
}
});
$(this).parent().html($(this).text());
$(this).parent().toggleClass('heading selected');
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What type of data can I pull from an iPhone? I have analytics on my phone to get some use info. Right now I get info such as UDID, iOS Version, and hardware version. But what else can I pull?
A: Use a specialist analytics package such as Flurry and you will be provided with a wealth of usage and user information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sandcastle xslt How do I change the output of a Sandcastle built website using xslt? Are there any tutorials on how to do this?
I can go in and change the css but this seems a little the wrong way around...
A: Sandcastle is open source, so you have the chance to tune it to suit your needs,
http://sandcastle.codeplex.com/SourceControl/list/changesets
From its source code you can see which parts are used to generate the web site, and then you can make whatever changes you like.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CSS Table width - 100% + minus margin I've stumbled across an issue that I'm not entirely sure how to resolve.
I have a page with a number of divs, one of which contains a table but has a margin of 20px. I need this table to 'butt' against the right-hand side of another div, which I have accomplished by using a margin of -20px - works as I'd hoped. As this div (which covers the entire right-hand side of the page) is fluid, the table has a width of 100%.
Whilst the left-hand side of the table is where I want it, the right-hand side is now 20px short of everything else.
Is there a way I can keep the negative margin on the right, without it also moving the table 20px from the right? I've tried a few things without success. My table CSS is pasted below.
.pricetable {
width:100%;
margin-left: -20px;
padding: 5px;
}
A: You can also set the width to less than 100% and set margin auto:
.pricetable {
width:90%;
margin: auto;
}
Hope it helps.
A: it is now possible with CSS calc:
.pricetable {
width: calc(100% - 20px);
margin-left: -20px;
padding: 5px;
}
A: You could absolutely position your table, so that it's aligned at the right.
position: absolute;
right: 0;
There's no way to add a left margin without moving the table, because the table offset is calculated in this way: margin + padding + width = offset width.
When you set the width to be 100%, the margin and padding cause the element to expand.
*
*Padding (left) X, (right) y + width = over 100%
*over 100% + negative width (X+y) = 100%.
The first definition adds some padding at each side of the table. The second definition shifts the table to the left, because it's a negative margin.
A: try giving table-layout:fixed and see
A: My solution was to wrap the table inside a div with the negative margin.
<div style="margin-right:-20px">
<table style="width:100%">
...
</table>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Reading vim plugin - strange notation and navigation Im reading great tpope rails.vim and what does it mean:
" }}}1
" Abbreviations {{{1
exactly here: https://github.com/tpope/vim-rails/blob/master/autoload/rails.vim#L3921
Is it for better navigation?
This file is quite huge, how to navigate on it properly - using ctags?
A: These are so called foldmarkers. Vim 6 introduced code folding and the triple braces are the default string to mark the beginning and the end of a fold. In addition, if you prepend the opening mark {{{ with text, it'll show in the collapsed line as a header. This is only one way to fold code. Being a manual method, it is easily controlled and thus preferred by many.
See :h folding and :h fold-marker.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object I am getting the following error when trying to get a JSON request and process it:
org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.myweb.ApplesDO]: can not instantiate from JSON object (need to add/enable type information?)
Here is the JSON I am trying to send:
{
"applesDO" : [
{
"apple" : "Green Apple"
},
{
"apple" : "Red Apple"
}
]
}
In Controller, I have the following method signature:
@RequestMapping("showApples.do")
public String getApples(@RequestBody final AllApplesDO applesRequest){
// Method Code
}
AllApplesDO is a wrapper of ApplesDO :
public class AllApplesDO {
private List<ApplesDO> applesDO;
public List<ApplesDO> getApplesDO() {
return applesDO;
}
public void setApplesDO(List<ApplesDO> applesDO) {
this.applesDO = applesDO;
}
}
ApplesDO:
public class ApplesDO {
private String apple;
public String getApple() {
return apple;
}
public void setApple(String appl) {
this.apple = apple;
}
public ApplesDO(CustomType custom){
//constructor Code
}
}
I think that Jackson is unable to convert JSON into Java objects for subclasses. Please help with the configuration parameters for Jackson to convert JSON into Java Objects. I am using Spring Framework.
EDIT: Included the major bug that is causing this problem in the above sample class - Please look accepted answer for solution.
A: You have to create dummy empty constructor in our model class.So while mapping json, it set by setter method.
A: So, finally I realized what the problem is. It is not a Jackson configuration issue as I doubted.
Actually the problem was in ApplesDO Class:
public class ApplesDO {
private String apple;
public String getApple() {
return apple;
}
public void setApple(String apple) {
this.apple = apple;
}
public ApplesDO(CustomType custom) {
//constructor Code
}
}
There was a custom constructor defined for the class making it the default constructor. Introducing a dummy constructor has made the error to go away:
public class ApplesDO {
private String apple;
public String getApple() {
return apple;
}
public void setApple(String apple) {
this.apple = apple;
}
public ApplesDO(CustomType custom) {
//constructor Code
}
//Introducing the dummy constructor
public ApplesDO() {
}
}
A: Regarding the last publication I had the same problem where using Lombok 1.18.* generated the problem.
My solution was to add @NoArgsConstructor (constructor without parameters), since @Data includes by default @RequiredArgsConstructor (Constructor with parameters).
lombok Documentation
https://projectlombok.org/features/all
That would solve the problem:
package example.counter;
import javax.validation.constraints.NotNull;
import lombok.Data;
@Data
@NoArgsConstructor
public class CounterRequest {
@NotNull
private final Integer int1;
@NotNull
private final Integer int2;
}
A: I would like to add another solution to this that does not require a dummy constructor. Since dummy constructors are a bit messy and subsequently confusing. We can provide a safe constructor and by annotating the constructor arguments we allow jackson to determine the mapping between constructor parameter and field.
so the following will also work. Note the string inside the annotation must match the field name.
import com.fasterxml.jackson.annotation.JsonProperty;
public class ApplesDO {
private String apple;
public String getApple() {
return apple;
}
public void setApple(String apple) {
this.apple = apple;
}
public ApplesDO(CustomType custom){
//constructor Code
}
public ApplesDO(@JsonProperty("apple")String apple) {
}
}
A: You must realize what options Jackson has available for deserialization. In Java, method argument names are not present in the compiled code. That's why Jackson can't generally use constructors to create a well-defined object with everything already set.
So, if there is an empty constructor and there are also setters, it uses the empty constructor and setters. If there are no setters, some dark magic (reflections) is used to do it.
If you want to use a constructor with Jackson, you must use the annotations as mentioned by @PiersyP in his answer. You can also use a builder pattern. If you encounter some exceptions, good luck. Error handling in Jackson sucks big time, it's hard to understand that gibberish in error messages.
A: If you start annotating constructor, you must annotate all fields.
Notice, my Staff.name field is mapped to "ANOTHER_NAME" in JSON string.
String jsonInString="{\"ANOTHER_NAME\":\"John\",\"age\":\"17\"}";
ObjectMapper mapper = new ObjectMapper();
Staff obj = mapper.readValue(jsonInString, Staff.class);
// print to screen
public static class Staff {
public String name;
public Integer age;
public Staff() {
}
//@JsonCreator - don't need this
public Staff(@JsonProperty("ANOTHER_NAME") String n,@JsonProperty("age") Integer a) {
name=n;age=a;
}
}
A: This happens for these reasons:
*
*your inner class should be defined as static
private static class Condition { //jackson specific
}
*It might be that you got no default constructor in your class (UPDATE: This seems not to be the case)
private static class Condition {
private Long id;
public Condition() {
}
// Setters and Getters
}
*It could be your Setters are not defined properly or are not visible (e.g. private setter)
A: When I ran into this problem, it was a result of trying to use an inner class to serve as the DO. Construction of the inner class (silently) required an instance of the enclosing class -- which wasn't available to Jackson.
In this case, moving the inner class to its own .java file fixed the problem.
A: Generally, this error comes because we don’t make default constructor.
But in my case:
The issue was coming only due to I have made used object class inside parent class.
This has wasted my whole day.
A: Thumb Rule: Add a default constructor for each class you used as a mapping class. You missed this and issue arise!
Simply add default constructor and it should work.
A: Can you please test this structure. If I remember correct you can use it this way:
{
"applesRequest": {
"applesDO": [
{
"apple": "Green Apple"
},
{
"apple": "Red Apple"
}
]
}
}
Second, please add default constructor to each class it also might help.
A: Add default constructors to all the entity classes
A: Failing custom jackson Serializers/Deserializers could also be the problem. Though it's not your case, it's worth mentioning.
I faced the same exception and that was the case.
A: For me, this used to work, but upgrading libraries caused this issue to appear. Problem was having a class like this:
package example.counter;
import javax.validation.constraints.NotNull;
import lombok.Data;
@Data
public class CounterRequest {
@NotNull
private final Integer int1;
@NotNull
private final Integer int2;
}
Using lombok:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.0</version>
</dependency>
Falling back to
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
Fixed the issue. Not sure why, but wanted to document it for future.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "473"
} |
Q: Undefined variable notice in PHP code I'm getting
"Undefined variable: html in on line $html .= generateOption($optstyle.'option', $level, $data, $padding);"
What's wrong with my function?
function generateOptions($parent, $level, $padding, $menu, $db)
{
$result=$db->query("SELECT id, name FROM menu WHERE parent='$parent' AND showinmenu='$menu'");
$spacer = ' ';
$padding = str_repeat($spacer, $level);
while($data=$result->fetch_row()){
$children_html = generateOptions($data[0], $level+1, $padding, $menu,$db);
$optstyle = empty($children_html) ? 'std' : 'bold';
$html .= generateOption($optstyle.'option', $level, $data, $padding); (this line)
$html .= $children_html;
}
return $html;
}
A: You didn't define $html before you tried to use it.
Try adding $html = ""; after $padding = str_repeat($spacer, $level);
A: You'll have to initialise the $html before you start appending to it. Think about $html .= something like $html = $html . something and you should see the issue.
Also, your query is insecure. Make sure you escape everything - just in case.
A: Just declare the variable first before appending to it. Using the dot operator just appends content. If you simply use $html = ''; before your loop the warning should be gone.
A: function generateOptions($parent, $level, $padding, $menu, $db)
{
$html = ''; # define `$html` first
$result = $db->query("SELECT id, name FROM menu WHERE parent='$parent' AND showinmenu='$menu'");
$spacer = ' ';
$padding = str_repeat($spacer, $level);
while($data = $result->fetch_row())
{
$children_html = generateOptions($data[0], $level+1, $padding, $menu,$db);
$optstyle = empty($children_html) ? 'std' : 'bold';
$html .= generateOption($optstyle.'option', $level, $data, $padding);
$html .= $children_html;
}
return $html;
}
As mentioned by others, you should escape your $parent and $menu variables to prevent SQL injection.
A: begin the code with this :
$html = "";
A: in begin line insert code
if (!isset($html)) {
$html = '';
};
A: $html .= generateOption($optstyle.'option', $level, $data, $padding); (this line)
$html .= $children_html;
Remove the dot in front of the first = in the first line.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625784",
"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.