text stringlengths 8 267k | meta dict |
|---|---|
Q: Rails 3: Duplicate validation error messages during testing I'm getting some weird validation behavior: it's duplicating my validation error messages and I can't figure out what's causing it... it doesn't do this in the rails console.
Here is the validation from my Phone model:
# phone.rb
validates :number, :length => { :minimum => 3 }
My spec:
require 'spec_helper'
describe Phone do
it "requires a number" do
user = User.make!
@p = Phone.new(number:nil,user_id:user.id,type:2)
@p.valid?
puts @p.errors.inspect
@p.should have(1).error_on(:number)
end
My test results:
# rspec and machinist
#<ActiveModel::Errors:0x000000036f1258 @base=#<Phone id: nil, user_id: 614, kind: nil, number: nil, created_at: nil, updated_at: nil>, @messages={:number=>["is too short (minimum is 3 characters)", "is too short (minimum is 3 characters)"]}>
F
Failures:
1) Phone requires a number
Failure/Error: @p.should have(1).error_on(:number)
expected 1 error on :number, got 2
# ./spec/models/phone_spec.rb:11:in `block (2 levels) in <top (required)>'
Finished in 0.50988 seconds
1 example, 1 failure
As you can see, I'm getting "is too short (minimum is 3 characters)" twice... It's also /only/ happening during testing.
Any ideas?
Thanks!
A: The problem is in the line:
Dir["#{Rails.root}/app/**/*.rb"].each { |f| load f }
in the spec_helper.rb file, in the Spork.each_run block
If you change the method 'load' to 'require', it fixes the problem.
Or if you have a recent enough version of Spork, you can remove the line altogether.
I am pretty sure the error is caused when someone is installing a newer version Spork(0.9.0+) with old instructions, because the line:
Dir["#{Rails.root}/app/**/*.rb"].each { |f| load f }
doesn't even has to be stated explicitly in the spec_helper.rb file anymore. If it is then when the load method is used in the spec_helper.rb file, it reloads the files specified , most likely the cause of the strange RSpec duplicate validations errors.
A: I encountered a similar issue of duplicate error messages, but it seemed to stem from my use of a different directory structure than the standard, e.g.:
- app
\- models_one
|- models_two
|- models_three
My load/require call in the Spork.each_run block looked like this:
Dir["#{Rails.root}/app/models_*/*.rb"].each { |f| load f }
I removed this and replaced it with these:
ActiveSupport::Dependencies.clear
ActiveRecord::Base.instantiate_observers
And there were no more duplicate error messages.
I was helped by this post: http://adams.co.tt/blog/2012/04/12/duplicate-active-model-validation-errors/ in which the author says it's a 1.8.7-specific problem which involves requiring different paths which resolve to the same file, but I am using 1.9.3 so it may not be related.
A: I'm not sure if this is going to solve your problem, but rspec is very quirky if you don't follow rspec convention. Try some more idiomatic rspec like the following:
require 'spec_helper'
describe Phone do
context :validations do
let(:user) { double(:user) }
subject { Phone.new(number:nil,user_id:user.id,type:2) }
before do
subject.valid?
end
it 'should have a minimum length of 3' do
subject.should have(1).error_on(:number)
end
end
end
I'd also like to suggest that you shouldn't unit test Rails' built in validations; they are already tested in Rails itself. Specifically, your length validation is tested in activemodel/test/cases/validations/length_validation_test.rb. The behavior of the validations should be covered in your integration tests.
I hope that's helpful.
A: I'm having the same problem (using rspec & spork).
I suspect it's something to do with the model being required twice, causing validations to run twice.
If you explicity require 'phone' at the top of your spec, it seems to fix it.
But I'd really like to know what's causing the problem...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Combining function and callback parameter to create new function I have a wrapper around the jQuery animate function, which accepts a callback parameter to fire after the animation is completed. I want to "build" that callback by combining a user-passed callback and internal code. For example, the user passes function Foo as his callback. I want the actual callback to be function Foo(); function Bar(); where function Bar() is internally defined. Here's an example of what I'm trying to achieve:
MainSubController.prototype.changeMain = function($newMain, subWinCallback) {
$mainWinCpy.animatePositionChange(lastSubWinPos, this.subWinSize,
function() {self.subWins.push($mainWinCpy); subWinCallback(); });
}
I think I could do it by building an intermediary partial function, but I'm not sure, and if I could, I don't know how to go about doing it.
Edit: The problem with the above code is that subWinCallback is not executed, or, it's not executing at the right time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Html.BeginForm() with GET method How can I specify that my form should be using GET method with @Html.BeginForm() ?
@using (Html.BeginForm(method: FormMethod.Get))
Here VS complains that best overload doesn't have a parameter method. Thank you!
A: There is an overload that allows you to specify the method:
@using (Html.BeginForm("someAction", "someController", FormMethod.Get))
{
...
}
A: Decorate the controller's action method with [HttpGet]. This is the controller action that this form will submit to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: Get Redmine custom field value to a file I'm trying to create a text file that contains the value of a custom field I added on redmine. I tried to get it from an SQL query in the create method of the project_controller.rb (at line 80 on redmine 1.2.0) as follows :
sql = Mysql.new('localhost','root','pass','bitnami_redmine')
rq = sql.query("SELECT value
FROM custom_values
INNER JOIN projects
ON custom_values.customized_id=projects.id
WHERE custom_values.custom_field_id=7
AND projects.name='#{@project.name}'")
rq.each_hash { |h|
File.open('pleasework.txt', 'w') { |myfile|
myfile.write(h['value'])
}
}
sql.close
This works fine if I test it in a separate file (with an existing project name instead of @project.name) so it may be a syntax issue but I can't find what it is. I'd also be glad to hear any other solution to get that value.
Thanks !
(there's a very similar post here but none of the solutions actually worked)
A: First, you could use Project.connection.query instead of your own Mysql instance. Second, I would try to log the SQL RAILS_DEFAULT_LOGGER.info "SELECT ..." and check if it's ok... And the third, I would use identifier instead of name.
A: I ended up simply using params["project"]["custom_field_values"]["x"] where x is the custom field's id. I still don't know why the sql query didn't work but well, this is much simpler and faster.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: problem with while loop here is the script I wrote but it seems it has problem with while ! while suppose to compare the content of K with SDATE and while they are not equal go to the loop !
for d in \
$(sed -nre 's/.*\[(..)\/(...)\/(....):(..:..:..) .*/\1 \2 \3 \4/p' thttpd.log | date +%s -f-);
do echo $d >s1; done
time=$(expr 60 \* 60 \* 24 \* 5)
EDATE=`tail -1 s1`
SDATE=$[$EDATE - $time]
time=$(expr 60 \* 60 \* 24 \* 5)
EDATE=`tail -1 s1`
SDATE=$[$EDATE - $time]
k=`tail -1 s1`
echo $k
echo $SDATE
while [$k -ne $SDATE](k and SDATE contain numbers)
do
k=`tail -1 s1`
sed '1d' < s1 > tempfile
mv s1 s1.old
mv tempfile s1
echo $K| awk '{print strftime("%d/%m/%Y:%T",$1)}'|tee -a ass
done
A: Try this:
while [[ $k != $SDATE ]]
A: The problem is that you do not have spaces around [ or ]. Which causes BASH to parse the line incorrectly.
With the following line, BASH will attempt to run the program [$K, probably not what you are intending.
while [$k -ne $SDATE]
What you need to have is the following:
while [ $k -ne $SDATE ]
A: Ah, shell programming is so touchy...
k=0
while [ $k != 4 ]; do echo $k; k=`expr $k + 1`; done
Works and prints 0, 1, 2, 3 on separate lines as expected and this essentially looks like what you have except for spaces, newlines, and sources of values. Maybe it is a string versus value problem but I did not think shell variables had types.
I would try stripping what you have back until it works then add back what you want it to do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Form inputs inside jQuery draggable objects are uneditable I'm trying to put a form inside an element, on which jQuery sortable is active. There's a DIV element, which is movable (with jQuery sortable), an IMG element, which is used as a handler for moving the DIV and FORM element with inputs inside. Both FORM and IMG els are inside the DIV. Problem is, that inputs inside the form can't be edited. When I turn sortable off, it works fine.
Am I doing something wrong or is it a bug? Is there a way to fix it?
Thank you kindly
A: I had this same issue. I got the sortable code from the jquery-ui website, and it had the following line of jquery code:
$( "#sortable" ).disableSelection();
once I commented this out, I was able to edit my forms again. It may work for you. I'm sure this will cause me other headaches (
A: The solution to this is to just bind a click handler to the form elements after the sortable call and then within the event handler set the focus to 'this', e.g.:
jQuery('.sortable-list input[type=text]').click(function(){ jQuery(this).focus(); });
A: I've made a workaround. Because I'm using ajax to load and send the form, I simply don't run the code to make things sortable when the form (with all els to be sortable) is loaded, then when it is sent I make it sortable again. Not solution, but made the job for me.
A: Try this:
//For disable
$("input, select, textarea").bind('mousedown.ui-disableSelection selectstart.ui-disableSelection', function(e){
e.stopImmediatePropagation();
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: calling functions returned as pointers from other functions in ctypes I'm trying to use ctypes to call a c function that was returned as a pointer from another function. It seems from the documentation that I can do this by declaring the function with CFUNCTYPE, and then creating an instance using the pointer. This, however seems to give me a segfault. Here is some sample code.
sample.c:
#include <stdio.h>
unsigned long long simple(void *ptr)
{
printf("pointer = %p\n", ptr);
return (unsigned long long)ptr;
}
void *foo()
{
return (void *)simple;
}
unsigned long long (*bar)(void *ptr) = simple;
int main()
{
bar(foo());
simple(foo());
}
and simple.py:
from ctypes import *
import pdb
_lib = cdll.LoadLibrary('./simple.so')
_simple = _lib.simple
_simple.restype = c_longlong
_simple.argtypes = [ c_void_p ]
_foo = _lib.foo
_bar = CFUNCTYPE(c_int, c_void_p)(_foo())
pdb.set_trace()
_bar(_foo())
Here's a gdb/pdb session:
(gdb) r
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /usr/bin/python simple.py
[Thread debugging using libthread_db enabled]
> .../simple.py(15)<module>()
-> _bar(_foo())
(Pdb) p _foo()
-161909044
(Pdb) cast(_bar,c_void_p).value
18446744073547642572L
(Pdb) _simple(_foo())
pointer = 0xfffffffff65976cc
-161909044
(Pdb) int('fffffffff65976cc',16)
18446744073547642572L
Curiously, if I run using the C main function, I get
$ ./simple
pointer = 0x400524
pointer = 0x400524
which doesn't match the pointer that I get from the python code.
What am I doing wrong here?
Thanks in advance for any guidance you can give!
A: You are not defining any return type for _foo, try adding:
_foo.restype = c_void_p
ctypes defaults to int returntype, and it looks (from the cast done in you pdb session) like you are on a 64-bit system meaning that you pointer will be truncated when converted to int. On my system the code seems to work - but that is a 32-bit system (and unfortunately I don't have any 64-bit system available to test on right now).
Also you _bar definition doesn't really match what is in the C code, I suggest using something like:
_bar = CFUNCTYPE(c_longlong, c_void_p).in_dll(_lib, "bar")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Adding Jira comment using soap in PHP How to add comment in Jira using SOAP in PHP?
A: $soapClient = new SoapClient("https://YOUR_JIRA_DOMAIN.com/rpc/soap/jirasoapservice-v2?wsdl");
$token = $soapClient->login($username, $password);
$soapClient->addComment($token, $issueKey, array('body' => "your comment"));
References
*
*http://docs.atlassian.com/software/jira/docs/api/rpc-jira-plugin/latest/com/atlassian/jira/rpc/soap/JiraSoapService.html#addComment%28java.lang.String,%20java.lang.String,%20com.atlassian.jira.rpc.soap.beans.RemoteComment%29
*https://bitbucket.org/rewbs/satellites-talk-samples/src/cd22351cf368/IssuesFromFilter.php
*http://codingx.blogspot.com/2011/04/play-with-jira-api-from-php.html
*http://confluence.atlassian.com/display/JIRA03x/Creating+a+SOAP+Client
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Python binary-data ascii error when encoding in multipart I'm using this cookbook recipe to encode images in a multipart form data to upload to Twitter.
When I run the code to pack the image in a django shell everything runs fine (even the print statements that I used to debug the post body with binary data) but when I try to run the same script from a django Command or a much simpler pure-python script I keep getting this error:
body = '\r\n'.join(body)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
So, why is this happening only when I run a script and not from the shell/CLI?
Thanks for everyone who can enlighten me into this :)
A: I think this is related to this question.
Does the answer provided there help you?
A: I found out that it was related to the results of my query.
They were returned in unicode and I used that value to create the path to my image, like:
image_path = "/my/path/%s.jpg" % model.name
model.name was something like u'model1' I printed out these values and removed the u' notation (by the old method of replacing :P) from the strings all worked fine.
What left me very frustrated is that the error pointed to '\r\n'.join and never to something related to the name of my file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to write just one 0x0A character to STDOUT in Ruby on Windows? How to write just one 0x0A character to STDOUT in Ruby on Windows. Just one, without 0x0D.
@EDIT: Thanks to all! I knew about binary/text mode concept but have no idea how to deal with this in Ruby interpreter. The solution is to use STDOUT.binmode.
There is an open question how than switch STDOUT back to text mode using platform independent code.
A: This is due to the "virtual newline". At the (Ruby) IO layer this feature is responsible for mapping "\n" (0x0A, LF) to/from the Operating Systems definition of a newline. Windows maps "\n" to CR+LF (whereas "\n" is mapped unchanged to LF in Unix-like systems).
Use ios.binmode to put the stream into binary mode which disables the "virtual newline" mode. This is also very important to do for dealing with binary streams such as images ;-)
Happy coding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: PHP/CSS can't get element to sit over a table? I have a div relatedListings that contains a table of customer's orders.
I want to add a heading above it, I have tried h3, div, and span but it always puts the element below the table.
The code that generates the table:
echo '<div id="relatedListings">
<h3 id="relatedListingsHeader">Customer\'s Listings</h3>' .
$account->listAds() .
'</div>';
The actual source from the browser after executed:
<table id='customerAds'>
<!-- Generated table data -->
</table><div id="relatedListings">
<h3 id="relatedListingsHeader">Customer's Listings</h3></div>
Notice in the second snippet, the div is AFTER the table. Any ideas?
EDIT: here is the listAds method:
echo "<table id='customerAds'>
<tr><th>Ad</th><th>Title</th><th>Description</th><th>Ad Date</th><th>Actions</th></tr>";
while ($ad = $ads->fetch()) {
echo "<tr id='row_{$ad['idAds']}'>
<td>{$ad['idAds']}</td>
<td>{$ad['Title']}</td>
<td>" . substr(strip_tags($ad['Description']), 0, 100) . "...</td>
<td>" . format::dateConvert($ad['DatePosted'], 12) . "</td>
<td><a href='#'>Delete</a></td>
</tr>";
}
echo "</table>";
A: I would venture to guess that $account->listAds() is echo-ing as well and not returning instead. If you can change that function to return instead you should be better off.
Update:
Now having seen your updated code - I'd suggestion having that function return a string - instead of using echo like you are
$tableCode = "<table id='customerAds'>
<tr><th>Ad</th><th>Title</th><th>Description</th><th>Ad Date</th><th>Actions</th></tr>";
while ($ad = $ads->fetch()) {
$tableCode .= "<tr id='row_{$ad['idAds']}'>
<td>{$ad['idAds']}</td>
<td>{$ad['Title']}</td>
<td>" . substr(strip_tags($ad['Description']), 0, 100) . "...</td>
<td>" . format::dateConvert($ad['DatePosted'], 12) . "</td>
<td><a href='#'>Delete</a></td>
</tr>";
}
$tableCode .= "</table>";
return $tableCode;
A: Your generated table data may be malformed, causing the browser to try and fudge the markup into what it thinks you meant. Since you didn't include that markup, I couldn't tell for sure. It would also be helpful to see the code from $account->listAds().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MVC Right separation for functional component I am building a Web application that allow people to subscribe to certain classes which are divided by semesters.
In one of my interface I have a list of all activities that act as a summary in the backend interface. I was looking to group them by semester and browse through a sequential navigation.
My problem is, where should I put my code since I want it to be easy to maintain and I want to respect the right MVC structure.
Here are my Ideas:
*
*Get the param value in the controller, get the previous and next semester through an
action helper, send the data to the view and then display it
or
*Get the param value in the controller, sent it to the view, let the view (through a
view helper) find the previous and next semester and then display it
I have a class that is able to find the semesters through calculation (so it's not in my models)
A: The first option. Your question is unclear to me, but your first option sounds the closest to what I would do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Grid with named RowDefinition fails to populate as ItemsPanel in WPF4 I have a Grid defined in an ItemsControl ItemsPanelTemplate, and one of RowDefinitions has a x:Name defined (so I could animate the row size).
<ItemsControl ItemsSource="{Binding Data, Source={StaticResource model}}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition x:Name="t" />
<RowDefinition />
</Grid.RowDefinitions>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
This worked fine in 3.5, however when we recently upgraded to 4.0 it all fell apart. What I would see is a Grid with the defined Row and Column definitions but no children.
If I set IsItemsHost=true on the Grid, everything starts working. If I add an x:Name to the Grid itself, or remove the x:Name from the RowDefinition it all works.
<ItemsPanelTemplate>
<Grid IsItemsHost="True">
<Grid.RowDefinitions>
<RowDefinition x:Name="t" />
<RowDefinition />
</Grid.RowDefinitions>
</Grid>
</ItemsPanelTemplate>
or
<ItemsPanelTemplate>
<Grid x:Name="g">
<Grid.RowDefinitions>
<RowDefinition x:Name="t" />
<RowDefinition />
</Grid.RowDefinitions>
</Grid>
</ItemsPanelTemplate>
This seems like a bug, but I wanted to check with the community and see if people agreed, or if I've overlooked something. I could not find anything on Connect or the web, so can anyone explain what I'm seeing?
A: I don't believe this is a bug. What you have done here is inadvertently introduced a bug in your code that does not throw an exception at design or compile time but at run-time, hence your animation did not complete and the content of the grid was not rendered.
The conflict is in the WPF XAML Namescope particular to DataTemplate as described in this MSDN article. The article does state that named elements within a template is automatically given a unique Namescope to prevent the name conflict, but it does not tell us what happens when the template root is unnamed but contains named children or how the IsItemsHost affects the ItemsTemplate.
*
*One approach I can suggest is to use your original scenario and during debugging, keep an eye on your output log for any runtime exceptions that has been quietly nerfed by the XAML parser related to your animation.
*Another (personally I think, better) approach would be to create a new 'templated control' that inherits from the ItemsControl. Here, you can access the ItemsPanel during the ApplyTemplate over-load to find your Grid/GridColumn and perform the animation there. Here is a good tutorial.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: jQuery add elements to empty selection? Why doesn't this work?
var spans = $();
var elem = document.getElementById('someId');
spans.add(elem);
What is the proper way to start off with an empty collection and add elements to it?
I want to loop through a collection of ids and find the element on the page and add it to the matched set.
A: I guess I don't get what you're asking. If you have an element and you want to add it to a collection, you just use the .add() method just like you've already shown. What confuses some is that this returns a new jQuery object so you would do it like this:
var spans = $();
var elem = document.getElementById('someId');
spans = spans.add(elem);
Of course, something like this would be shorter:
var spans = $();
spans = spans.add('#someId');
And, of course, you don't have to start with an empty object. You would just start with:
var spans = $('#someId');
A: Quoting from the jQuery website:
Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method.
Hence, when you do .add() it will not save the added elements, you would have to explicitly assign the element to the newly created object i.e
var $elements = $('.elements');
$elements = $elements.add($('#anotherelement'));
A: If you're looking to push or add items selected from a jQuery object, you could also do this:
var $els = $(),
$someEls = $(".some-els");
$els.push.apply($els, $someEls);
Just another way to do it.
A: What you actually want to do is use jQuery to it's full potential. You can use selectors to grab and create the collection right away. Your three lines above becomes one line:
var spans = $('#someId');
to add more ids to the collection, you can separate them with commas:
var spans = $('#someId1, #someid2, #someid3');
A: The .add() method returns a new jQuery object, so you'd need to overwrite the old one:
spans = spans.add( elem );
...or since you're adding DOM elements, you can modify the existing jQuery object with .push().
spans.push( elem );
EDIT: Changed .pushStack() to .push(), though I don't know if .push() is officially supported.
You could use .pushStack() to add a collection though.
spans = spans.pushStack( [elem] );
or
spans = spans.pushStack( document.getElementsByTagName('div') );
A: There may be better ways to do what you're trying, but if you just want to create an empty jQuery object, use this:
var $foo = $([]);
Edit: I should clarify - your code actually should work, unless you're using an older version of jQuery, in which case $() would create a collection containing the document object. In newer versions, however, there's nothing wrong with that. The code snippet I pasted above is just something that should work in older versions and newer versions of jQuery.
Edit 2: In response to this portion of the question: "I want to loop through a collection of ids and find the element on the page and add it to the matched set", the following code might be useful:
var ids = ['foo', 'bar', 'baz'],
selector = $.map(ids, function(i, id) {
return '#' + id;
}).join(','),
$collection = $(selector);
A: While this doesn't directly answer the question of "how to append to an existing jQuery selection", I have a work-around for this particular use-case.
You can pass an array of DOM elements to jQuery, and it will create a jQuery selection out of them.
var spansArray = [];
var elem = document.getElementById('someId');
spansArray.push(elem);
var spans = $(spansArray);
I can't think of any reason why you would need to add each element to the jQuery selection one-at-a-time, as opposed to all-at-once, so this should be a "drop-in-replacement" for your use case. In theory, this must also prove more efficient, as jQuery's .add() is ultimately just calling .push() on some array behind the scenes.
A: Try
var spans = $("<span />");
var elem = $("#someId").html();
spans.append(elem).appendTo('#someAnotherId');
instead
A: The reason your code doesn't work is because add does not change the collection, it returns a new jQuery object with the new elements in it. If you wanted, you could instead say spans = spans.add(elem);, but what you're doing is unnecessary: the beauty of jQuery is that it makes this sort of imperative programming unnecessary. Look at helloandre's answer for a much easier way to accomplish your goal.
It's like the following, if this makes sense:
var x = [1, 2, 3];
x.concat(4);
console.log(x); // [1, 2, 3] -- concat does not mutate the original array
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
} |
Q: How to make the Force Close window display friendly app name instead of a package name? I think it is possible to replace the Java package name in Force Close window in Android with a more readable application name. I cannot find any information how to do it or recall where I saw it, however. I tried to search on Google and SO without luck. I have labels for both activity and application tags in my Manifest.
Is it possible to setup a custom application name in FC window, and if it is, how to do it?
A: There is a way to set a global exception handler, which will catch any exception which is caused on that thread. So you set it in your main activity and it will apply to every subactivity.
But! Don't ever do that to suppress exceptions and simply show a dialog because it looks nicer (I would even affirm that this would be the most dumb idea of all you can have since you're disabling a basic feature which is there to help you to fix exceptional behavior). It's not what the handler is there for! Usually the handler invokes the previous default handler to preserve the default exception handling. It only wants the crash info.
I wrote that because of this answer. No offence! It's only a big fat warning to attempt to force wrong behavior.
final UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
// get the crash info
defaultHandler.uncaughtException(thread, ex);
}
});
A: This currently isn't possible without modifying code at the system level. What you may have seen, however, is a custom error handler by an application. If you surround the bulk of your application code with a large try / catch block, you could pop up your own dialog informing the user of an error (with the application name and text of your choosing, of course). This would have to be done for each separate activity though, and its much better practice to simply avoid FCs altogether (hire a test group?).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SQL query to find rows with at least one of the specified values Suppose you had two tables. One called MOVIES:
*
*MovieId
*MovieName
Then another called ACTORS that contains people who appear in those movies:
*
*MovieId
*ActorName
Now, I want to write a query that returns any movie that contains ONE OR MORE of the following actors: "Tom Hanks", "Russell Crowe" or "Arnold Schwarzenegger".
One way to do it would be something like:
SELECT DISTINCT A.MovieId, M.MovieName FROM ACTORS A
INNER JOIN MOVIES M USING (MovieId)
WHERE A.ActorName IN ('Tom Hanks', 'Russell Crowe', 'Arnold Schwarzenegger');
Which is perfectly fine, however in my case I might have several more of these conditions on the WHERE clause so I want to find a way to make the MOVIES table the primary table I select from.
What's the best way to query for this? I'm using Oracle 11g if that matters, but I'm hoping for a standard SQL method.
A: First you should have a 3rd table implementing the n:m relationship:
CREATE TABLE movie (
movie_id int primary key
,moviename text
-- more fields
);
CREATE TABLE actor (
actor_id int primary key
,actorname text
-- more fields
);
CREATE TABLE movieactor (
movie_id int references movie(movie_id)
,actor_id int references actor(actor_id)
,CONSTRAINT movieactor_pkey PRIMARY KEY (movie_id, actor_id)
);
Then you select like this:
SELECT DISTINCT m.movie_id, m.moviename
FROM movie m
JOIN movieactor ma USING (movie_id)
JOIN actor a USING (actor_id)
WHERE a.actorname IN ('Tom Hanks', 'Russell Crowe', 'Arnold Schwarzenegger');
Note, that text literals are enclose in single quotes!
A: You can use EXISTS or IN subqueries:
SELECT *
FROM MOVIES m
WHERE EXISTS
(
SELECT *
FROM ACTORS a
WHERE a.MovieId = m.MovieId
AND a.ActorName IN ('Tom Hanks', 'Russell Crowe', 'Arnold Schwarzenegger')
)
or
SELECT *
FROM MOVIES m
WHERE m.MovieId IN
(
SELECT a.MovieId
FROM ACTORS a
WHERE a.ActorName IN ('Tom Hanks', 'Russell Crowe', 'Arnold Schwarzenegger')
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Android + ListFragment with a custom view hierarchy I'm attempting to customize the fragment layout by returning my own view hierarchy from onCreateView(LayoutInflater, ViewGroup, Bundle). This inflates my custom view, but seems to stack the views instead of inflating within, I see everything at once. Any help is appreciated.
MyActivity.java:
public class MyActivity extends FragmentActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
ArrayListFragment list = new ArrayListFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, list).commit();
}
}
public static class ArrayListFragment extends ListFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
inflater.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.main, container);
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String List[] = {"Larry", "Moe", "Curly"};
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, List));
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="THIS IS A BUTTON" />
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
<TextView
android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="No data" />
</LinearLayout>
A: I wasn't returning the new view within the onCreateView method of the ListFragment class. For instance:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, null);
return view;
}
All works well now in the land of Android!
A: I think you'd better
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.main, container, false);
return root;
}
A: optimized way and shot code
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list_alphabet, container, false);
}
A: getSupportFragmentManager().beginTransaction().add(android.R.id.content, list).commit();
List is not accepted, it's looking for a fragment.
A: use this pattern, works perfectly!
inflater.inflate(R.layout.list_layout, container, false);
public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)
attachToRoot Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: NSData to file PHP I have NSData that I am 'POST'ing to a PHP file on my site, from that NSData, I am writing it to a file. However, the file's contents are the string of NSData (range of letters and numbers) rather than the parsed data. How can I parse the NSData to a string in PHP and then write the contents of that string to a file?
Here is my code so far:
$filename = $_POST['username'] . "_iCal_" . $newID . ".ics";
$File = $upload_path . $filename;
$Handle = fopen($File, 'w');
$Data = urldecode($_POST['ical']);
$Data = str_replace (" ", "", $Data);
fwrite($Handle, $Data) or die("s");
fclose($Handle) or die("s");
[NSKeyedArchiver archivedDataWithRootObject:event] //event is an NSObj-- Subclass with NSCoding etc... implemented
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:MPiCalUpload_URL]];
[request setTimeOutSeconds:MPiCalRetriever_timeout];
[request setPostValue:_username forKey:@"username"];
[request setPostValue:data forKey:@"ical"];
A: Consider passing the data as a Base64 string. Search SO for "NSData Base64", you'll find plenty of examples. Then on the PHP side, use base64_decode() to get the bytes back.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Debugging missed broadcast datagrams, which show up in wireshark, but not in C# app? I have two machines A1 and A2, both of which are running the same embedded code, which broadcast packets. The third machine, B3, is a Windows XP box running a C# (.NET 4.0) app, which listens for those broadcasts.
All of the data from A1 is received by the C# as expected, 95% of the data from A2 is received with intermittent, seemingly random, lost UDP datagrams.
When I look on wireshark on B3, all of the packets from both machines arrive exactly as expected, but when I dump the bytes to a text file immediately after receiving them, I see that datagrams from B2 are missing.
How can it be that a packet is displayed on wireshark, but does not get passed to my C# app, some of the time? I could understand if the datagram had bad headers, etc., but Wireshark shows everything as expected, even for these missing ones. Does Windows / .NET perform some check that Wireshark does not by default?
A: I would recommend dumping the B2 stream into a file, and then replaying it directly to your app (using a local app, if possible). You should benefit from having a constant data stream in order to (hopefully) narrow down the problematic part.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to (efficiently) convert int[] to Integer[]? Is there any direct way to convert int array to Integer array with out looping element by element.
Brute force way will be
int [] a = {1,2,3};
Integer [] b = new Integer[a.length];
for(i =0; i<a.length; i++)
b[i]= i;
Is there any direct way with out traveling the entire array?
A: You've found the "only" way to do it using pure Java. I prefer to make the Integer construction explicit, via
int[] a = {1,2,3};
Integer[] b = new Integer[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = Integer.valueOf(a[i]);
}
Note that Apache has some utilities in Apache Lang, which basically do the same thing; however, the call looks more like
Integer[] newArray = ArrayUtils.toObject(oldArray);
Of course, if you don't include the Apache libraries, you could write your own static function to make the code look pretty (if that's your concern).
A: There's noting built in JDK but if you have apache commons, you could use
Integer[] ArrayUtils.toObject(int[] array)
A: There are third-party libraries which will do the dirty work for you, but they're just going to loop under the covers.
E.g. with Guava:
int[] primitives = {1,2,3};
List<Integer> boxed = Ints.asList(primitives);
Integer[] boxedArray = Ints.asList(primitives).toArray(new Integer[]);
They don't give a one-method conversion presumably because you probably shouldn't be using arrays anyway but rather a List.
A: That's really the only way. When you're doing b[i] = i Java is auto unboxing your int to Integer. However that doesn't work when going from an int-array to an Integer-array.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What's an appropriate design pattern for this hierarchical class structure? I have a class that instantiates a hierarchy of classes. The interface should hide all of the internal hierarchy by presenting a single class reference. (An the interface to the classes at intermediate levels should hide internal implementation details the same way.) I am having a little difficulty deciding how to flow the interface parameters down to the lowest levels and to flow state changes up to the top level. What I have come up with gets messy.
I have seen some discussions of the blackboard pattern but, from what I have seen, it looks ad hoc and flat rather than hierarchical. (Although flat vs hierarchical may not be important.)
The class I have is a calendar view, subclasing UIView. The hierarchy includes a header class, a grid class (instantiated more than once), a tile class (instantiated many times), plus some helper classes. It's based on Keith Lazuka's kal calendar in Objective C. I've decided to reorganize it for my needs, and wanted to rethink this part of it before I introduce problems with flexibility.
My question is in the title.
A: I have decided that the KVO (Key Value Observer) design pattern makes sense for bubbling state information from the lower levels to the top. Only that state information that needs to flow up is observed at each of the corresponding layers.
In this application, a tapped tile event is sent to the observer at the next level up (the grid level), telling it that the user has selected a date, which is a property of the tile class.
At the grid level, it changes its state based on its current state and the new information that it's observer receives from the tile. (In my calendar, the user can select a range of dates by choosing start date and end date, and can continue tapping tiles to change his date range selection.) This changes state at the grid level translates into a change in the start and/or the end date, so an NSDictionary property is updated.
At the calendar level, an observer sees the startDate/endDate dictionary change. Regardless of which grid this came from (there are two grids, and only one of them is active at a time. The tiles and the calendar do not need to be aware of this) the calendar's start and end dates are updated.
The calendar is a view that is planted into one of the other views of the application, initialized with a month to be shown, and with a selected date range (start and stop dates). Information is flowed down from the top though the pointers to each of the immediate subviews at any layer. Those subviews take care of keeping their subviews configured. I have eliminate the need to add explicitly add delegate methods or callbacks, and that has simplified the connections from top to bottom. Connections only go the the immediate level above or below in the hierarchy.
This may not seem like much after all, because it looks rather straightforward. But it wasn't clear until I spent awhile thinking about it. I hope it gives others some ideas for their own code. I would still like to know if there are other suggestions responding to my question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is my controller not ordering by what Im telling to order by? My controller action is calling all images belonging to a specific user and Im trying to order by its position (Im using the acts_as_list gem) but when I go to the page, the images are FIRST sorted by the created date, and then position (according to rails console). But because it orders by the creation date first my controller order is being ignored which is no good.
here is my action
def manage_tattoos
@tattoos = current_member.tattoos.order("position DESC")
end
and my server console shows:
Tattoo Load (0.6ms) SELECT `tattoos`.* FROM `tattoos` WHERE
(`tattoos`.member_id = 1) ORDER BY tattoos.created_at DESC, position DESC
A: Have you tried specifiing the order in the association?
class TodoList < ActiveRecord::Base
has_many :todo_items, :order => "position"
end
A: Does your association between Member and Tattoo have an order clause? E.g.
# Member class
has_many :tattoos, :order => "created_at DESC"
Is this the case? If so you might need to change your query to something like:
Tattoo.where(:member_id=>current_member.id).order("position DESC")
I'm unaware of a way to clear the order clause from an ActiveRecord association.
A: Or specify what to do with created_at:
current_member.tattoos.order("position DESC, created_at DESC")
A: Well it seems Im just very absent minded and had completely forgotten that I set a default scope on the model. Took that out and everything is fine
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: security for cookies If I sign-up to a website and the website sends me a cookie with and ID with which it can identify me, can somebody else impersonate me if they get hold of this cookie?
If somebody else knows the format of the cookie and guesses the ID can they impersonate me this way?
Also, any material where these things are discussed is appreciated.
A: The answer to both questions is a qualified "yes". But, both impersonations can be made very difficult. Things that make it difficult to steal a session Id from a cookie:
*
*Using https. All communications between you and the server are encrypted and very difficult to hack.
*If the server is using PHP sessions, the ID in the cookie is lengthy and difficult to guess.
*Even without these, to intercept a cookie is difficult since the perpetrator must make his/her computer listen for transmissions to/from your IP address or the server IP.
Best security is long IDs (a la PHP sessions) combined with usage of https.
If you're developing, here's some good info: http://thinkvitamin.com/code/how-to-create-totally-secure-cookies/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: onCreate() is not called by getWritableDatabase() I am writing a database in my android app, but my tables aren't being created. I added break points at my onCreate method, and my getWriteableDatabase, and getWritableDatabase is called, but onCreate is not.
package com.fslade.app;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "applicationdata";
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_TABLE = "peopleT";
// Database creation sql statement
private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE + " (_id integer primary key autoincrement, "
+ "company_name text not null, name text not null, city text not null, vertical text not null, title text not null, email text not null, bio text not null, photo text not null, status text not null);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
// Method is called during an upgrade of the database, e.g. if you increase
// the database version
@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
Log.w(DatabaseHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS todo");
onCreate(database);
}
}
And in my database helper I call getWriteableDatabse():
package com.fslade.app;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class ContentStorageHelper {
public static final String KEY_ID = "_id";
public static final String KEY_COMPANY_NAME = "company_name";
public static final String KEY_PERSON_NAME = "name";
public static final String KEY_CITY = "city";
public static final String KEY_VERTICAL = "vertical";
public static final String KEY_TITLE = "title";
public static final String KEY_EMAIL = "email";
public static final String KEY_BIO = "bio";
public static final String KEY_PHOTO = "photo";
public static final String KEY_STATUS = "status";
private static final String[] COLUMNS = { KEY_ID, KEY_COMPANY_NAME,
KEY_PERSON_NAME, KEY_CITY, KEY_VERTICAL, KEY_TITLE, KEY_EMAIL,
KEY_BIO, KEY_PHOTO, KEY_STATUS };
private Context context;
private SQLiteDatabase database;
private DatabaseHelper dbHelper;
public ContentStorageHelper(Context context) {
this.context = context;
}
public ContentStorageHelper open() throws SQLException {
dbHelper = new DatabaseHelper(context);
database = dbHelper.getWritableDatabase();
// dbHelper.onCreate(database);
// I added this onCreate() to see if it helped, but when I ran it
// it said that the database had already been created
return this;
}
public void close() {
dbHelper.close();
}
/**
* Create a new person If the person is successfully created return the new
* rowId for that person, otherwise return a -1 to indicate failure.
*/
public long createPerson(String company_name, String name, String city,
String vertical, String title, String email, String bio,
String photo, String status) {
ContentValues initialValues = createContentValues(company_name, name,
city, vertical, title, email, bio, photo, status);
return database.insert(DatabaseHelper.DATABASE_TABLE, null,
initialValues);
}
/**
* Return a Cursor over the list of all people in the database
*
* @return Cursor over all notes
*/
public Cursor fetchPeopleByVertical(String vertical) {
String selection = KEY_VERTICAL+"="+vertical;
Cursor result = database.query(DatabaseHelper.DATABASE_TABLE, COLUMNS,
selection, null, null, null, null);
return result;
}
private ContentValues createContentValues(String company_name, String name,
String city, String vertical, String title, String email,
String bio, String photo, String status) {
ContentValues values = new ContentValues();
values.put(KEY_COMPANY_NAME, company_name);
values.put(KEY_PERSON_NAME, name);
values.put(KEY_CITY, city);
values.put(KEY_VERTICAL, vertical);
values.put(KEY_TITLE, title);
values.put(KEY_EMAIL, email);
values.put(KEY_BIO, bio);
values.put(KEY_PHOTO, photo);
values.put(KEY_STATUS, status);
System.out.print("test: " + status);
return values;
}
}
A: The creation only happens once (that's the whole sense of an database helper).
Did you check whether your database was created? It's located at /data/data/your.package.name/databases/dbname.
If you clear your application data in the android application settings, your onCreate should be called again...
A: It's a rather stupid implementation limitation. :-) Make sure the database name has a .db extension. onCreate() will not be called if it has no extension.
A: SQLiteOpenHelper.onCreate() is called back after SQLiteOpenHelper.getWritableDatabase() (or after SQLiteOpenHelper.getReadableDatabase() ) only when the database does not exist in the application's persistent storage (ie. SD card). In other words, onCreate() is called only once, if the code successfully creates a database - which is stored in persistent storage. If the database exists in persistent storage, but you're changing its schema,
you use SQLiteOpenHelper.onUpgrade(), which is called back when you open a database by name but with a version number that wasn't used before. In which you drop the old schema objects, and then in which you can call SQLiteOpenHelper.onCreate() to create your new schema. And if you want to run code whenever the database is opened (code called back by SQLiteOpenHelper.get[Writable,Readable]Database() ), implement onOpen() . Then call a method that initializes your database (or code initialized against your database) that's called from each of SQLiteOpenHelper.onCreate() and SQLiteOpenHelper.onOpen().
For example, you might want to use a reference to the SQLiteDatabase , against which to call data management methods like SQLiteDatabase.execSQL() .
In each of
SQLiteOpenHelper.onCreate(SQLiteDatabase db)
and
SQLiteOpenHelper.onOpen(SQLiteDatabase db)
call something like
void initDB(SQLiteDatabase db)
{
this.db = db;
}
There are other object lifecycle events that callback handlers in your code that you should handle, as Android multitasks your process. But at a minimum your database handling code has to handle SQLiteOpenHelper.onCreate() and SQLiteOpenHelper.onOpen().
A: I had the same problem. I fund 2 solutions
*
*Restart the emulator and check 'Wipe user Data'
My emulator is slow restarting so ...
*Change the Version Number of your database and it called 'OnCreate' again and gave me a curret version of my database. I lost the stored info (no big Deal)
Good Luck
A: I was having the same problem. I had forgotten a space in between two sql commands in my SQL_Create string and so the column I needed wasn't implemented correctly, but when I found and fixed the error in the String, it didn't fix the issue, because the App already registered that database as having that table. So onCreate was never called. For me, the simplest solution was to update the version number. This created a new db and table (correctly), and fixed the app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Can't assign to mapType::const_iterator? ("no operator = matches") typedef map<string,int> mapType;
mapType::const_iterator i;
i = find_if( d.begin(), d.end(), isalnum );
at the '=' i am getting the error:
Error:no operator "=" matches these operands
I know that find_if returns an iterator once the pred resolves to true, so what is the deal?
A: The documentation for std::find_if
We can only guess at the error as you have only provided half the problem.
Assuming d is mapType and the correct version of isalnum
The problem is that the functor is being passed an object to mapType::value_type (which is how the map and all containers store their value). For map the value_type is actually a key/value pair actually implemented as std::pair<Key,Value>. So you need to get the second part of the object to test with isalnum().
Here I have wrapped that translation inside another functor isAlphaNumFromMap that can be used by find_if
#include <map>
#include <string>
#include <algorithm>
// Using ctype.h brings the C functions into the global namespace
// If you use cctype instead it brings them into the std namespace
// Note: They may be n both namespaces according to the new standard.
#include <ctype.h>
typedef std::map<std::string,int> mapType;
struct isAlphaNumFromMap
{
bool operator()(mapType::value_type const& v) const
{
return ::isalnum(v.second);
}
};
int main()
{
mapType::const_iterator i;
mapType d;
i = std::find_if( d.begin(), d.end(), isAlphaNumFromMap() );
}
A: If d is a map, then the problem is with your attempted use of isalnum.
isalnum takes a single int parameter, but the predicate called by find_if receives a map::value_type. The types are not compatible, so you need something that adapts find_if to `isalnum. Such as this:
#include <cstdlib>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
typedef map<string,int> mapType;
bool is_alnum(mapType::value_type v)
{
return 0 != isalnum(v.second);
}
int main()
{
mapType::const_iterator i;
mapType d;
i = find_if( d.begin(), d.end(), is_alnum );
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to instantiate and populate a Scala Stream in Java? I have a Scala function foo(bs : Stream[Bar]) : Bat that I need to call from Java code. How do I create the "bs" Stream (Stream[Bar]) in Java and lazily generate its Bar objects?
A: Depending on what needs to be in the stream, it might be easiest to create a java.util.Iterator and then convert this to a Stream via a scala.collection.Iterator:
import scala.collection.JavaConverters;
import scala.collection.immutable.Stream;
...
List<String> list = new ArrayList<String>();
\\ Fill the list somehow...
Iterator<String> it = list.iterator();
Stream<String> stream = JavaConverters.asScalaIteratorConverter(it)
.asScala().toStream();
The iterator doesn't have to come from a collection, of course—we can just as easily create an infinite stream by implementing our own iterator:
Stream<String> stream = JavaConverters.asScalaIteratorConverter(
new Iterator<String>() {
int i = 0;
public boolean hasNext() { return true; }
public void remove() { throw new UnsupportedOperationException(); }
public String next() { return Integer.toString(i++); }
}
).asScala().toStream();
It's not as pretty as something like Stream.iterate(0)(_ + 1).map(_.toString), but it works.
A: The best way is to use one of the factories available on Stream object companion. For the most useful of them, you'll need to implement Function1 as well, which can be done by extending AbstractFunction1.
Here's an example:
import scala.collection.immutable.Stream;
import scala.runtime.AbstractFunction1;
public class Ex {
public Stream<Integer> stream = Stream.iterate(0, new Increment());
}
class Increment extends AbstractFunction1<Integer, Integer> {
public Integer apply(Integer v1) {
return v1 + 1;
}
}
A: Have you tried
scala.collection.immutable.Stream bs = new scala.collection.immutable.Stream()
?
A: I know you were looking for scala stream but there is functional java too: http://functionaljava.googlecode.com/svn/artifacts/3.0/javadoc/fj/data/Stream.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Django database model "unique_together" not working? I want my ip and stream_id combination to be unique, so I wrote this model:
# Votes
class Vote(models.Model):
# The stream that got voted
stream = models.ForeignKey(Stream)
# The IP adress of the voter
ip = models.CharField(max_length = 15)
vote = models.BooleanField()
unique_together = (("stream", "ip"),)
But for some reason it produces this table, skipping the ip
mysql> SHOW CREATE TABLE website_vote;
+--------------+---------------------------------------------+
| Table | Create Table |
+--------------+---------------------------------------------+
| website_vote | CREATE TABLE `website_vote` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`stream_id` int(11) NOT NULL,
`ip` varchar(15) NOT NULL,
`vote` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `website_vote_7371fd6` (`stream_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 |
+--------------+---------------------------------------------+
1 row in set (0.00 sec)
Why doesn't it include ip in the key? For the record I am aware that the unique_together line can be written without nesting the tuples, but that has no bearing on the issue
A: unique_together needs to be in the models Meta class. See docs.
class Vote(models.Model):
# The stream that got voted
stream = models.ForeignKey(Stream)
# The IP adress of the voter
ip = models.CharField(max_length = 15)
vote = models.BooleanField()
class Meta:
unique_together = (("stream", "ip"),)
Also, there's a builtin IPAddressField model field. See the docs here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: BLToolkit - Current readiness for Azure Does anybody know if BLToolkit has been tested and certified for use with Azure Sql and if it supports the dropped connection retry functionality? And if not are there any plans to get it tested and passed?
A: At the time of writing, there is nothing official on the BL Toolkit website, and no issues listed in their issue tracker for Azure.
There are a few other requests (e.g. here and here) that are requesting the same details. At the moment they are unanswered but you could add your weight to them.
Based on this evidence from the official sources I would say that the Toolkit is not Tested or Certified specifically for Azure use.
With the exception of the transient nature of Azure which may require handling of database reconnections, there doesn't seem to be anything obvious that would prevent you from using the Toolkit however.
I would recommend you raise an issue with the developers regarding Azure Testing and Certification while performing a proof of concept test on Azure to determine how to best handle reconnections on Azure for your specific application.
There is recent activity on the project, so I'd be quite hopeful of a response.
A: I wrote Azure Sql Data Provider for BLToolkit. You can find its sources on github.
Also it's available over NuGet. Please, see how to install and configure it here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: De-authorize a Facebook app using the new OpenGraph API I have this code to de-authorize my FB application for currently logged in user:
FB.api({ method: 'Auth.revokeAuthorization' });
It's using the deprecated REST API. How do I do the same using the OpenGraph API with FB.api method?
A: I figured it out:
FB.api("/me/permissions", "delete", function(response){});
A: In graph API you can issue HTTP DELETE request to
https://graph.facebook.com/_UID_/permissions
this should deauthorize the app
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Programmatically adding text labels to a family of curves
Possible Duplicate:
How do I label different curves in Mathematica?
Using Mathematica, I would like to programmatically add text labels to each member of a family of curves. I'd prefer not to use a legend. Here's an example:
f[x_, a_] := a*x
myplot = Plot[Evaluate@Table[f[x, a], {a, {0.5, 1, 2}}], {x, -5, 5}]
mytext = Graphics[Evaluate@Table[Text["a = " <> ToString[a],
{5, f[5, a]}, {1, 0}], {a, {0.5, 1, 2}}]]
Show[myplot, mytext]
There has to be a better or more standard way of doing this...right? My hack isn't terribly pretty. The text bleeds into the plot for a = 1 and a = 0.5
I went through the interactive way of adding text labels as outlined by Add Text to a Graphic. I'd really like to do this programmatically though.
What do people do in practice? Do people prefer to interactively add labels because of the potential headache of doing it programmatically?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Removing cdata in simplehtmldom Hello good day I am trying to scrape an xml feed that was given to us, I am using simple htmldom to scrape it but some contents have cdata, how can I remove it?
<date>
<weekday>
<![CDATA[ Friday
]]>
</weekday>
</date>
php
<?php
<?php
include('simple_html_dom.php');
include ('phpQuery.php');
if (ini_get('allow_url_fopen'))
$xml = file_get_html('http://www.link.com/url.xml'); }
else{ $ch = curl_init('http://www.link.com/url.xml');
curl_setopt ($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$src = curl_exec($ch);
$xml = str_get_html($src, false); }
?>
<?php
foreach($xml->find('weekday') as $e)
echo $e->innertext . '<br>';
?>
I believe by default simplehtmldom removes the cdata but for some reason it doesn't work.
Kindly tell me if you need any info that would be helpful to solve this issue
Thank you so much for your help
A: You can make use of another xml parser that is able to convert cdata into a string (Demo):
$innerText = '<![CDATA[ Friday
]]>';
$innerText = (string) simplexml_load_string("<x>$innerText</x>"));
Extended code-example based on OP's code
# [...]
<?php
foreach($xml->find('weekday') as $e)
{
$innerText = $e->innertext;
$innerText = (string) simplexml_load_string("<x>$innerText</x>");
echo $innerText . '<br>';
}
?>
Usage instructions: Locate the line which contains the foreach and then compare the original code with the new code (only the foreach in question has been replaced).
A: I agree with the other answer - just allow CDATA to be shown. I'd recommend simpleXML
$xml = simplexml_load_file('test.xml', 'SimpleXMLElement', LIBXML_NOCDATA);
echo '<pre>', print_r($xml), '</pre>';
LIBXML_NOCDATA is important - keep that in there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Understanding UIGraphicsGetCurrentContext() I'm trying to understand Quartz and getting the context you have to draw on. If I have a function where I create a context, but then I call another function to some other drawing to the same context, do I need to pass the context from the first method to the next? Or can I just use UIGraphicsGetCurrentContext() for any CG methods that require a context since I'm still drawing into the same context?
A: The docs for UIGraphicsGetCurrentContext() say:
The current graphics context is nil by default. Prior to calling its
drawRect: method, view objects push a valid context onto the stack,
making it current. If you are not using a UIView object to do your
drawing, however, you must push a valid context onto the stack
manually using the UIGraphicsPushContext(_:) function.
So after calling UIGraphicsPushContext() with the context you've created, your other methods can access that context with UIGraphicsGetCurrentContext(). If you're calling UIGraphicsGetCurrentContext() outside of drawRect: and haven't set a context explicitly with UIGraphicsPushContext(), the current graphics context is undefined—and certainly not safe to use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: C# how to use Regex.replace, to replace all the pattern matches with the target string Yes, I want to search and replace all the occurrences of the pattern and replace them with a target string. I am trying to use Regex.Replace(src, pattern, target), is there a flag like \g to put in pattern to make it work, or what?
A: There is no \g or concept of a global search, as the .NET Regex class is global by default. In other words, it should just work, assuming you've written your regular expression properly.
You might want to test it in Regex Hero and then once you've got it working click the .NET button at the top to get the code with properly escaped strings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Zend render static / dynamic with multi controllers I'm pretty new to Zend (read the documents concerning routers and controllers).
My StaticController and IndexController :
class StaticController extends Zend_Controller_Action
{
public function displayAction()
{
$page = $this->getRequest()->getParam('filename');
$this->render($page);
}
}
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$albums = new Application_Model_DbTable_Albums();
$this->view->albums = $albums->fetchAll();
}
public function registerAction()
{
...
}
}
application.ini :
resources.router.routes.staticpage.route = /:filename
resources.router.routes.staticpage.defaults.controller = static
resources.router.routes.staticpage.defaults.action = display
My static content urls are : site.com/faq site.com/privacy ...
These work, however others, such as site.com/register uses the StaticController rather than the IndexController, I can't say that I suprised by this behavior.
These static pages (about us, terms and cond...) need to be included in the zend logic for .po translation.
I can think of many diffrent ways to achieve this outside the Zend framework, but would really like to do it the proper zend way.
How can I distinguish static and dynamic content, and still keep pretty urls?
Any help would be much appreciated !
A: You could do it this way :
resources.router.routes.staticpages.route = "/:filename"
resources.router.routes.staticpages.defaults.controller = static
resources.router.routes.staticpages.defaults.action = display
resources.router.routes.staticpages.reqs.filename="(list|of|static|pages)"
If you don't know what 'reqs' is, it's very simple. For each param specified in 'reqs' you specify the regexp it should match in order to use this route.
But I personally would use an action per static page instead of a param in a single action, which would require this route :
resources.router.routes.staticpages.route = "/:action"
resources.router.routes.staticpages.defaults.controller = static
resources.router.routes.staticpages.reqs.action="(list|of|static|pages)"
It's planning that you may one day require different logic for rendering some your static pages
A: You should consider using a prefix for static content so the router knows that you are trying to pull static content and not trying to reference an action in the IndexController.
resources.router.routes.staticpage.route = /static/:filename
resources.router.routes.staticpage.defaults.controller = static
resources.router.routes.staticpage.defaults.action = display
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Close copied worksheet when exporting into CSV I try to save each worksheet of an excel spreadsheet into CSV files. The following script do the job. The line .Parent.Close savechanges:=False is supposed to close the created worksheet but when uncommented the script stops after the first sheet. If I comment the line, all the sheets are processed.
Dim newWks As Worksheet
Dim wks As Worksheet
For Each wks In ActiveWorkbook.Worksheets
wks.Copy 'to a new workbook
Set newWks = ActiveSheet
With newWks
.SaveAs Filename:="C:\home\tmp\base\" & wks.Name & ".txt", FileFormat:=xlTextWindows
.Parent.Close savechanges:=False
End With
Next wks
MsgBox "done with: " & ActiveWorkbook.Name
A: You're closing the activeworkbook. If you want to close the newly created object then do something like this (tested it and it works for me):
Dim newWkb As Workbook
Dim wks As Worksheet
For Each wks In ActiveWorkbook.Worksheets
wks.Copy 'to a new workbook
Set newWkb = ActiveWorkbook
With newWkb
.SaveAs Filename:="C:\home\tmp\base\" & wks.Name & ".txt", FileFormat:=xlTextWindows
newWkb.Close savechanges:=False
End With
Next wks
MsgBox "done with: " & ActiveWorkbook.Name
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Implementing OnTouchListener on LinearLayout - Android Development public class UnitConverterActivity extends Activity implements OnTouchListener {
/** Called when the activity is first created. */
LinearLayout mLinearLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLinearLayout = new LinearLayout(this);
ImageView i = new ImageView(this);
i.setImageResource(R.drawable.mainmenu);
//i.setAdjustViewBounds(false);
i.setScaleType(ScaleType.FIT_XY);
i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mLinearLayout.addView(i);
setContentView(mLinearLayout);
//setContentView(R.layout.main);
}
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
}
I have used the above method to load an image for the main menu I am trying to create. The image has four areas and each will be used to call a particular function of the app. Now I am trying to implement touch interface on those areas. I know how to define the range of pixels for that purpose but I am at loss on how to implement OnTouchListner on the image. Please help me in this regard.
A: If your image was split into four rectangular quarters (say)
then in onCreate have:
i.setOnTouchListener(this);
and for your listener, something like this (illustrates the principle only):
@Override
public boolean onTouch(View v, MotionEvent mev) {
int width = v.getWidth();
int height = v.getHeight();
float x = mev.getX();
float y = mev.getY();
String msg;
if (x < width / 2) {
if (y < height / 2)
msg = "Top left quarter";
else
msg = "Bottom left quarter";
} else {
if (y < height / 2)
msg = "Top right quarter";
else
msg = "Bottom right quarter";
}
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
return false;
}
A: Just put this code in onCreate().
i.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//your code
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Overriding Camel & log4j I'm fairly new to Apache Camel, but have to say that I love it so far. One "limitation" (probably a lack of understanding on my part) I've hit so far is that Camel ships with log4j as its default logging component.
My team has already gone to great lengths to build our own logging framework, which ends up posting all log messages to an ActiveMQ queue, and ultimately, our database.
I'd like to configure Camel to work with our logging framework, since so much has already been invested in getting it working. Although Camel doesn't seem to provide any documentation on this, I do have two ideas and wanted to run them by the SO community.
(1) Find a way to re-configure log4j's LoggerFactory. That way we can have our own LoggerFactory return instances of our homegrown Loggers.
(2) Write our own log4j appender, which would use our homegrown Logger.
Has anyone ever had experience with this? Is there an easier/better/more elegant solution out there? Any input is appreciated.
A: Log4J already provides a JMSAppender. You could be able to just configure one and go. Check out http://activemq.apache.org/how-do-i-use-log4j-jms-appender-with-activemq.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: self invoking function in for loop Here's code from https://github.com/Khan/khan-exercises/blob/master/khan-exercise.js
for ( var i = 0; i < loading; i++ ) (function( mod ) {
if ( !testMode && mod.src.indexOf("/khan-exercises/") === 0 && mod.src.indexOf("/MathJax/") === -1 ) {
// Don't bother loading khan-exercises content in production
// mode, this content is already packaged up and available
// (*unless* it's MathJax, which is silly still needs to be loaded)
loaded++;
return;
}
// Adapted from jQuery getScript (ajax/script.js)
var script = document.createElement("script");
script.async = "async";
for ( var prop in mod ) {
script[ prop ] = mod[ prop ];
}
script.onerror = function() {
// No error in IE, but this is mostly for debugging during development so it's probably okay
// http://stackoverflow.com/questions/2027849/how-to-trigger-script-onerror-in-internet-explorer
Khan.error( "Error loading script " + script.src );
};
script.onload = script.onreadystatechange = function() {
if ( !script.readyState || ( /loaded|complete/ ).test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = undefined;
runCallback();
}
};
head.appendChild(script);
})( urls[i] );
Strange thing: instead of usual for loop code block we see self invoking function!(inside of other self invoking function) Why is that? how will this function run?
A: Basically the for loop runs the function each time with value url[i] passed into the mod parameter.
for ( var i = 0; i < loading; i++ ) (function( mod ) {...The code...})(urls[i]);
if you notice in the code you will see this
(function( mod ) {...The code...})(urls[i])
which is a function call passing urls[i] in to the parameter mod
A: It's an odd construct, but basically if you exclude the {} from a for loop, it will simply run the next line for each iteration, it's similar to excluding {} with an if if you want a one-line if.
So it's basically equivalent to this:
function doSomething(){...}
for ( var i = 0; i < loading; i++ ) {
doSomething(urls[i]);
}
Where doSomething is that large function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What regular expression can validate this type of string? How do I validate this using a regex in js?
first.last.wrt
OR
first.last
Both are part of email addresses, only the name part in the format mentioned above should validated.
Ex: These should validate using the regex:
john.doe.wrt
john.doe
A: If you only want letters/numbers/underscores to validate:
(\w+?)\.(\w+?)(?:\.wrt)?
If you want anything to validate in the "first" and "last" parts:
(.+?)\.(.+?)(?:\.wrt)?
Capture Groups:
*
*First Name
*Last Name
A: if(/^[a-z]+\.[a-z]+(\.wrt)?$/i.test('the string')) {
// It validates!
} else {
// It doesn't...
}
I take it apostrophes and such aren't allowed, but you can add them within the square brackets.
A: /^[a-z]+\.[a-z]+(\.wrt)?$/
Based on your example, this would work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: MongoDB C# mapping domain objects Normally when using Nhibernate I have models in the Nhibernate project, then they are mapped to a UI model to be used and then back, however I have to use merge frequently opposed to update because the mapped model although having the same Id as an existing NhibernateModel it isnt the same object.
On my next project I know MongoDB is going to be the database so I am just wondering if there would be any issues when mapping from UI to Mongo objects? A scenario would be:
*
*User creates an account
*The account is persisted in Mongo
*The user views the account details (a call to mongo, then a map to a UI model)
*The user changes their date of birth
*The user saves their changed account (a map to a mongo model, then a call to mongo to update)
Hopefully this will be a simple answer!
A: One issue you might want to consider with Mongo is that it can accept an update document containing just the few fields you want to change, so instead of saving the entire object back you may end up making separate calls to update individual components of it.
This feature is particularly useful in an AJAX powered application where you have lots of small updates to make. For example, on page load you might fire of a single update to set the user's LastAccessed date, when the click an element in the UI you might update a single field on their record, ...
If you want to use it in a more traditional ORM style you can do that (albeit without the change tracking features you might be used to) but it's worth considering this alternate style.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: django save data in database only when certain conditions are met I have a python function that scrapes some data from a few different websites and I want to save that data into my database only if a certain condition is met. Namely, the scraped data should only be saved if the combination of the location and date field is unique
So in my view I have a new location variable and and date variable and essentially I just need to test this combination of values against what's already in the database. If this combination is unique, then save it. If it's not, then do nothing.
class Speech(models.Model):
location = models.ForeignKey(Location)
speaker = models.CharField(max_lenth=100)
date = models.DateField
I'm pretty new to django so I'm just not sure how to go about executing this sort of database query.
A: You want a combination of two things. First, you want a inner Meta class to enforce the uniqueness in the database:
class Speech(models.Model):
location = models.ForeignKey(Location)
speaker = models.CharField(max_length=100)
date = models.DateField()
class Meta:
unique_together = ('location', 'date')
Then, when you're doing your data manipulation in your view, you want the get_or_create method of the default model manager:
speech, new = Speech.objects.get_or_create(
location=my_location_string,
date=my_datetime_variable,
)
if new:
speech.speaker = my_speaker_string
speech.save()
I hope that gets you started. As always, you know your needs better than I do, so don't blindly copy this example, but adapt it to your needs.
Documentation:
*
*unique_together
*get_or_create
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Where can nightly builds of OpenJDK 7 for Windows be found? I have searched high and low for a CI server or other source for a nightly build of OpenJDK7. I would like this so that I can track the bug fixes and performance improvements being made to hotspot for invokedynamic support.
I have found the instructions for building my own copy, but they are not for the faint of heart (me).
A pointer to an up-to-date build (and a source for more as the days & weeks progress) would be lovely. Anyone?
A: There are no known nightlies available publicly from the OpenJDK project
This open source project provides prebuilt binaries for Mac, Linux and Windows with the IcedTea patches:
https://github.com/alexkasko/openjdk-unofficial-builds/
The downloads are at:
https://bitbucket.org/alexkasko/openjdk-unofficial-builds/downloads/
Some binaries are also available in Maven central at:
http://mirrors.ibiblio.org/maven2/com/alexkasko/openjdk/
A: The openjdk community doesn't produce binaries beyond the RI. It's up to os/platform providers or others to build/produce build the binaries.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: iPad Home Screen Icon Pixelated when inatlled via Ad-Hoc I am testing my app via Ad-Hoc Distribution and have run into a strange problem.
When testing via Xcode to my iOS device everything looks and works exactly as expected; however when installing the app through iTunes (using an IPA file generated in Xcode using the Ad-Hoc Provisiong Profile) the Home Screen icon appears pixelated, as if the wrong size version is being used.
Does anyone know what's going on; is this normal behavior because this is a Ad-Hoc distro?
Any help would be appreciated.
A: For anyone experiencing the same problem; turns out the Simulator that comes with Xcode ignores the case of a file name, while the actual iPad does not. This will lead to the incorrect home screen icon being displayed on the iPad home screen, if the case of the icon name was changed in the directory or Xcode.
I hope this helps some one!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySQL root password change I have been trying to reset my MySQL root password. I have run mysqld_safe --skip-grant-tables, updated the root password, and checked the user table to make sure it is there.
Once restarting the MySQL daemon I tried logging in with the new root password that I just set and still get Access denied for user 'root' errors. I have also tried completely removing and reinstalling MySQL (including removing the my.cnf file) and still no luck. What can I do next?
A: ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';
You can find Resetting the Root Password in the MySQL documentation.
A: For me, only these steps could help me setting the root password on version 8.0.19:
mysql
SELECT user,authentication_string FROM mysql.user;
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_pass_here';
FLUSH PRIVILEGES;
SELECT user,authentication_string FROM mysql.user;
If you can see changes for the root user, then it works.
Source: Can't set root password MySQL Server
A: Have a look at this from the MySQL reference manual:
First log in to MySQL:
mysql -u root -p
Then at the mysql prompt, run:
UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
Then
FLUSH PRIVILEGES;
Look at this page for more information: Resetting the Root Password: Unix Systems
UPDATE:
For some versions of mysql, the password column is no longer available and you'll get this error:
ERROR 1054 (42S22): Unknown column 'Password' in 'field list'
In this case, use ALTER USER as shown in the answer below.
A: You have to reset the password! Steps for Mac OS X (tested and working) and Ubuntu:
Stop MySQL
sudo /usr/local/mysql/support-files/mysql.server stop
Start it in safe mode:
sudo mysqld_safe --skip-grant-tables
(The above line is the whole command.)
This will be an ongoing command until the process is finished, so open another shell/terminal window and log in without a password:
mysql -u root
mysql> UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';
Start MySQL
sudo /usr/local/mysql/support-files/mysql.server start
Your new password is 'password'.
A: Using the mysqladmin command-line utility to alter the MySQL password:
mysqladmin --user=root --password=oldpassword password "newpassword"
Source
A: For the current latest MySQL version (8.0.16), none of these answers worked for me.
After looking at several different answers and combining them together, this is what I ended up using that worked:
update user set authentication_string='test' where user='root';
A: Please follow the below steps.
*
*sudo service mysql stop
*sudo mysqld_safe --skip-grant-tables
*sudo service mysql start
*sudo mysql -u root
*use mysql;
*show tables;
*describe user;
*update user set authentication_string=password('1111') where user='root';
*FLUSH PRIVILEGES;
Log in with password "1111".
A: This is the updated answer for WAMP v3.0.6 and up.
In the MySQL command-line client, phpMyAdmin or any MySQL GUI:
UPDATE mysql.user
SET authentication_string=PASSWORD('MyNewPass')
WHERE user='root';
FLUSH PRIVILEGES;
In MySQL version 5.7.x there is no more password field in the MySQL table. It was replaced with authentication_string. (This is for the terminal/CLI.)
In the MySQL command-line client, phpMyAdmin or any MySQL GUI:
UPDATE mysql.user SET authentication_string=PASSWORD('MyNewPass') WHERE user='root';
FLUSH PRIVILEGES;
A: I searched around as well and probably some answers do fit for some situations,
my situation is Mysql 5.7 on a Ubuntu 18.04.2 LTS system:
(get root privileges)
$ sudo bash
(set up password for root db user + implement security in steps)
# mysql_secure_installation
(give access to the root user via password in stead of socket)
(+ edit: apparently you need to set the password again?)
(don't set it to 'mySecretPassword'!!!)
# mysql -u root
mysql> USE mysql;
mysql> UPDATE user SET plugin='mysql_native_password' WHERE User='root';
mysql> set password for 'root'@'localhost' = PASSWORD('mySecretPassword');
mysql> FLUSH PRIVILEGES;
mysql> exit;
# service mysql restart
Many thanks to zetacu (and erich) for this excellent answer (after searching a couple of hours...)
Enjoy :-D
S.
Edit (2020):
This method doesn't work anymore, see this question for future reference...
A: I tried the answer from kta, but it didn't work for me.
I am using MySQL 8.0.
This worked for me in the MySQL command-line client (executable mysql):
SET PASSWORD FOR 'root'@'localhost' = 'yourpassword'
A:
This is for Mac users.
On 8.0.15 (maybe already before that version) the PASSWORD() function does not work. You have to do:
Make sure you have Stopped MySQL first (above).
Run the server in safe mode with privilege bypass:
sudo mysqld_safe --skip-grant-tables
Replace this mysqld_safe with your MySQL path like in my case it was
sudo /usr/local/mysql/bin/mysqld_safe –skip-grant-tables
then you have to perform the following steps.
mysql -u root
UPDATE mysql.user SET authentication_string=null WHERE User='root';
FLUSH PRIVILEGES;
exit;
Then
mysql -u root
ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'yourpasswd';
A: Now just use:
SET PASSWORD FOR <user> = '<plaintext_password>'
Because 'SET PASSWORD FOR <user> = PASSWORD('<plaintext_password>')' is deprecated and will be removed in a future release.(Warning in 04/12 2021)
Please use SET PASSWORD FOR <user> = '<plaintext_password>' instead.
Update 04/12 2021 AM 2:22:07 UTC/GMT -5 hours.
Use the following statement to modify directly in the mysql command line:
mysql> SET PASSWORD FOR'root'@'localhost' = PASSWORD('newpass');
or 1.The terminal enters the bin directory of MySQL
cd /usr/local/mysql/bin
2.Open MySQL
mysql -u root -p
3.At this time you can use your default password
4.Perform operations in MySQL at this time
show databases;
5.You will be prompted to reset the root user password.
So how to reset the root password? I checked a lot of information but it didn’t take effect.
Including entering to modify the database in safe mode, using the mysqladmin command:
"Mysqladmin -u root password"your-new-password""
etc.,
Will not work.
The correct steps are as follows:
1.It is still in the cd /usr/local/mysql/bin/ directory
2.sudo su
After entering, you will be asked to enter your computer password.
When you enter it, nothing is displayed. After you enter it, press Enter
Then press enter
3.Cross the authorization verification
sh-3.2# ./mysqld_safe --skip-grant-tables &
If the execution of the command is stopped, and the execution has been completed at this time,
press Enter directly, and then exit to exit:
sh-3.2# exit
4.Re-enter MySQL at this time, no -p parameter, no password
./mysql -u root
5.Select the database MySQL (here MySQL refers to a database in MySQL,
there are other databases in MySQL, you can view it through show databases;)
use mysql;
6.Update the password of the root user in the database table:
update user set authentication_string=‘123456’ where User='root';
Note: The password field here is authentication_string,
not the password circulated on the Internet.
It is estimated that MySQL was updated later.
Re-enter MySQL and use the password you just set, is it all right?
Because you have just set to bypass the authorization authentication,
you can log in to MySQL directly without a password.
My stupid way is to restart the computer and log in to MySQL with the password again to see if the modification is effective;
A: Update from 2022
I've tried a few of the answer but the one that works for me is the following
ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';
Courtesy of StrongDM
Note: I'm using the MySql client for Windows 10 and I'm also logging as the root user.
A: SET PASSWORD FOR 'root'@'localhost' = PASSWORD('mypass');
FLUSH PRIVILEGES;
A: I found it! I forgot to hash the password when I changed it. I used this query to solve my problem:
update user set password=PASSWORD('NEW PASSWORD') where user='root';
I forgot the PASSWORD('NEW PASSWORD') and just put in the new password in plain text.
A: On MySQL 8.0.4+
To update the current root user:
select current_user();
set password = 'new_password';
To update another user:
set password for 'otherUser'@'localhost' = 'new_password';
To set the password policy before updating the password:
set global validate_password.policy = 0;
set password = 'new_password';
set password for 'otherUser'@'localhost' = 'new_password';
Another / better way to update the root password:
mysql_secure_installation
Do you want to stick with 5.x authentication, so you can still use legacy applications?
In my.cnf file
default_authentication_plugin = mysql_native_password
To update root:
set global validate_password.policy = 0;
alter user 'root'@'localhost' identified with mysql_native_password by 'new_password';
A: On MySQL 8 you need to specify the password hashing method:
ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'new-password';
A: In MySQL 5.7, the password is replaced
with 'authentication_string'. Use
update user set authentication_string=password('myfavpassword') where user='root';
A: So many comments, but I was helped by this method:
sudo mysqladmin -u root password 'my password'
In my case after installation I had got the MySQL service without a password for the root user, and I needed to set the password for my security.
A: This worked for me -
ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';
Chapter 4 Resetting the Root Password: Windows Systems
A: For MySQL 5.7.6 and later:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';
For MySQL 5.7.5 and earlier:
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');
A: A common error I run into from time to time, is that I forget the -p option, so be sure to use:
mysql -u root -p
A: Exit from WAMP and Stop all WAMP services.
Open Notepad and then type:
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('');
Then save it to the C: drive with any name... like this "c:/example.txt"
Now go to your "wamp" folder: wamp → bin → mysql → mysql (your version) → bin
In my case the path is "C:\wamp\bin\mysql\mysql5.6.17\bin".
Now copy your path, run CMD with (Ctrl + R), and then type "cmd" (Enter).
Type cd, right click on CMD, and paste the path (Enter).
Now type (mysqld --init-file=C:\\example.txt) without braces and (Enter).
Then restart the PC or open Task Manager and kill mysqld.exe.
Start WAMP and your password will be removed...
A: For macOS users, if you forget your root password, thusharaK's answer is good, but there are a few more tricks:
If you are using a system preference to start MySQL serverside, simply
sudo mysqld_safe --skip-grant-tables
might not work for you.
You have to make sure the command-line arguments are the same with the system start configuration.
The following command works for me:
/usr/local/mysql/bin/mysqld --user=_mysql --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data --plugin-dir=/usr/local/mysql/lib/plugin --log-error=/usr/local/mysql/data/mysqld.local.err --pid-file=/usr/local/mysql/data/mysqld.local.pid --keyring-file-data=/usr/local/mysql/keyring/keyring --early-plugin-load=keyring_file=keyring_file.so --skip-grant-tables
You can use
ps aux | grep mysql
to check your own.
A: Or just use interactive configuration:
sudo mysql_secure_installation
A: Resetting root password.
*
*sudo mysql --defaults-file=/etc/mysql/debian.cnf
*alter user 'root'@'localhost' identified with mysql_native_password by 'new_password';
A: *
*On Mac open system preferences MySQL.
*In the configuration section of MySQL, check for "Initialize Database".
*Change the password in the prompt.
A: On Ubuntu,
sudo dpkg-reconfigure mysql-server-5.5
Replace 5.5 with your current version and you will be asked for the new root password.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "178"
} |
Q: Android custom dialler on tapping phone number links I have to implement custom dialler application. Well it will not make regular phone call, instead it will connect to some service to estabilish VoIP connection. That is simple part I think I can handle it. But the other part is a bit tricky for me. I want to "register" my dialler somehow in the system to have it in context menu when you click on a phone number link in an e-mail for example. Now, when you click the number, default dialler appears. I want context menu to be shown where you can select if you want to use phone or my dialler. Is it possible? Can someone provide me some more tips?
OK. I know I have to create some intent-filter for that. Here is what I did but it does not work. Still no "My App" in the context menu when clicking phone number in some e-mail message.
<intent-filter android:priority="100">
<action android:name="android.intent.action.CALL_PRIVILEGED" />
<action android:name="android.intent.action.DIAL" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="tel" />
<data android:scheme="callto" />
</intent-filter>
A: Tha answer for your question is:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.DIAL" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="tel" />
</intent-filter>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem with TRandomStream - Delphi TurboPower LockBox 3 I am using TurboPower LockBox 3 (http://sourceforge.net/projects/tplockbox/ and http://lockbox.seanbdurkin.id.au/tiki-index.php)
I have a problem with the TRandomStream. I'm trying to generate a chunk of 32 byte random data, but the output does not seem to be random.
The code is:
function StringToHex(S: String): String;
var I: Integer;
begin
Result:= '';
for I := 1 to length (S) do
Result:= Result+IntToHex(ord(S[i]),2)+' ';
end;
procedure TForm1.btn1Click(Sender: TObject);
const
Len = 32;
var
j,k: Integer;
P: Pointer;
Str: AnsiString;
begin
GetMem(P,Len);
TRandomStream.Instance.Randomize;
SetLength(Str,Len);
for j := 1 to 20 do
begin
TRandomStream.Instance.Read(P^,Len);
for k := 0 to Len-1 do
begin
Str[k+1]:=PAnsiChar(P)[k];
end;
mmoOutput.Lines.Add('> '+StringToHex(Str));
end;
FreeMem(P,Len);
end;
The output is:
> 91 79 00 77 FD F7 1C 51 22 64 BA 07 9F 87 8F B2 85 94 92 84 6B F7 5B 55 1A 0D DE E5 44 4A 56 DA
> A5 A6 C3 3D DB 01 69 61 5A 66 D8 ED 3F 3B 4D 00 A5 D7 CB 84 BB 40 CE 3E 5A 90 54 DD BF 63 0E 2C
> A5 5F 75 70 76 1F 08 25 5A E0 8D F0 9C 0B 15 F7 A5 9F C1 A7 F9 7C FF BA 5A 60 58 60 B5 97 F4 25
> A5 9F 23 E2 09 D2 74 52 5A 60 AC 5E 6E D8 B6 81 A5 9F 33 B5 2B B8 B5 15 5A 60 4C 51 96 DB 68 66
> A5 9F B3 4D 3A 51 4C 0D 5A 60 4C E6 D5 4C F8 83 A5 9F B3 11 AF 19 DB 2D 5A 60 4C 8E D2 D6 49 70
> A5 9F B3 31 55 5D D1 28 5A 60 4C CE B7 26 56 C8 A5 9F B3 31 86 7A 83 A0 5A 60 4C CE E1 A5 B8 E8
> A5 9F B3 31 0E 64 14 5E 5A 60 4C CE 31 9F CC EB A5 9F B3 31 4E B0 9B 4A 5A 60 4C CE B1 69 6C 04
> A5 9F B3 31 4E 12 D6 AE 5A 60 4C CE B1 BD 6A C9 A5 9F B3 31 4E 22 A9 D0 5A 60 4C CE B1 5D 5D F1
> A5 9F B3 31 4E A2 41 DF 5A 60 4C CE B1 5D F2 30 A5 9F B3 31 4E A2 05 54 5A 60 4C CE B1 5D 9A 2D
> A5 9F B3 31 4E A2 25 FA 5A 60 4C CE B1 5D DA 12 A5 9F B3 31 4E A2 25 2B 5A 60 4C CE B1 5D DA 3C
> A5 9F B3 31 4E A2 25 B3 5A 60 4C CE B1 5D DA 8C A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C
> A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C
> A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C
> A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C
> A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C
> A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C
> A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C
> A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C
> A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C
> A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C A5 9F B3 31 4E A2 25 F3 5A 60 4C CE B1 5D DA 0C
Which does not seem to be random.
What am I doing wrong?
Thanks and regards.
A: OK. I've found the problem and a fix. Procedure TRandomStream.Crunch uses Compiler Version switching:
For Compiler Version > 17
FValue := FValue * Factor + 1 ;
Whilst for Compiler Version <= 17 (which is my case), the use of the function SquarePlus1Int64_NoOverflowChecks equates to:
FValue := FValue * FValue + 1;
To fix change:
function SquarePlus1Int64_NoOverflowChecks(Factor: int64): int64;
begin
result := Factor * Factor + 1
end;
to
function MultiplyPlus1Int64_NoOverflowChecks(Value,Factor: int64): int64;
begin
result := Value * Factor + 1
end;
and in TRandomStream.Crunch change:
FValue := SquarePlus1Int64_NoOverflowChecks(FValue);
to
FValue := MultiplyPlus1Int64_NoOverflowChecks(FValue, Factor);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: UILocalNotification not cancelling after firing My application generates multiple local notifications and while I'm testing it, I see that the app continuously receives the local notification appDelegate message. This is in spite of my having no repeat interval.
<UIConcreteLocalNotification: 0x1574b0>{fire date = (null), time zone = (null), repeat interval = 0, next fire date = 2011-09-23 19:40:35 +0000}
This is the debug value returned at my breakpoint. As you'll notice, there is no data except the next fire date, which shouldn't technically be called because there is no interval. Also, this is the only notification in the SharedApplication LocalNotifications array.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multithreading: C# program running C dll - Unresponsive C# I wrote a C dll that performs two tasks:
1) Relay certain messages to the C# program
2) Perform an intensive task on a different thread
It all works but the C# UI is unresponsive, even though C is running the intensive task on a different thread.
I have also exposed the C function that kicks off the intensive task to C#, allowing C# to attempt to run that function on a different thread.
No matter what, C# gets bogged down and the C# program becomes unresponsive when the intensive task runs.
I forgot to mention that I have written the entire program in C and it works without a problem but I'd like to write a C# library to use this in future .NET projects.
[DllImport(@"C:\projects\math\randomout\Debug\randout.dll", CharSet = CharSet.Auto, EntryPoint = "task_ToggleTask")]
internal static extern bool task_ToggleTask();
__declspec( dllexport ) BOOL task_ToggleTask()
{
if ( _threadStopped )
{
_threadStopped = FALSE;
_t_TaskHandle = ( HANDLE )_beginthread( task_Calculate, 0, NULL );
return TRUE;
}
else
{
_threadStopped = TRUE;
CloseHandle( _t_TaskHandle );
return FALSE;
}
}
static void task_Calculate( void* params )
{
while ( !_threadStopped )
{
WORD nextRestInterval = rand_GetBetween( 15, 50 );
/*
trivial math calculations here...
*/
//next update is at a random interval > 0ms
Sleep( nextRestInterval );
}
_endthread();
}
A: You need to reduce your thread's priority. I'm assuming though this happens to your system and not just the program. If it happens in your program, are you certain nothing else is going on in your main app thread and that its actually running on a separate thread?
Try reducing the thread's priority - see:
Programmatically limit CPU Usage of a Thread running inside a Service
A: I'll try a general answer, since you haven't specified which C# UI technology you're using (WPF or Winforms), and haven't given any example of your UI code:
I think you'd better off keep your C code as a simple utility library, without trying to do any threading stuff there, and Let the C# code manage the background thread. .Net UI has many threading techniques to keep the UI responsive while doing some long tasks in the background, e.g.: Backgroundworker, Dispatcher.Invoke, Control.Invoke etc... (take a look at this question for example).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: iPhone EXC_BAD_ACCESS with NSMutableArray of strings Problem context is a ViewController with several button handlers and a scores.list data file of 1000 NSString objects. If I click on buttonOne, the handler code checks if the file scores.list exists in the User Documents directory. If yes, it loads the data in an NSMutableArray called score, if not it creates the NSMutableArray in memory (to be stored on disk later) like this:
- (void)readScores
{
// Setup path + filename pathUserDocDirScorelist);
...
// test for presence scores.list in documents dir
if ([fileManager fileExistsAtPath: pathUserDocDirScorelist])
{ // Read scores.plist into NSMutableArray
score = [NSMutableArray arrayWithContentsOfFile:pathUserDocDirScorelist];
} else { // Initialize empty scores array with 1000 empty NSString entries
score = [[NSMutableArray alloc] init];
int i;
for(i = 0; i < 1000; i++) {
[score addObject:@""];
}
}
// at this point there is always a valid array score with 1000 entries
}
Basically this code works; in both cases (reading data from scores.list or in-mem build-up) I can verify in the debugger (with 'po score') that an array with 1000 entries is present afterwards.
Now comes the problem that is blocking me for 2 days now:
In the handler of buttonTwo, statements like [score count] crash, but only in case the array score gets its data from disk, not if build-up in memory. In the first case is the array still valid though until the last line of handler code of buttonOne, but then 'evaporates' as soon as the array is addressed in a next handler (EXC_BAD_ACCESS).
No, it is not caused by a premature release statement, since there are none (yet) in my entire app. :)
(not concerned with memory leaks yet).
How is this possible that within one view a NSMutableArray is valid at the end of button handler 1, but invalid at the beginning of the next button handler 2 if no explicit release statement is executed in between?
Extra info:
ViewController.h:
@interface ViewController : UIViewController {
NSMutableArray *score;
...
}
@property (nonatomic, retain) NSMutableArray *score;
...
- (IBAction) buttonOne: (id) sender;
- (IBAction) buttonTwo: (id) sender;
@end
And in ViewController.m I have:
@synthesize score;
...
- (IBAction) buttonOne: (id) sender {
if (score == nil) {
[self readScores];
}
...
NSLog(@"Number of entries in score = %i", [score count]); // never crashes
}
- (IBAction) buttonTwo: (id) sender {
NSLog(@"Number of entries in score = %i", [score count]); // **crash point**
}
P.S. I tried NSZombieEnabled by starting the app with alt/cmd/R and adding 'NSZombieEnabled=YES', but that does not result in extra information in the debug console.
A: It's always a little dangerous to do this:
score = [[NSMutableArray alloc] init];
outside of an init method. Because, the problem is that perhaps your method readScores is executed twice. I'd guess it almost certainly is.
What happens then is the the first scores object is never released. That causes a memory leak and sooner or later you get the dreaded EXC_BAD_ACCESS.
So, the best thing is either to first check:
if (score)
{
[score release];
}
Or, alternatively, set up scores as a synthesized retained object in your .h file. Then you can replace your code as follows and let everything happen automatically:
self.scores = [NSMutableArray array];
Note that here, I didn't use:
self.scores = [NSMutableArray alloc] init];
because that would cause two retains to happen, and of then EXC_BAD_ACCESS due to over-retention.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: trying to __dopostback from jscript, RaisePostBackEvent not firing i'm trying to follow the suggestion here: Call ASP.NET function from JavaScript?
But it's not working for me. The page does post back. but my RaisePostBacKEvent never fires. I am doing this in a usercontrol and not a page:
public partial class MyTreatment : System.Web.UI.UserControl, IPostBackEventHandler
Anyone have any suggestions on how to get this working?
Thanks
A: Are you specifying the ClientID of your control, as opposed to the ClientID of the page (as in the example from the other SO question you referenced)?
If not then that would explain why the page is posting back but not calling the RaisePostBack method in your control.
To reference the ClientID of your control, call the __doPostBack function like so:
__doPostBack("<%= yourControlID.ClientID %>", "an argument");
As a side note, if your control is the only control on the page then the __doPostBack function will not be created by ASP.NET unless you make a call to GetPostBackEventReference for your control.
You do not necessarily need to make use of the reference but you need to call the method so the page knows to generate the client side function.
You can call GetPostBackEventReference like so:
public class MyTreatment : UserControl, IPostBackEventHandler
{
protected override void OnLoad(EventArgs e)
{
string postBackEventReference = Page.ClientScript.GetPostBackEventReference(this, string.Empty);
base.OnLoad(e);
}
public void RaisePostBackEvent(string eventArgument)
{
}
}
Hope this helps.
A: It should work with using the user control instance ID's UniqueID property (I couldn't get this to work with ClientID, in my own personal experiences). Like so:
__doPostBack("<%= yourControlID.UniqueID %>", "arg");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Coldfusion stripping leading zeroes in autosuggest I've just encountered CF's unwanted "feature" which involves stripping leading zeroes from the values returned to an autosuggest input. I was thinking I could prepend some character to the values and strip them out after the return, but have hit a snag. I'm modifying an existing function, which looks like this:
<cffunction name="lookupTailNumber" access="remote" returntype="Array" >
<cfargument name="search" type="any" required="false" default="">
<!--- Define variables --->
<cfset var data="">
<cfset var result=ArrayNew(1)>
<!--- Do search --->
<cfquery name="data">
SELECT DISTINCT SERIAL_NUMBER AS list
FROM aircraft_status
WHERE SERIAL_NUMBER LIKE '%#trim(ARGUMENTS.search)#%'
ORDER BY list
</cfquery>
<!--- Build result array --->
<cfloop query="data">
<cfset ArrayAppend(result, list)>
</cfloop>
<!--- And return it --->
<cfreturn result>
</cffunction>
which returns a response which looks like this:
[3001.0,1.00002E8,1.00002001E8,1.00002002E8,1.00002003E8,1.00002004E8]
or in JSON format:
0
3001
1
100002000
2
100002001
3
100002002
4
100002003
where all the results have had leading zeroes stripped away. I've tried modifying the query to prepend a character to each value:
<cfquery name="data">
SELECT DISTINCT (concat(' ', SERIAL_NUMBER)) AS list
FROM aircraft_status
WHERE SERIAL_NUMBER LIKE '%#trim(ARGUMENTS.search)#%'
ORDER BY list
</cfquery>
which returns this:
[" 0000003001"," 0100002000"," 0100002001"," 0100002002"," 0100002003"," 0100002004"]
so you'd think all was well, right? Problem: when returned, none of the values show up in the autosuggest field!!! I've also tried prepending different characters, including numbers, with no luck. Looking at the elements in yui-ac-bd div > ul, none are populated or displayed.
The input is declared like so:
<cfinput style = "width:300px;"
class = ""
type="text"
name="txtvalueFilter"
maxlength="15"
id="txtvalueFilter"
autosuggest="cfc:mycfcpath({cfautosuggestvalue})"
/>
Thoughts?
A: Try appending a space, so the built-in JSON serializer will treat it as a string instead of an int in JSON.
Also, make sure you have installed the latest hotfixes for your version of CF.
I wonder if u need to "Build result array". What happen if you return data.list? or, maybe use ListToArray(valueList(data.list)) instead?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Python - how to avoid exec for batching? I have an existing python application (limited deployment) that requires the ability to run batches/macros (ie do foo 3 times, change x, do y). Currently I have this implemented as exec running through a text file which contains simple python code to do all the required batching.
However exec is messy (ie security issues) and there are also some cases where it doesn't act exactly the same as actually having the same code in your file. How can I get around using exec? I don't want to write my own mini-macro language, and users need to use multiple different macros per session, so I can't setup it such that the macro is a python file that calls the software and then runs itself or something similar.
Is there a cleaner/better way to do this?
Pseudocode: In the software it has something like:
-when a macro gets called
for line in macrofile:
exec line
and the macrofiles are python, ie something like:
property_of_software_obj = "some str"
software_function(some args)
etc.
A: Have you considered using a serialized data format like JSON? It's lightweight, can easily translate to Python dictionaries, and all the cool kids are using it.
You could construct the data in a way that is meaningful, but doesn't require containing actual code. You could then read in that construct, grab the parts you want, and then pass it to a function or class.
Edit: Added a pass at a cheesy example of a possible JSON spec.
Your JSON:
{
"macros": [
{
"function": "foo_func",
"args": {
"x": "y",
"bar": null
},
"name": "foo",
"iterations": 3
},
{
"function": "bar_func",
"args": {
"x": "y",
"bar": null
},
"name": "bar",
"iterations": 1
}
]
}
Then you parse it with Python's json lib:
import json
# Get JSON data from elsewhere and parse it
macros = json.loads(json_data)
# Do something with the macros
for macro in macros:
run_macro(macro) # For example
And the resulting Python data is almost identical syntactically to JSON aside from some of the keywords like True, False, None (true, false, null in JSON).
{
'macros': [
{
'args':
{
'bar': None,
'x': 'y'
},
'function': 'foo_func',
'iterations': 3,
'name': 'foo'
},
{
'args':
{
'bar': None,
'x': 'y'
},
'function': 'bar_func',
'iterations': 1,
'name': 'bar'
}
]
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WCF DispatchMessageInspector - Process and make available to operation I want to create a DispatchMessageInspector for my WCF service that will run before each operation, perform some processing and then make the result of that processing available to the operation.
Creating the MessageInspector is easy. However, after I do what I need to do there, where can I place the object that I create so it can be accessed by the code in each operation? In the MessageInspector, would I just store it in the OperationConext, or is there a cleaner solution?
A: You'd normally store this information on the message properties, then access it via the operation context on the operation (see an example in the code below).
public class StackOverflow_7534084
{
const string MyPropertyName = "MyProp";
[ServiceContract]
public interface ITest
{
[OperationContract]
string Echo(string text);
}
public class Service : ITest
{
public string Echo(string text)
{
Console.WriteLine("Information from the inspector: {0}", OperationContext.Current.IncomingMessageProperties[MyPropertyName]);
return text;
}
}
public class MyInspector : IEndpointBehavior, IDispatchMessageInspector
{
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
}
public void Validate(ServiceEndpoint endpoint)
{
}
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
request.Properties[MyPropertyName] = "Something from the inspector";
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "").Behaviors.Add(new MyInspector());
host.Open();
Console.WriteLine("Host opened");
ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
ITest proxy = factory.CreateChannel();
Console.WriteLine(proxy.Echo("Hello"));
((IClientChannel)proxy).Close();
factory.Close();
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Is BeginRead guaranteed to read any incoming bytes that arrive after a call to it? Let's say that after BeginRead is called, there is other code that will ultimately trigger the arrival of the bytes I want to read. Is the following scenario ever possible:
(1) Call to BeginRead is made, passing in 'buf' and returns
(2) Other code executes that is guaranteed to be subsequent to (1) and results in bytes being sent to a port
(3) Bytes arrive destined for the port but are not read into 'buf' due to some timing issue
I would not expect it to be possible but am looking for confirmation from someone experienced. If this is somehow possible, then what would be an alternative to get the guarantee I'm looking for?
A: BeginRead will finish when some data is available - but how much data isn't guaranteed. The most obvious example is if the buffer has already been filled before your "extra" data is sent to the port... but equally the buffer doesn't have to be filled - for example, in a network stream, BeginRead might return when a single packet has been read, even if there are more on the way.
You're likely to want to call BeginRead repeatedly until you've either read all of the data in the stream (i.e. the other end has closed the connection) or you've read as much as you were trying to (e.g. the whole of a length-prefixed message).
A: If you want to do proper network communication you WILL have to do application level framing.
Really though, the easiest thing to do would be to use a messaging library that takes care of all of this for you. Take a look at zeromq, it's really great and there's a .NET binding for it.
A: The bytes are probably there but they just might not be where you are looking for them. It is hard to say without seeing the code. I would suggest using WireShark to watch to make sure the data you think is being sent really is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Flashdata only shows every OTHER time the code runs I am relatively new to CodeIgniter, so I'm not sure if this is just bad coding, or if it is a problem with how I'm using CodeIgniter's flash data. For context: the user submits a phrase in a simple HTML form. The phrase is compared against what should be typed in (pretty simple, right?). This correct phrase changes based upon what step in the activity they are on. When they get the text wrong, I am attempting to use flashdata to show the error message. Here are the controller portions, followed by the view:
//Get step number
$step = $this->input->post('step');
$correct_text = array(
1 => 'TESTPHRASE',...
...
//If user enters the correct text
$entered_text = strtoupper($this->input->post('entered_text'));
if ($entered_text == $correct_text[$step])
{
...
}
//If user enters the incorrect text
else
{
$data['step'] = $step;
$this->session->set_flashdata('entry_error', '<b>Sorry!</b>Your entry was incorrect. Be sure to carefully read the instructions!');
$this->load->view('template', $data);
}
Here is the view that only runs every other time.
<?php
if ($this->session->flashdata('entry_error'))
{ ?>
<div id="game_error">
<?php echo $this->session->flashdata('entry_error'); ?>
</div>
<?php } ?>
A: From the docs: CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared.
You are setting the flashdata and then trying to access it during the same request. It's not available until the next request which is why it seems like it's only working every other time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Contact Form Problems Trying to install this contact form:
http://www.catswhocode.com/blog/how-to-create-a-built-in-contact-form-for-your-wordpress-theme
I'm getting HUGE gaps between fields: http://themeforward.com/demo2/features/contact-form/
Any idea what the problem is? I should be able to figure this one out after the problem is identified.
A: According to the markup, you have your padding-bottom set to 32767px.
Take a look at these CSS class definitions:
#archive_content ul li, #content ul li {
padding-bottom: 32767px;
...
}
A: The problem is this CSS rule in style.css (line 1260):
#post_content ul li, #archive_content ul li, #content ul li {
padding-bottom: 32767px;
}
The margin-bottom: -32767px; would counteract that if it wasn't immediately superceded by margin: 10px 0;.
So, from that rule set, remove either:
*
*margin: 10px 0, or
*padding-bottom: 32767px and margin-bottom: -32767px
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Define a pre-processor variable for all the files in make I have a number of .c and .h files with some parts of the code disabled by putting the code block in pre-processor directives e.g.
#ifdef FOOBAR
// some code that can be compiled if needed by defining FOOBAR in pre-processor.
#endif
No I need to define FOOBAR such that its defined for every file that is compiled by gcc using make.
Is there a way to do this with some option to make or Makefile ?
Thanks.
A: Add the compiler option -DFOOBAR to the make variable CFLAGS
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Not adding (non-retina) 1x images to an iPhone app Is there a way to not add 1x images to an iPhone/iPad app?
I'm developing an iPhone app and also testing on my iPad.
When I just use @2x images, the iPad successfully resizes down to the 1x size.
Is there any downside to not to add 1x images? Or are they still important?
A: By forcing the device to downsample, you're sacrificing performance and memory for a negligible amount of disk space. It's a really bad trade-off. Plus, downsampling a larger image on the fly on the device is likely to use a lower-quality downsampling algorithm than what's available in, say, Photoshop (for performance reasons).
A: I had an app with 100+ near-fullscreen photos, and dropping the @1x versions made possible to keep the app below the 50 MB limit for downloading over a cellular connection.
In my case, I had no choice, but as @Kevin Ballard mentions, perhaps the trade-off is not worth it. Remember that non-retina images are 25% the size of the retina ones, so in terms of pixels you are only going from 1.25 to 1.00.
Granted, with compressed images the relation might not be linear (i.e., @1x PNG/JPEG may weight more than 1/4 of the equivalent @2x image on disk).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Java: how to execute a process which is not attached to a Windows console? Both, Runtime.exec() as well as ProcessBuilder seem to attach a console to the started process. On Windows 7, one can see a conhost.exe popping up in the Task Manager. My problem is now that the C process I'm trying to start performs following test to determine whether it has a console window to which it can issue prompts:
HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
if (cons != INVALID_HANDLE_VALUE) {
// Prompt user; this makes my application hang
}
Is it possible with Java to start the C process in a way that upper test fails in order to avoid the prompt?
A: At least on OpenJDK 6, CreateProcess is being called with CREATE_NO_WINDOW. I would imagine that the Sun JDK's code is pretty similar. This makes me wonder if something else is causing that console to be present. Have you tried running your program with javaw.exe instead of java.exe?
Thinking outside of the box, maybe JGit is a better way to solve your particular problem.
A: Try this:
ProcessBuilder pb = new ProcessBuilder( "cmd", "/C start /B myprogram.exe param1 param2" );
The /B flag tells start to not create a new console, though I don't know whether or not start itself will end up allocating a console when called from Java.
A: Using Runtime is tricky cause you need to consume the output and input with streams.. See this article:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
Instead try using the exec library of apache commons.. Here's something that will get you started:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Regex to validate url The url will be something like: meusite.com/user/{keyword here}
The user will only enter the key word, then I would a regex to validate word if this does not invalidate the URL, blank spaces, special characters and 5 to 22 characters.
A: You just want to validate the keyword? Something like this should work:
/^[a-zA-Z0-9_\-\.\+]{5,22}$/
But why not just escape it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Must template parameters be types? In the Bjarne Stroustrup C++ Book (chapter 13, page 331), it said that "a template parameter can be used in the definition of subsequent template parameter". And it gives the following code:
template<class T, T def_val> class Cont{ /* ... */ }
Can anyone provide an example of how to use this template. For example, how to initialize an object of Cont? It look to me that "def_val" is not a type argument, and should not be placed in <>. Am I wrong?
Thanks a lot
A: You can do something like this:
Cont<int, 6> cnt;
// ^ as long as this is of type T (in this case int)
// def_val will be of type int and have a value of 6
Template parameters aren't required to be types.
This only works when T is an integral type (int, unsigned, long, char etc but not float, std::string, const char*, etc), as @Riga mentioned in his/her comment.
A: def_val is a value argument. An instantiation could look like this:
Cont<int, 1> foo;
An interesting case where this is useful is when you want to have a pointer to a class-member as template paremeter:
template<class C, int C::*P>
void foo(C * instance);
This enables foo to be instantiated with a pointer to a member of type int of any class.
A: Here's an example of how to instantiate the above:
template<class T, T def_val> class Cont{ /* ... */ };
int main()
{
Cont<int,42> c;
}
A: T def_val is an object of type T (which was previously passed). It could be used to initialize items in the container, for example. To use, it would look something like:
Object init(0);
Cont<Object, init> cont;
(psuedo-code; Object must obviously be a type that's legal to use in this manner)
That then uses the second template parameter. It's included in the template because it has a templated type; def_val must be of type T and must be passed when the object is created.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: JSF ui:repeat included by ui:include wrapped in h:panelGroup with conditional rendering... A mouthfull Original question is below, but as I have come up with a more minimal example to demonstrate this problem, and figured it should go at the top.
Anyway, it appears that ui:repeat tags are processed before checking to see if parent elements are actually rendered. To recreate this, here is the facelet (minimalTest.xhtml):
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Test JSF <ui:repeat> inside <h:panelGroup rendered="false"></title>
</h:head>
<h:body>
<h:form>
<h1>Testing</h1>
<h:panelGroup rendered="false">
<span>#{minimalTestBean.alsoThrowsException}</span>
<ul>
<ui:repeat value="#{minimalTestBean.throwsException}" var="item">
<li>#{item}</li>
</ui:repeat>
</ul>
</h:panelGroup>
</h:form>
</h:body>
</html>
With using this bean (MinimalTestBean.java):
package com.lucastheisen.beans;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean
@ViewScoped
public class MinimalTestBean implements Serializable {
private static final long serialVersionUID = 9045030165653014015L;
public String getAlsoThrowsException() {
throw new RuntimeException( "rendered is false so this shouldnt get called either" );
}
public List<String> getThrowsException() {
throw new RuntimeException( "rendered is false so this shouldnt get called" );
}
}
From this example you can see that the h:panelGroup that contains the ui:repeat is statically set to rendered=false which I would assume would mean that none of the EL expressions inside of that h:panelGroup would get executed. The EL expressions just call getters which throw a RuntimeException. However, the ui:repeat is actually calling the getter for its list thus causing the exception even though it should not be getting rendered in the first place. If you comment out the ui:repeat element, no exceptions get thrown (even though the other EL expression remains in the h:panelGroup) as I would expect.
Reading other questions here on stackoverflow leads me to believe that is likely related to the oft-referred-to chicken/egg issue, but I am not sure exactly why, nor what to do about it. I imagine setting the PARTIAL_STATE_SAVING to false might help, but would like to avoid the memory implications.
---- ORIGINAL QUESTION ----
Basically, I have a page that conditionally renders sections using <h:panelGroup rendered="#{modeXXX}"> wrapped around <ui:include src="pageXXX.xhtml" /> (per this answer). The problem is that if one of the pageXXX.xhtml has a <ui:repeat> inside of it, it seems to get processed even when the containing <h:panelGroup> has rendered=false. This is a problem because some of my sections rely on having been initialized by other sections that should be visited before them. Why is the included pageXXX.xhtml getting processed?
This is a painful bug and incredibly hard to boil down to a small example, but here is the most minimal case I could build that demonstrates the issue. First a base page:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Test JSF <ui:include></title>
</h:head>
<h:body>
<h:form>
<h1>#{testBean.title}</h1>
<h:panelGroup rendered="#{testBean.modeOne}">
<ui:include src="modeOne.xhtml" />
</h:panelGroup>
<h:panelGroup rendered="#{testBean.modeTwo}">
<ui:include src="modeTwo.xhtml" />
</h:panelGroup>
</h:form>
</h:body>
</html>
As you can see this page will conditionally include either the modeOne page or the modeTwo page based upon the value in the testBean bean. Then you have modeOne (the default):
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
<ui:composition>
<span>Okay, I'm ready. Take me to </span>
<h:commandLink action="#{testBean.setModeTwo}">mode two.</h:commandLink>
</ui:composition>
</html>
Which in my real world app would be a page that sets up things needed by modeTwo. Once set up, an action on this page will direct you to modeTwo:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
<ui:composition>
<div>Here is your list:</div>
<ui:repeat value="#{testBeanToo.list}" var="item">
<div>#{item}</div>
</ui:repeat>
</ui:composition>
</html>
The modeTwo page basically presents a details for the modeOne page in a ui:repeat as the actual information is in a collection. The main managed bean (TestBean):
package test.lucastheisen.beans;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
@ManagedBean
@ViewScoped
public class TestBean implements Serializable {
private static final long serialVersionUID = 6542086191355916513L;
private Mode mode;
@ManagedProperty( value="#{testBeanToo}" )
private TestBeanToo testBeanToo;
public TestBean() {
System.out.println( "constructing TestBean" );
setModeOne();
}
public String getTitle() {
System.out.println( "\ttb.getTitle()" );
return mode.getTitle();
}
public boolean isModeOne() {
return mode == Mode.One;
}
public boolean isModeTwo() {
return mode == Mode.Two;
}
public void setModeOne() {
this.mode = Mode.One;
}
public void setModeTwo() {
testBeanToo.getReadyCauseHereICome();
this.mode = Mode.Two;
}
public void setTestBeanToo( TestBeanToo testBeanToo ) {
this.testBeanToo = testBeanToo;
}
private enum Mode {
One("Mode One"),
Two("Mode Two");
private String title;
private Mode( String title ) {
this.title = title;
}
public String getTitle() {
return title;
}
}
}
Is the bean for all the main data, and the TestBeanToo bean would be for the details:
package test.lucastheisen.beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean
@ViewScoped
public class TestBeanToo implements Serializable {
private static final long serialVersionUID = 6542086191355916513L;
private ObjectWithList objectWithList = null;
public TestBeanToo() {
System.out.println( "constructing TestBeanToo" );
}
public String getTitle() {
System.out.println( "\ttb2.getTitle()" );
return "Test Too";
}
public List<String> getList() {
System.out.println( "\ttb2.getList()" );
return objectWithList.getList();
}
public void getReadyCauseHereICome() {
System.out.println( "\ttb2.getList()" );
objectWithList = new ObjectWithList();
}
public class ObjectWithList {
private List<String> list;
public ObjectWithList() {
list = new ArrayList<String>();
list.add( "List item 1" );
list.add( "List item 2" );
}
public List<String> getList() {
return list;
}
}
}
A: <ui:repeat> does not check the rendered attribute of itself (it has actually none) and its parents when the view is to be rendered. Consider using Tomahawk's <t:dataList> instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why doesn't $(this) work inside a javascript function? I've attached an onlick event to a function. I want to reference the element being clicked from inside the function so I can change its inner HTML, but why is it not working? Is there any other way to reference the clicked element?
HTML
<div class="save_button" onclick="toggle_save_star(<?php echo $listing->listing_id ?>,'<?php echo base_url()?>')">
<?php if($listing->saved_element_id):?>
<img src="<?php echo site_url('images/core/icons/basic2/star1_16.png')?>" />
<?php else:?>
<img src="<?php echo site_url('images/core/icons/basic2/star1_16_gray.png')?>" />
<?php endif; ?>
</div>
Javascript Function
function toggle_save_star(element_id, site_url) {
var url = site_url+"AJAX/ajax_default/modify_saved";
var button = $(this);
$.post(url,{action: 'toggle', element_id: element_id, type: 'listing' }, function(data) {
if(data == 'saved') {
$(button).html('<img src="'+site_url+'images/core/icons/basic2/star1_16.png" />');
}
else{
$(button).html('<img src="'+site_url+'images/core/icons/basic2/star1_16_gray.png" />');
}
});
}
A: I think in this case "this" don't reference to the div. You should try:
$('.save_button').click(function(){
$(this)...
});
A: Try $("#"+element_id) instead. $(this) isn't working because you're not running this function as a method on an object.
Improving on the other answers, try this:
$(".save_button").click(function(){
toggle_save_star(element_id, site_url, $(this));
});
and in your function, the third new argument (called "target", let's say) could be used like this:
var button = target;
then use button like button.html(...);
A: The main problem here is that when you assign a string to onclick in your markup as in:
<div class="save_button" onclick="toggle_save_star..."
then, the code in the quotes gets evaluated by eval() and the this pointer will be set to point to the window object, not to the object that generated the click. If you want this set appropriately, then you can't assign the onclick handler in the markup, you would need to do it with JS as in:
$(".save_button").click();
or some other way in code.
In addition, there's a coding error in your toggle_save_star function.
Your button variable is already a jQuery object so you don't need to try to make it into another one with $(button). If you were going to use that function, you would have to change it to this:
function toggle_save_star(element_id, site_url) {
var url = site_url+"AJAX/ajax_default/modify_saved";
var button = $(this);
$.post(url,{action: 'toggle', element_id: element_id, type: 'listing' }, function(data) {
if(data == 'saved') {
button.html('<img src="'+site_url+'images/core/icons/basic2/star1_16.png" />');
}
else{
button.html('<img src="'+site_url+'images/core/icons/basic2/star1_16_gray.png" />');
}
});
}
A: You would be better off removing the onclick from your div and going with something like the following:
http://jsfiddle.net/cpeele00/epD3v/
This allows you access the clickable item, in this case 'save_button'.
Then, at the bottom of your page (before you reach the closing body tag, insert your script there).
<script>
$(document).ready(function(){
//CALL THE FUNCTION HERE
//DEFINE THE FUNCTION HERE (see the jsFiddle link above)
});
</script>
</body>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What database is best suited, especially in terms of disk usage, to millions of very small rows with a high insert, query, and delete volume? I'm looking at a table structure that might look about like this:
| char(32) | char(32) | (boolean) |
The combination of the first two columns will be indexed. This database could easily have millions if not tens of millions of rows being inserted, queried, updated, and deleted every day. What's the best database tool for this? Is it MySQL or is there something more efficient that will use less space on disk?
A: Any relational database should be able to handle the load you describe assuming a proper logical and physical schema.
A: Only that one table? Is the table shared, or only updated by one process?
If that's the only data you're keeping and it's maintained by a single process then any kind of database is probably overkill. Why not a linked list in memory?
A: Does it have to be on a disk? Why not use memcached or redis? I assume you can make your "table" into "key/value" pairs?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to swap jquery for prototype in Rails 3.1 I have a rails 3.1 project that was created with the default jQuery. What is the best way to convert the project to use prototype instead?
A: *
*Remove the jquery gem from Gemfile
*add prototype-rails to it
From https://github.com/rails/prototype-rails:
You may want to add them to your
app/assets/javascripts/application.js:
//= require prototype
//= require prototype_ujs
//= require effects
//= require dragdrop
//= require controls
New applications using this may also want to add
config.action_view.debug_rjs = true
to their config/environments/development.rb.
A: diodeus is right, i'd rewrite it, and take it as a great opportunity to improve the code ;)
nevertheless i'm curious, why would you wanna switch TO prototype
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Determining methods available in a web service by examining the WSDL file (I am fairly new to web services, kindly excuse any incorrect terminology)
Given a WSDL URL, how does one determine what methods are available in that web service by looking at the source of the WSDL file?
Also, how does one construct a SOAP response to use with the WSDL file to post data back to the web service?
A: I think what you ask is how to interpret a wsdl. Following articles[1][2] may help you.
[1] http://wso2.org/library/2873
[2] http://wso2.org/library/2935
A: Unlike the others, I'm not going to go into details about the WSDL file and how you can read it. You will eventually learn all of that by yourself by reading books, articles, experimenting with web services etc.
What I'm going to do is recommend you a very simple to use, yet powerful tool, than must be in the toolbox of every web service developer (especially someone new to web services): SoapUI.
You create a simple project in SoapUI and point it to the WSDL file of the web service. It will discover the operations, create sample request and response messages, create mocks of the web service and much more.
You can then look at the WSDL code and with the help of what's presented inside SoapUI discover which elements are involved in each method.
A: Just open this url to WSDL (looks like http://host:port/ddfdgfgd?wsdl) in your browser or download it to file.
Find all WSDL sections portType (portType is similar Java interface). All WSDL port types contains operations linked to input/output messages. These messages linked with XSD elements or types (it depends SOAP encoding type).
Also you can import WSDL with Java with wsimport command line tool and implement client or server side.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Annotation or keyword to tell garbage collector of objects to remove first There is an annotation or a keyword in Java that tells the garbage collector to remove some objects first when the memory is running out.
Unfortunately I've forgotten it's name. Do you know it?
A: I think I'm safe in saying that your memory's in error. You may be thinking of reference objects.
A: I can't even see how you would annotate an object. Annotations are a compile time thing and objects are a runtime thing.
Perhaps you meant to say something like "how do I annotate a class to tell the garbage collector to collect objects of this class before any other objects".
I've never heard of such feature though.
Perhaps you're thinking of some cache eviction algorithms:
*
*least recently used (LRU),
*least frequently used (LFU), or
*first in first out (FIFO)
In that case, have a look at the EHCache library.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I trigger a function? I have this code:
<a href="#" class="button" id="buyme" ></a>
<a href="#" id="buy" onclick="placeOrder('10');return false;"><span id="please">click me</span></a>
<script>
$('#buyme').click(function() {
$('#buy').trigger(function(placeOrder('10')));
});
</script>
<script>
function placeOrder(var) {
.....
}
</script>
What I want to do is when I click on #buyme to trigger the onclick from the #buy link or to trigger the function from inside onClick.
My example doesn't seem to do it. Any ideas?
edit:
for some reason :
$('#buyme').click(function() {
$("#buy").click();
});
doesn't work
A: Just call the function yourself:
$('#buyme').click(function() {
placeOrder('10');
});
You could also trigger the click event of the button and let it call the function (seems a bit backwards though):
$('#buyme').click(function() {
$("#buy").click();
});
A: $("#buyme").click(function(){
$("#buy").click();
});
A: Just use click(). According to docs, calling it without an argument triggers the event.
$('#buy').click();
A: This bit: function(placeOrder('10')) is invalid. Replace it with:
$('#buy').click();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sending log to remote MSMQ I installed NLog version 2 and sending to a remote MSMQ is not working. Do I have the config setup properly?
<nlog autoReload="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target xsi:type="MSMQ" name="MSMQLog" useXmlEncoding="true" queue="FormatName:DIRECT=OS:server01\private$\test_log" recoverable="true" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="MSMQLog" />
</rules>
</nlog>
I installed MSMQ on my local box and the server I'm sending the message too. NLog doesn't throw any exceptions (they are turned on). I don't see anything in the outgoing mailbox on my local machine.
I am able to send to the queue by using the following code.
using (var queue = new MessageQueue(@"FormatName:DIRECT=OS:server01\private$\tasi_log"))
{
var message = new Message("TEST");
message.Formatter = new BinaryMessageFormatter();
queue.Send(message);
}
Does NLog work with remote queues?
A: So I tried sending to a public queue and it still didn't work using NLog. So, I looked at the NLog.Extended source code and I found this method.
protected override void Write(LogEventInfo logEvent)
{
if (this.Queue == null)
{
return;
}
string queue = this.Queue.Render(logEvent);
if (!MessageQueue.Exists(queue))
{
if (this.CreateQueueIfNotExists)
{
MessageQueue.Create(queue);
}
else
{
return;
}
}
using (MessageQueue mq = new MessageQueue(queue))
{
Message msg = this.PrepareMessage(logEvent);
if (msg != null)
{
mq.Send(msg);
}
}
}
I commented out the following if statement and it now sends to remote queues. Can someone verify this? Is this a bug, or am I missing something?
if (!MessageQueue.Exists(queue))
{
if (this.CreateQueueIfNotExists)
{
MessageQueue.Create(queue);
}
else
{
return;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jquery tabs inside a floating div not showing up properly i can get tabs working fine in straight htm file with no floats. when i add a left & right container side by side the tabs get messed up. The content gets displayed outside of the tab div underneath it.
here is the code, anyone solve this issue? i found similar things but nothing exactly like what i am accomplishing. jquery 1.6.4
<link href="css/jquery-ui-1.8.15.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript">
$(function ($)
{
$('#tabs').tabs();
});
</script>
<br />
<a href="cheer.htm" style="margin-left:10px;">
<img border="0" src="images/cheerleadingjrchiefs3sm.gif" width="180" height="92" alt="" />
</a>
</div>
<div id="rightContainer">
<div id="tabs">
<ul>
<li><a href="#tabs-1">Nunc tincidunt</a></li>
<li><a href="#tabs-2">Proin dolor</a></li>
<li><a href="#tabs-3">Aenean lacinia</a></li>
</ul>
<div id="tabs-1">
<p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p>
</div>
<div id="tabs-2">
<p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p>
</div>
<div id="tabs-3">
<p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.</p>
<p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.</p>
</div>
</div>
</div>
styles:
#navMenu
{
list-style-type:none;
font-size:1.2em;
font-weight:bold;
margin-left: 10px;
height: 297px;
}
#navMenu li
{
padding-bottom:5px;
}
#leftContainer
{
width:210px;
float:left;
background-image: url("../images/jrchiefsbg.gif");
background-repeat:repeat;
}
#rightContainer
{
margin-left:220px;
}
two of the many styles in the included jquery stylesheet
.ui-helper-clearfix:after {
clear: both;
content: ".";
display: block;
height: 0;
visibility: hidden;
}
.ui-helper-clearfix {
display: block;
}
i used firebug to remove the clear: both; on the class .ui-helper-clearfix:after and it put everything where it is suppose to be minus the actual background gray color
now the only problem is that the gray background isn't behind the whole li element
A: Basically, try a "float: right" on your right col.
If that doesn't work, consider making a fiddle, it's much easier to understand stuff when you can debug the code right away.
A: So after fiddling with CSS on the page in firebug I couldn't get it perfect. I switched to
http://flowplayer.org/tools/tabs/index.html
Came out real nice using the non image CSS. To work with the image tabs I would have to resice the actual tab image to get what I needed inside the right container.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: file_get_contents() and stream_get_contents() fail to open stream I'm trying to force a file to be downloaded by sending it special headers. In doing so, I have to redirect URL requests for PDF documents through my download script.
I pass a query called $seg3, which is base64_encode()ed before sending, and then base64_decode()ed and urlencoded() when trying to request the file.
I've taken a look at using,
if (ini_get('allow_url_fopen') == '1')
{
$data = file_get_contents(urlencode(base64_decode($seg3)));
}
else
{
$fp = fopen(urlencode(base64_decode($seg3)), 'rb');
$data = stream_get_contents($fp);
fclose($fp);
}
But both file_get_contents() and stream_get_content() fail with:
fopen($URL): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
Yet when I dump the URL that is being sent, I can copy and paste it in my browser and open the file.
It only seems to occur when spaces are in the file, yet the error occurs whether I use urlencode() or not.
A: It may be that an url returns a 404 error, but still returns regular contents as well. So while the browser may display a regular page, this function will fail because of the result code.
A: I'm sure this has been fixed already, but if there are spaces urlencode($url) might solve your problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding customized functions to Buildbot I have written a function in python and I would like to have Buildbot to execute this function
when it receives a "build" command. I have used the "factory.addStep()" before to add new commands through command line, but I'm not sure how I can add a python function to Buildbot. Thanks and please let me know if I'm being unclear on anything.
A: Do you want the code to run on the master or the slave?
If you want to run code on the master, then all you need to do is subclass BuildStep, and put your code in .start (see the link in vernomcrp's answer).
If you want to run the code on the slave, things become trickier. The simplest solution is if you can write a python script (rather than function), and execute that script. You can include the script in your repository, or download it to the slave with FileDownload or StringDownload.
If you require the code to run in the slave process it self, you need patch the slave, to add a new command, and create a corresponding BuildStep on the master, that calls your new command. This requires modifying the buildslave code on all slaves that you want to run the code on. This isn't documented anywhere, so you will need to have a look at the code to figure out how to do this.
A: I think we can customize buildstep to execute python function. Have a look at this link http://buildbot.net/buildbot/docs/latest/manual/customization.html. I think it has something what you want. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Error when accessing Count property of an IList in ASP.Net MVC 3 When I try to display the count property of an IList in my ViewModel on the View i get the following error:
The property System.Collections.Generic.IList`1[[WebUI.ViewModels.ItemViewModel, WebUI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].Count could not be found.
The line in my view that riases the error is:
<td>@Html.DisplayFor(modelItem => item.ItemCollection.Count)</td>
Upon inspection, the collection is populated correctly and this line of code works correctly:
<td>@Html.DisplayFor(modelItem => item.ItemCollection[0].Id)</td>
I clearly have a reference to System.Collections.Generic so I suspect the error is refering to the WebUI.ViewModels.ItemViewModel object. This is accessible when debugging and the error is only raised when accessing Count.
A: Why dont you try:
<td>@Model.ItemCollection.Count</td>
Without the HtmlHelper...
A: You can Cast IList to List then use List.Count
Try this:
<td>@Html.DisplayFor(modelItem => ((List<WebUI.ViewModels.ItemViewModel>)item.ItemCollection).Count)</td>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: "The Report is empty" - is bug? I've created report with 3 parameters in iReport and it's running successfully. The report is execute MS SQL stor proc with 3 parameters:
*
*startdate;
*enddate;
*dept_nm (department name);
iReport gives good result. As soon as I exported jrxml file to JasperReports Server 4.1 I have message "The report is empty".
In the Repository under JasperReports Server I've created controls for dates parameters and single list values for dept_nm parameter.
Do you know how to debug and trace this message coming from???
A: Your query is returning no data. The message appears when the report result is null.
The quickest way to debug this in JasperReports Server is to modify the report's behavior when no data is returned. The default behavior is "No Pages". Change it to "All Sections, No Details". That way you'll get at least the report title and summary band.
Display your parameters in the title band to see what their values are. Often they aren't what you expect. For example, your input control is "StartDate", but your parameters is "startdate". So the parameter doesn't get the value you thought it would.
A: I get this a lot. E.g if you have sub reports only, it thinks the main report is blank. You have to do something silly like insert a dummy SQL into your report such as "select 1" then populate a hidden part of the report with the result. When it works on in report studio, but gives you the report is empty on the server (with a good data source - other reports working) is when you have real trouble. Not solved those yet.
A: Maybe you did not connect your report to any Data Source.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Having issues passing Objects among tiers I'm trying to do something that should be real simple but I'm getting errors I don't know how to correct. Also, I don't even know if I'm doing things the "correct" way.
I have 3 entities. My first entity is called Bill and it's my main one. The other two are Repeat and Type. Bill has foreign keys (i.e. TypeId) which point to their respective primary keys. Both Type and Repeat are similar. They have their Id and description.
What I'm trying to do with EF and LINQ to Entity: Get all bills with all the properties of Bill but instead of the TypeId, I want TypeDesc.
This is an N tier Solution with 3 projects
Thus far I have my data layer I call Model, business layer I call BLL and my presentation later I call GUI.
namespace BillApp.Model
{
public class BillModel
{
public List<BillType> GetAllBills()
{
using (BillsEntities be = new BillsEntities())
{
var results = from o in be.Bills
.Include("Type")
.Include("Repeat")
select new
{
BillId = o.BillId,
Name = o.Name,
URL = o.URL,
PaymentAmount = o.PaymentAmount,
Balance = o.Balance,
DueDate = o.DueDate,
TypeDesc = o.Type.TypeDesc,
RepeatDesc = o.Repeat.RepeatDesc,
Username = o.UserName
};
return results.ToList();
}
}
}
public class BillType
{
#region Properties
public int BillId { get; set; }
public string Name { get; set; }
public string URL { get; set; }
public decimal PaymentAmount { get; set; }
public decimal Balance { get; set; }
public DateTime DueDate { get; set; }
public string TypeDesc { get; set; }
public string RepeatDesc { get; set; }
public string Username { get; set; }
#endregion
}
}
results returns an error Cannot implicitly convert type System.Linq.IQueryable<AnonymousType#1> to System.Collections.Generic.List<BillApp.Model.BillType>
Next I try and pass the object to my BLL with this code.
namespace BillApp.BLL
{
public class BillBLL
{
public List<BillType> GetAllBills()
{
BillModel b = new BillModel();
return b.GetAllBills();
}
}
}
But BillType has an error:The type or namespace name 'BillType' could not be found (are you missing a using directive or an assembly reference?)
What am I missing? What can I do better?
A: I think the error messages are pretty clear: results is of type IQueryable<T> and you're trying to return a List<T>. To return a list instead, you can use the ToList method. You'll also need to create instances of BillType instead of anonymous objects, so that it conforms to the List<BillType> return type. Your GetAllBills method would look like this:
public List<BillType> GetAllBills()
{
using (BillsEntities be = new BillsEntities())
{
var results = from o in be.Bills
.Include("Type")
.Include("Repeat")
select new BillType
{
BillId = o.BillId,
Name = o.Name,
URL = o.URL,
PaymentAmount = o.PaymentAmount,
Balance = o.Balance,
DueDate = o.DueDate,
TypeDesc = o.Type.TypeDesc,
RepeatDesc = o.Repeat.RepeatDesc,
Username = o.UserName
};
return results.ToList();
}
}
For the second error you're probably just missing a using directive to have access to your BillType type which is in a different namespace. You'd have this line at the top of the file:
using BillApp.Model;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to set the date in a plist to [NSDate dateWithTimeIntervalSince1970:0]? I have a row in my plist using a Date type. I manually set to the date to Jan 1, 1970 12:00:00 AM. I'm using the plist as defaults for NSUserDefaults. When I read the value using NSUserDefaults, it returns 1970-01-01 08:00:00 +0000. As a result, this check always fails:
if ([defaultDateFromPlist isEqualToDate:[NSDate dateWithTimeIntervalSince1970:0]])
// this never evaluates to true since the time is returning 08:00:00
What date do I type in my plist to make sure the default is equal to [NSDate dateWithTimeIntervalSince1970:0]?
A: In the Xcode project navigator you can right-click on the plist file and select Open as Source Code. This will allow you to edit the file in its raw XML form.
From there you can set the time more precisely using "Z". So you can have something like this:
<key>startDate</key>
<date>1970-01-01T00:00:00Z</date>
A: Time zones strike again! The date you're comparing to is 00:00 GMT on 1/1/1970, not 00:00 in your local time, so you'll need to specify a time zone in the date in the plist. Try using the same "+0000" suffix in the plist as you got in the output, and you should be fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Only count a download once it's served We have this code which serves a download:
public class downloadRelease : IHttpHandler {
public void ProcessRequest (HttpContext context) {
-- snip --
context.Response.Clear();
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + OriginalFileName);
context.Response.WriteFile(Settings.ReleaseFileLocation + ActualFileName);
// Log download
Constructor.VersionReleaseDownload.NewReleaseDownload(ActualFileName);
It works fine, except that the log download code runs as soon as the download starts seemingly, not when the download has fully completed as we expect.
Can someone explain why this is, and how to change it so it only logs when it's completed? We don't want to count partial downloads.
A: This blog post has exactly same issue as yours and a solution too.
Response.Buffer = false;
Response.TransmitFile("Tree.jpg");
Response.Close();
// logging here
A: The write response is an asynchronous process. It is managed by the container for the application. In your case the .NET/ASP.net run time is handling it. If you want to find out when the last chunk was sent you'll have to have some kind of callback/event on that [coming from the container/runtime]. In Java its the application server that gets this information [Glassfish, Tomcat etc]
A: You can try to add this before writing the file:
context.Response.BufferOutput = false;
A: This is a bit tricky... depending on how precise you want the logging to be it might even be that it is not possible... but there are the following options with the Response object :
*
*BinaryWrite / Flush / Close
*TransmitFile / Flush / Close
The first option requires you to read the file chunk after chunk calling BinaryWrite and Flush for every chunk...
The second option is easier to implement since it is just a call to TransmitFile and then to Flush.
After everything is sent and before logging you need to call Close.
In any case it can help to call DisableKernelCache before starting to send a response...
BEWARE that all of the above will show a noticeable performance hit!
This effect can be reduced by creating an in-memory-cache for the files you want to serve though...
As to the logging I would consider moving the logging code to the EndRequest event handler...
AFAIK this is the nearest you can get to your goal except writing your own TcpListener-based HTTP server or hacking IIS / HTTP.SYS .
Some reference links:
*
*http://msdn.microsoft.com/en-us/library/12s31dhy.aspx
*http://msdn.microsoft.com/en-us/library/system.web.httpresponse.binarywrite.aspx
*http://msdn.microsoft.com/en-us/library/system.web.httpresponse.flush.aspx
*http://msdn.microsoft.com/en-us/library/system.web.httpresponse.close.aspx
*http://msdn.microsoft.com/en-us/library/system.web.httpresponse.disablekernelcache.aspx
*http://msdn.microsoft.com/en-us/library/system.web.httpapplication.endrequest.aspx
A: Have you tried handling the EndRequest event of HttpApplication?
Or perhaps, using the ReleaseHandler() method of IHttpHandlerFactory, assuming that you mark your IHttpHandler as non-reusable?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Javascript: Onclick Set Dropdown Menu Checked Value UPDATE: I was trying lots of different methods for doing this and none of them worked... until... I changed my dropdown menu name from (date-range) to (dateRange) removing the (-), sorry for wasting time!
I have a search form and a custom reset form button, which resets all the values in the form. I now have a dropdown menu and when the reset button is pressed, I want the first option to be selected.
This is my form:
<select name="date-range" id="date-range">
<option value="Any">Any date</option>
<option value="Today">Today</option>
<option value="Yesterday">Yesterday</option>
<option value="1 Week">Within 1 Week</option>
<option value="1 Month">Within 1 Month</option>
<option value="3 Months">Within 3 Months</option>
<option value="6 Months">Within 6 Months</option>
<option value="1 Year">Within 1 Year</option>
</script>
... and this is my javascript function that now needs to select the first dropdown value "Any".
function resetSearchForm()
{
document.searchFrm.searchStr.value='';
document.searchFrm.vertical.checked = true;
document.searchFrm.horizontal.checked = true;
** dropdown select first **
}
What is the proper way to do this? Any help gratefully received :)
A: This will work:
document.getElementById('date-range').selectedIndex = 0;
Example can be found here:
http://jsfiddle.net/yPmmG/3/
A: No javascript required, just add the selected attribute to the first option. That's what the attribute is for.
<option selected value="Any">Any date</option>
It is recommended that all select elements have one option with the selected attribute, that way there is always one selected by default. It will be the selected option when the page first loads and if the form is reset.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to tokenize text in PL/PGSQL using regular expressions? I want to tokenize text in my database with RegEx and store the resulting tokens in a table. First I want to split the words by spaces, and then each token by punctuation.
I'm doing this in my application, but executing it in the database might speed it up.
Is it possible to do this?
A: There is a number of functions for tasks like that.
To retrieve the 2nd word of a text:
SELECT split_part('split this up', ' ', 2);
Split the whole text and return one word per row:
SELECT regexp_split_to_table('split this up', E'\\s+');
Actually, the last example splits on any stretch of whitespace.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Jquery ajax calls, which is best? I have found this information on the web about jquery ajax requests.
load(): Load a piece of html into a container DOM.
$.getJSON(): Load a JSON with GET method.
$.getScript(): Load a JavaScript.
$.get(): Use this if you want to make a GET call and play extensively with the response.
$.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.
$.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the fly.
But it doesn't say anything about performance which is best for using it for what. Which is best for from validation? Which is best in speed and such alike.
I have never used jQuery ajax before and wondered from some of you more experienced programmers in your time of using jQuery ajax requests which have your find suit your needs best?
What is JSON I know it is called javascript object notation but what does mean?
A: None will be better or worse. Use what is appropriate for the situation.
A: They are all just shorthand for $.ajax() with a certain subset of parameters. None is "better" than the other, whichever works for your situation is "best".
A: I would suggest $.ajax() for flexibility and it gives you more option..
The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available and are easier to use. If less common options are required, though, $.ajax() can be used more flexibly.
A: If you look in the documentation, get uses ajax under the covers. Also look at this
http://api.jquery.com/jQuery.ajaxSetup/
it could save you some typing.
A: Like kingjiv said, each and every one of those go through the $.ajax method.
load() sets the type to get/post does other things in the background to make sure that the response is populated on the selected element then calls $.ajax. Below is the code.
load: function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf( " " );
if ( off >= 0 ) {
var selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
} // after this is calls $.ajax and passes in the parameters
$.getJSON(): This just calls $.get setting the dataType to json. $.get in turn calls $.ajax
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
}
$.getScript(): You guessed it, just calls $.get and passes in the dataType as script.
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
$.get() & $.post(): These two methods call $.ajax as well.
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
In conclusion, use whatever is suited to the purpose, just depends on what you intend to do. The performance should be the same since you have seen they all go through $.ajax
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Detect whether user is logged in to Facebook I want to show Login button and Login status as "LOGGED IN" if the user has Facebook open in any other tab of their browser, and otherwise show "NOT LOGGED IN".
A: To use the Facebook to determine, the user would have had to first approve your application. This can be checked with the javascript sdk:
FB.getLoginStatus(function(response) {
if (response.authResponse) {
// logged in and connected user, someone you know
} else {
// no user session available, someone you dont know
}
});
If you just want to know if they are logged into Facebook (not your application), someone has found a loophole to detect.
A: The Facebook Javascript SDK supports checking if your site's user is logged into Facebook, see here: https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: string.GetHashCode() returns different values in debug vs release, how do I avoid this? To my surprise the folowing method produces a different result in debug vs release:
int result = "test".GetHashCode();
Is there any way to avoid this?
I need a reliable way to hash a string and I need the value to be consistent in debug and release mode. I would like to avoid writing my own hashing function if possible.
Why does this happen?
FYI, reflector gives me:
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail), SecuritySafeCritical]
public override unsafe int GetHashCode()
{
fixed (char* str = ((char*) this))
{
char* chPtr = str;
int num = 0x15051505;
int num2 = num;
int* numPtr = (int*) chPtr;
for (int i = this.Length; i > 0; i -= 4)
{
num = (((num << 5) + num) + (num >> 0x1b)) ^ numPtr[0];
if (i <= 2)
{
break;
}
num2 = (((num2 << 5) + num2) + (num2 >> 0x1b)) ^ numPtr[1];
numPtr += 2;
}
return (num + (num2 * 0x5d588b65));
}
}
A: GetHashCode() is not what you should be using to hash a string, almost 100% of the time. Without knowing what you're doing, I recommend that you use an actual hash algorithm, like SHA-1:
using(System.Security.Cryptography.SHA1Managed hp = new System.Security.Cryptography.SHA1Managed()) {
// Use hp.ComputeHash(System.Text.Encoding.ASCII (or Unicode, UTF8, UTF16, or UTF32 or something...).GetBytes(theString) to compute the hash code.
}
Update: For something a little bit faster, there's also SHA1Cng, which is significantly faster than SHA1Managed.
A: Here's a better approach that is much faster than SHA and you can replace the modified GetHasCode with it: C# fast hash murmur2
There are several implementations with different levels of "unmanaged" code, so if you need fully managed it's there and if you can use unsafe it's there too.
A: /// <summary>
/// Default implementation of string.GetHashCode is not consistent on different platforms (x32/x64 which is our case) and frameworks.
/// FNV-1a - (Fowler/Noll/Vo) is a fast, consistent, non-cryptographic hash algorithm with good dispersion. (see http://isthe.com/chongo/tech/comp/fnv/#FNV-1a)
/// </summary>
private static int GetFNV1aHashCode(string str)
{
if (str == null)
return 0;
var length = str.Length;
// original FNV-1a has 32 bit offset_basis = 2166136261 but length gives a bit better dispersion (2%) for our case where all the strings are equal length, for example: "3EC0FFFF01ECD9C4001B01E2A707"
int hash = length;
for (int i = 0; i != length; ++i)
hash = (hash ^ str[i]) * 16777619;
return hash;
}
I guess this implementation is slower than the unsafe one posted here. But it's much simpler and safe. Works good in case super speed is not needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Time-varying values in Rx I have two observables. One is from Observable.fromEvent(..), where the underlying event is the user checking a Winforms checkbox. The other is Observable.Interval(..) which I subscribe to in order to do some IO, and I would like to prevent this observable from doing IO, whenever the checkbox is not checked.
I could do it like this:
var gui = new GUI();
var booleans = Observable
.FromEvent<GUI.NewAllowHandler, bool>(
h => gui.NewAllow += h,
h => gui.NewAllow -= h)
Observable.Interval(TimeSpan.FromSeconds(10))
.CombineLatest(booleans, Tuple.Create)
.Where(t => t.Item2)
.Select(t => t.Item1)
.Subscribe(l => DoStuff(l));
but this has the overhead of mixing the booleans in and out of the stream. A nicer way of doing this would be, if I could generate a time-varying value from the booleans variable, which at all times had the value of the last event. Then I could do something like this:
var gui = new GUI();
var booleanState = Observable // typeof(booleanState) == ???
.FromEvent<GUI.NewAllowHandler, bool>(
h => gui.NewAllow += h,
h => gui.NewAllow -= h)
.TimeValue() // hypothetical syntax
Observable.Interval(TimeSpan.FromSeconds(10))
.Where(_ => booleanState)
.Subscribe(l => DoStuff(l));
, which to me seems much closer to the problem statement. Is there anything like this in Rx, or is there anything else, that could make such problems easier to handle?
A: The Where statement in your interval should work with a properly scoped normal bool:
var booleans = Observable
.FromEvent<GUI.NewAllowHandler, bool>(
h => gui.NewAllow += h,
h => gui.NewAllow -= h)
var isBoxChecked = false;
booleans.Subscribe(t => isBoxChecked = t);
Observable.Interval(TimeSpan.FromSeconds(10))
.Where(_ => isBoxChecked)
.Subscribe(l => DoStuff(l))
Edit: Per your comment, another way of doing it:
intervals = Observable.Interval(TimeSpan.FromSeconds(10));
booleans
.Where(t => t)
.SelectMany(_ => intervals.TakeUntil(booleans))
.Subscribe(l => DoStuff(l))
A: You need to model the checkbox checked state as Behavior and not as Event stream (because behavior has always a value and this value changes over a period of time - which fits with checkbox checked state). So you can do something like:
var booleans = new BehaviorSubject<bool>(chk.Checked)
var chkEvents = ... //generate boolean observable from checkbox check event
chkEvents.Subscribe(booleans);
Observable.Interval(TimeSpan.FromSeconds(10))
.Where(i => booleans.First())
.Subscribe(i => DoIO());
A: I'm going to give you two solutions. The first is a very simple and hopefully obvious one using only one observable. The second is a uses both observables.
Since you want to allow the IO only when the box is checked then this is the simplest approach:
Observable
.Interval(TimeSpan.FromSeconds(10))
.Where(_ => gui.IsChecked)
.Subscribe(l => DoStuff(l));
No need at all for the other observable.
But if you really need to use it then the Switch() extension method is your best bet. Try this:
booleans
.Select(b => b == true
? Observable.Interval(TimeSpan.FromSeconds(10))
: Observable.Empty<long>())
.Switch()
.Subscribe(l => DoStuff(l));
It's pretty clean and helps to show that there are empty periods if the checkbox is not ticked.
I hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: android videoview garbled in new activity I'm loading an mp4 video from external storage into a videoview in every activity. In the first activity, the video is perfect, in the second activity, the video is garbled, and then in the third activity, the video is perfect again. Do I need to somehow clean up the videoview before loading a new activity? The video is consistently garbled following a clear video, and consistently clear after a garbled video.
I tried setting the onpreparedlistener and then starting the mediaplayer in the onprepared method, but every other video still remains garbled. However, when I break at the onprepared method, the video from the previous activity is still visible and running only in the cases where the new video is garbled. When the new activity blacks out the old video, the new video is not garbled.
It seems like the video is persisting from the previous activity to the new activity every other time. I'm confused.
A: I had a similar issue before - what is happening is that your video is not completely buffered or in a READY state before you begin playing it. Take a look at the state diagram for the MediaPlayer here.
This is pretty much what you need to do.
It is persisting into the next activity because the media player keeps playing its contents until it is done playing them. Do this:
@Override
public void onDestroy() {
super.onDestroy();
if (mediaPlayerInstance.isPlaying())
mediaPlayerInstance.stop();
}
That should solve your problem!
A: Alright I've got it working. I needed to reset the mediaPlayer associated with the videoview before starting the new activity. I guess this means that my new activity is using the same videoview and therefore the same mediaplayer in the new activity.
Although calling reset works, it's hard to believe that that's what I'm supposed to do. It seems like videoview was designed so I don't have to manage the mediaplayer since the only way to access the mediaplayer is through the onPreparedListener...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Center Text on a Button I know this has been asked a couple of times before, but not of the solutions seem to be working in this case. Basically, I want the word "play" to be centered vertically and horizontally on this button. Horizontally, the text behaves itself, but vertically, not matter what I try, it is always a little bit lower than it should, in all browsers I test it on. Does anyone have any suggestions? Thanks
<style type="text/css">
button {
font-family: Verdana, Geneva, sans-serif;
color: white;
border-style: none;
vertical-align: center;
text-align: center;
}
button:hover {
cursor: pointer;
}
button::-moz-focus-inner /*Remove button padding in FF*/
{
border: 0;
padding: 0;
}
.start {
background-color: #0C0;
font-size: 2em;
padding: 10px;
}
</style>
<button type="button" class="start">play</button>
A: The padding on .start is likely what you'll have to play around with, although the way it's set, it should be centering it, but you can break it out to something like padding: 8px 10px 10px 10px;
You might also check and set the line-height under .start and see if it helps.
A: The correct value for vertical-align is middle, not center. However I'm not sure if that'll make the difference, because it might just affect where the button itself is aligned vertically relative to surrounding text. I'm pretty sure button text is vertically centered by default, though...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Rules-of-thumb doc for mathematical programming in R? Does there exist a simple, cheatsheet-like document which compiles the best practices for mathematical computing in R? Does anyone have a short list of their best-practices? E.g., it would include items like:
*
*For large numerical vectors x, instead of computing x^2, one should compute x*x. This speeds up calculations.
*To solve a system $Ax = b$, never solve $A^{-1}$ and left-multiply $b$. Lower order algorithms exist (e.g., Gaussian elimination)
I did find a nice numerical analysis cheatsheet here. But I'm looking for something quicker, dirtier, and more specific to R.
A: @Dirk Eddelbeuttel has posted a bunch of stuff on "high performance computing with R". He's also a regular so will probably come along and grab some well-deserved reputation points. While you are waiting you can read some of his stuff here:
http://dirk.eddelbuettel.com/papers/ismNov2009introHPCwithR.pdf
There is an archive of the r-devel mailing list where discussions about numerical analysis issues relating to R performance occur. I will often put its URL in the Google advanced search page domain slot when I want to see what might have been said in the past: https://stat.ethz.ch/pipermail/r-devel/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Refactoring 'match' in routes.rb I've read official guide but still have misunderstanding.
Is this code able for refactoring?
match '/help', :to => 'home#help'
match '/contact', :to => 'home#contact'
match '/about', :to => 'home#about'
help, contact and about are the only actions in the controller home.
A: I did this on a hunch and it's not mentioned in the documentation, but it looks like it works (I'm on rails 3.1):
controller :home do
get 'help'
get 'contact'
get 'about'
end
This also creates the help_url, help_path, etc helpers.
One warning though, this restricts the http verbs to GET. If you have a POST action (as an example, for a contact form), you could do either:
controller :home do
get 'help'
match 'contact', :via => [:get, :post]
get 'about'
end
or just:
controller :home do
get 'help'
match 'contact'
get 'about'
end
which will allow all http verbs on the contact route. But I find it better to be explicit about the accepted verbs.
A: You should be able to use rails shorthand here and do:
match 'home/help'
match 'home/contact'
match 'home/about'
Since the method names match this should work.
A: you could of course do
match '/:action', :controller => :home, :constraints => { :action => /^(help|contact|about)$/ }
but this is neither prettier, nor really shorter
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Git Alias - Multiple Commands and Parameters I am trying to create an alias that uses both multiple Git commands and positional parameters. There are Stackoverflow pages for each, and it would appear painfully obvious to do both, but I am having trouble.
As an example, I want to switch to branch foo and perform a status. So in my .gitconfig, I have:
[alias]
chs = !sh -c 'git checkout $0 && git status'
which doesn't work. Whereas something like this will work.
chs = !sh -c 'git checkout $0'
echoes = !sh -c 'echo hi && echo bye'
Any insight would be appreciated.
A: You can define a shell function.
[alias] chs = "!f(){ git checkout \"$1\" && git status; };f"
A: Try this one:
[alias]
chs = "!sh -c 'git checkout \"$0\" && git status'"
Call it like this: git chs master
A: It's possible to have multiline git alias by appending \ at the end of each line.
[alias]
chs = "!git checkout $1 \
; git status \
"
A: The problem here is that the positional parameters seem to be getting sent to the shell command twice (as of git 1.9.2). To see what I mean, try this:
[alias]
test = !git echo $*
Then, do git test this is my testing string. You should observe the following output (last two lines edited here for clarity):
03:41:24 (release) ~/Projects/iOS$ git test this is my testing string
this is my testing string this is my testing string
^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^
#1 #2
One way to work around this would be to
[alias]
chs = !git checkout $1 && git status && git echo x >/dev/null
This will consume the extra positional parameter as it gets applied to that last echo command and have no effect on the results.
A: I was able to create multi-line and quite complex git aliases. They work fine on Windows but I assume they'd work elsewhere too, for example:
safereset = "!f() { \
trap 'echo ERROR: Operation failed; return' ERR; \
echo Making sure there are no changes...; \
last_status=$(git status --porcelain);\
if [[ $last_status != \"\" ]]; then\
echo There are dirty files:;\
echo \"$last_status\";\
echo;\
echo -n \"Enter Y if you would like to DISCARD these changes or W to commit them as WIP: \";\
read dirty_operation;\
if [ \"$dirty_operation\" == \"Y\" ]; then \
echo Resetting...;\
git reset --hard;\
elif [ \"$dirty_operation\" == \"W\" ]; then\
echo Comitting WIP...;\
git commit -a --message='WIP' > /dev/null && echo WIP Comitted;\
else\
echo Operation cancelled;\
exit 1;\
fi;\
fi;\
}; \
f"
I wrote a post and have a few more examples here.
A: An example for people who want to try out what different aliases do.
Putting this in the alias-section of GIT's configuration-file (e.g. ~/.gitconfig) :
[alias]
a0 = "!echo $*"
a1 = "!echo $* #"
a2 = "!f () { echo \"$*\"; }; f "
a3 = "!f () { echo \"$*\"; }; f #"
a4 = "!f () { echo \"$*\"; }; f \"$*\" #"
a5 = "!f () { echo \"$*\"; }; f \"$@\" #"
a6 = "!f () { echo \"$*\"; }; f \"$1\" #"
And then executing this command:
cat ~/.gitconfig | grep --extended-regexp -- '(a[0-9])|(alias)' ; \
echo "" ; \
export CMD ; \
for I in {0..6} ; \
do \
CMD="a""${I}" ; \
echo -n "Executing alias.${CMD} = " ; \
git config --global alias."${CMD}" ; \
git $CMD 'hoi daar' en nu ; \
git $CMD hoi daar en nu ; \
echo "" ; \
done ; \
unset CMD ;
Should give this as output:
[alias]
a0 = "!echo $*"
a1 = "!echo $* #"
a2 = "!f () { echo \"$*\"; }; f "
a3 = "!f () { echo \"$*\"; }; f #"
a4 = "!f () { echo \"$*\"; }; f \"$*\" #"
a5 = "!f () { echo \"$*\"; }; f \"$@\" #"
a6 = "!f () { echo \"$*\"; }; f \"$1\" #"
Executing alias.a0 = !echo $*
hoi daar en nu hoi daar en nu
hoi daar en nu hoi daar en nu
Executing alias.a1 = !echo $* #
hoi daar en nu
hoi daar en nu
Executing alias.a2 = !f () { echo "$*"; }; f
hoi daar en nu
hoi daar en nu
Executing alias.a3 = !f () { echo "$*"; }; f #
Executing alias.a4 = !f () { echo "$*"; }; f "$*" #
hoi daar en nu
hoi daar en nu
Executing alias.a5 = !f () { echo "$*"; }; f "$@" #
hoi daar en nu
hoi daar en nu
Executing alias.a6 = !f () { echo "$*"; }; f "$1" #
hoi daar
hoi
A: [alias]
chs = !git branch && git status
A: This will work (tested with zsh and bash):
[alias] chs = !git checkout $1 && git status
A: This targets Windows batch / msysgit bash; might not work on other environments.
As Olivier Verdier and Lily Ballard have said
[alias] chs = !git checkout $1 && git status
almost works, but gives a spurious extra insertion of the argument ...
git chs demo -> git checkout demo && git status demo
But if you add && : to the end of your alias, then the spurious argument is consumed into a location tag.
So
[alias] chs = !git checkout $1 && git status && :
gives the correct output ...
git chs demo -> git checkout demo && git status
A: [alias]
chs = !git checkout && git status
ac = !git add . && git commit -m
what is ! ?
If the alias expansion is prefixed with an exclamation point, it will be treated as a shell command. What does the exclamation mark mean in git config alias?
To call alias from .gitconfig file
git chs
git ac "write_your_commit_message"
alias is more useful for add and commit in git you can do more fast
A: This is an old post, but no one has provided what I think is the simplest solution. This works in my *nix-based CLI, your mileage may vary.
[alias]
chs = "!git checkout $1; git status"
A simple semi-colon (;) is all you need to run multiple git commands.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "238"
} |
Q: Entity-specific functions in Symfony2 In my Symfony2 project, I have a ModelBundle which holds my entities, and other bundles for the frontend, backend, etc, which utilise that ModelBundle.
I have a couple of model-specific functions that perform some entity-specific tasks.
Where do I put these?
*
*Do I create a seperate 'model' folder next to my Entity folder, and
put all those functions in there?
*Do I create a controller in my 'ModelBundle' that holds these
functions as actions? This might be weird, since controllers, in my
mind, take HTTP requests and return an HTTP response, so it's not
applicable in this context.
*Do I put them inside the entity classes themselves? Is this nice?
And is there a chance that they are over-written when I re-generate
my ORM?
*Am I looking for custom repositories? I can make those and put them into a 'model' folder or something. http://www.doctrine-project.org/docs/orm/2.0/en/reference/working-with-objects.html#custom-repositories
P.S.: I love Symfony2, but I will be very happy when everyone has a defined set of best practices for the framework :-)
A: It'd be helpful to know what type of model-specific functions you plan on writing.
If the functionality is for an entity you've already fetched from the database, it belongs in the entity class.
If the functionality has to do with finding an entity or group of entities based on specific criteria, it belongs in a custom repository class.
I'm not a fan of thinking that model classes and entity classes should be different. IMHO, it's an unnecessary level of abstraction.
You're correct in thinking that this functionality doesn't belong in the controller.
If you do go with custom repositories, I suggest keeping them either in an "Entity" folder, or a "Repository" folder. I personally keep mine in "Entity", but that's likely a side effect of having used Doctrine 1 for so long and being used to 'Table' classes.
I hope this helps, but if you have any questions please post some more details of what you hope to accomplish.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Which platforms will support Visual Studio 11? We all know that windows 8 will be released very soon, and that Visual Studio 11 will be released too. With Visual Studio 11 you can make Metro UI apps exactly like WP7.
My question is that if we program with VS 11, is it supported on Windows 7, Vista and XP?
A: You can install VS11, but you will not be able to develop Metro UI unless you're in Windows 8.
http://social.msdn.microsoft.com/Forums/en-NZ/toolsforwinapps/thread/0155ffb8-b526-46f3-9286-3befd5563b32
That is why they are giving you the Win8 Dev Preview image that you can install VS11 Ultimate and test it out.
Windows 8 Developer Preview Downloads Page
VS11 Developer Preview
A: Here is the best way to install VS11 and develop Metro apps:
http://www.hanselman.com/blog/GuideToInstallingAndBootingWindows8DeveloperPreviewOffAVHDVirtualHardDisk.aspx
A: Visual Studio 11 Beta will only run on Windows 7 or Server 2008 and above.
Targeting depends on the project type. Windows 8 Metro app projects can only be built when running VS11 on the Windows 8 Consumer Preview. But the MFC/CRT etc. can target down to Vista.
What sort of application were you thinking of building?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: range input disable does not work in chrome I am disabling my range input however in chrome it shows it grayed out but it is still usable.
<input type="range" disabled min="0" max="100"/>
I would assume the above would not allow you to change its value.
Am I doing it wrong?
jsFiddle
Relevant specification Disabled
A: Here is the Chrome bug report, guess just need to wait for version 15 as the commenters mentioned.
Bug 54820
A: you can remove all binded events of that specific scroll group to make that scroll disable like:
<div id="fieldset1">
<input type="range" disabled min="0" max="100" readonly="1"/>
</div>
<script>
$(":range").rangeinput();
$('#fieldset1 *').unbind(); // for all events
</script>
its works ..
no need to disable text field; beacause on form submission that field will not be posted ..
A: My solution JSFIDDLE (Works fine in default android browser)
html
<input id="range" type="range" value="10" min="0" max="30" step="10"/>
<button id="disableBtn">Disable</button>
JS
document.getElementById('disableBtn').addEventListener('input', filter);
document.getElementById('disableBtn').addEventListener('click', disable);
function disable(){
document.getElementById('range').disabled = !document.getElementById('range').disabled;
}
function filter(){
if(document.getElementById('range').disabled){
document.getElementById('range').value = document.getElementById('range').defaultValue;
}
}
A: I found a corny solution for chrome, because it doesn't seem like you can disable it from user input. Put a div over it so a user cannot interact with it. Not pretty but works:
<div style="position:relative;">
<div style="position:absolute;z-index:5;width:100%;height:100%;"></div>
<input type="range" disbaled=True min="0" max="100" value="0"/><span id="v">100</span>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: jQuery animate colors plugin only works when clicked? Trying to animate background color on page load but it only works when I actually click the element. I am using the colors plugin.
$(window).load(function () {
$(".hilite").toggle(function() {
$(this).animate({ backgroundColor: "yellow" }, 1000);
},function() {
$(this).animate({ backgroundColor: "#FFF2A8" }, 500);
});
})
<span class="hilite">THIS should change background COLOR</span>
A: You are using no plugin that I can see.
toggle() works on click.
A: As far as I understand, you are trying to do this:
$(document).ready(function(){
$('.hilite').css({'background-color', 'yellow'});
$('.hilite').animate({ 'background-color' : "#FFF2A8" }, 1000);
});
or this:
$(document).ready(function(){
$('body').animate({ 'background-color': "#FFF2A8" }, 1000);
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Linux SoftLink to applications and execution I have created a softlink to an application using the following command:
ln -s sourcedir/Application somedir/ApplicationSoftLink
But I do not know how to start the application using the softlink. My understanding of a softlink is that it is the same as a shortcut in Windows, you just double-click the shortcut and the application will launch. However, when I tried to ./ApplicationSoftLink the application would not start.
Could someone please provide some assistance?
A: ln -s sourcedir/Application somedir/ApplicationSoftLink probably puts the wrong path in your symbolic link.
Try:
ln -s $PWD/sourcedir/Application somedir/ApplicationSoftLink
A: Were you in somedir when you tried running ./ApplicationSoftLink?
I think what you want to do is create the link in some directory in your path, so you don't have to say where the file is at all. You can type
echo $PATH
to find out what's in your path. /usr/local/bin is a good choice for things like this.
A: is sourcedir/Application executable?
when I tried to "./ApplicationSoftLink" the application would not
start.
Is there any error message?
were you typing ./ApplicationSoftLink under "somedir"?
or try ln -s /absolute/path/sourcedir /absolute/path/you/want/somedir/myApp
then under somedir/myApp/ run ./Application
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I change the entire style of a button from code behind in realtime? I have a button that flashes.
I would like to change the entire button style from a resource dictionary when ever it flashes.
I would think it would be like this:
DesktopWindow.AlertButton.Style = (Style)DesktopWindow.Resources["GreenAlertButtonStyle"];
But that doesn't work. How do I do this? I cannot simply change the background color (although that's all I really want to do) because I want to preserve the triggers. When ever I change the background of the button right now, the mouseover triggers stop working....
The button:
<Style TargetType="Button" x:Key="BaseAlertButtonStyle">
<Setter Property="ToolTip" Value="Show Alert List"/>
<Setter Property="Effect" Value="{DynamicResource dropShadow}" />
<Setter Property="Background" Value="{DynamicResource AlertButtonBackground}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Border CornerRadius="5" x:Name="ButtonBorder" Margin="0,0,0,0"
VerticalAlignment="Stretch" BorderThickness="0"
BorderBrush="#ffffff" Padding="0"
Background="{TemplateBinding Background}"
HorizontalAlignment="Stretch">
<Image x:Name="alertImage">
<Image.Source>
<BitmapImage UriSource="/resources/alertIcon.png" />
</Image.Source>
</Image>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Background" Value="{DynamicResource ButtonRolloverBackground}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I dont wanna hear it about doing a search for this issue....
A: Try:
DesktopWindow.AlertButton.Style = FindResource("GreenAlertButtonStyle") as Style;
A: After setting background explicitly you have to clear BackgroundProperty and then set new style.
button1.ClearValue(BackgroundProperty);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Building a graph with draggable nodes I want to populate some user data on the browser as a graph of draggable nodes, with each node representing a user and the edges are relationships between them. I figured out a solution(it works): I use draggable divs over an HTML5 canvas (the divs have a greater z-index than the canvas, and hence are visible). The canvas is then used to draw the lines connecting the divs. The problem is that every time the "drag" event is triggered by the user dragging a node, the entire canvas needs to be cleared and ALL the edges need to be redrawn. That leads to flicker and this, I think, is not the optimal solution. Please note that I'm not really a HTML/CSS pro, and may be my solution is very naive.
I can use any suggestions from you CSS(3)/HTML(5) Gurus. I am open to all sorts of solutions, but would like to avoid Flash/[Silver|Moon]light.
As some example, I really like the Pearltrees interface, but mine need not be that fancy. I tried "reading" main.js from their page source, but its a gazillion functions, all wrapped up in a single line each.
A: You don't have to clear the entire canvas each time it draws. That's just the simplest way to code it.
Instead you can keep track of the line(s) related to the moved node and just redraw that section by drawing over the line with the background color (more complicated if background isn't a solid color), then drawing the new line.
You'll run into complications when you have intersecting lines that you'll need to handle. For simplicity, erasing can be done in rectangles then some math will figure out if you're intersecting other lines, if so they will need to be redrawn as well.
If you want to get really fancy you can redraw in a more granular fashion but rectangles should be sufficient in most cases.
A: i've never done something like this, but if you can use css3, you could use an hr or a a div with just the top border set, and resize and rotate it with jquery + css3.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Problem with displaying AS3 code in Flex I have AS3 script bitfade.text.steel returning type Sprite. It works in Flash environment but not in FLEX. In Flex it displays nothing. No errors appear. It looks like the attached code also works. I use Flex SDK 4.5
Can you give me a clue what the problem with this code might be?
English is not my native language.
If there are any errors please correct me.
Chris
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
creationComplete="creationComplete();" >
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import bitfade.text.steel;
import flash.display.Sprite;
import mx.core.UIComponent;
function creationComplete(){
var textSteel = new steel("config.xml");
if(textSteel is Sprite){
trace("it is a sprite");
}
//var textSteelName:String = getQualifiedClassName(textSteel);
//trace(textSteelName);
textSteel.x = 150;
trace("this is visible on the screen");
var sprite:Sprite = new Sprite();
sprite.graphics.beginFill(0xFFCC00);
sprite.graphics.drawCircle( 40, 40, 40 );
sprite.graphics.endFill();
var wrapper:UIComponent = new UIComponent();
wrapper.addChild(sprite);
wrapper.addChild(textSteel);
animationStage.addElement(wrapper);
}
]]>
</fx:Script>
<s:Group id="animationStage" visible="true" x="50" y="50">
<s:Label text="test">
</s:Label>
</s:Group>
</s:WindowedApplication>
A: If I switch your custom class to a Sprite, and draw something on it, it shows up. Therefore I Believe there is a bug within your steel class. A sprite won't have any size until something is inside it with a size. There is no indication of the code you've shown what happens inside your steel class.
My sample:
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" creationComplete="creationComplete();">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
// import bitfade.text.steel;
import flash.display.Sprite;
import mx.core.UIComponent;
public function creationComplete():void{
var textSteel : Sprite = new Sprite();
if(textSteel is Sprite){
trace("it is a sprite");
}
//var textSteelName:String = getQualifiedClassName(textSteel);
//trace(textSteelName);
textSteel.x = 150;
// JH Code added new
textSteel.graphics.beginFill(0xFFCC00);
textSteel.graphics.drawRect(0,0,100,100);
textSteel.graphics.endFill();
trace("this is visible on the screen");
var sprite:Sprite = new Sprite();
sprite.graphics.beginFill(0xFFCC00);
sprite.graphics.drawCircle( 40, 40, 40 );
sprite.graphics.endFill();
var wrapper:UIComponent = new UIComponent();
wrapper.addChild(sprite);
wrapper.addChild(textSteel);
animationStage.addElement(wrapper);
}
]]>
</fx:Script>
<s:Group id="animationStage" visible="true" x="50" y="50">
<s:Label text="test">
</s:Label>
</s:Group>
</s:WindowedApplication>
A: I think you need to set the width and height of the wrapper UIComponent instance.
UIComponents don't automatically resize to their content so it's showing up with a width and height of 0.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to do flags in C# In C# I have seen enums used in a flag format before. Such as with the Regex object.
Regex regex = new Regex("expression", RegexOptions.Something | RegexOptions.SomethingElse);
If I have a custom enum:
enum DisplayType
{
Normal,
Inverted,
Italics,
Bold
}
How would i format a method to accept multiple enums for one argument such as the syntax for Regex? i.e SomeMethod(DisplayType.Normal | DisplayType.Italics);.
A: Use the FlagsAttribute, like so
[Flags]
enum DisplayType
{
None = 0x0,
Normal = 0x1,
Inverted = 0x2,
Italics = 0x4,
Bold = 0x8
}
A: I know i'm a bit late to the party but I would like to add I this code snippet i keep around because it helps me create Flagged enums when i need them.
[Flags]
enum Generic32BitFlags
{
None = 0, /* 00000000000000000000000000000000 */
Bit1 = 1 << 1, /* 00000000000000000000000000000001 */
Bit2 = 1 << 2, /* 00000000000000000000000000000010 */
Bit3 = 1 << 3, /* 00000000000000000000000000000100 */
Bit4 = 1 << 4, /* 00000000000000000000000000001000 */
Bit5 = 1 << 5, /* 00000000000000000000000000010000 */
Bit6 = 1 << 6, /* 00000000000000000000000000100000 */
Bit7 = 1 << 7, /* 00000000000000000000000001000000 */
Bit8 = 1 << 8, /* 00000000000000000000000010000000 */
Bit9 = 1 << 9, /* 00000000000000000000000100000000 */
Bit10 = 1 << 10, /* 00000000000000000000001000000000 */
Bit11 = 1 << 11, /* 00000000000000000000010000000000 */
Bit12 = 1 << 12, /* 00000000000000000000100000000000 */
Bit13 = 1 << 13, /* 00000000000000000001000000000000 */
Bit14 = 1 << 14, /* 00000000000000000010000000000000 */
Bit15 = 1 << 15, /* 00000000000000000100000000000000 */
Bit16 = 1 << 16, /* 00000000000000001000000000000000 */
Bit17 = 1 << 17, /* 00000000000000010000000000000000 */
Bit18 = 1 << 18, /* 00000000000000100000000000000000 */
Bit19 = 1 << 19, /* 00000000000001000000000000000000 */
Bit20 = 1 << 20, /* 00000000000010000000000000000000 */
Bit21 = 1 << 21, /* 00000000000100000000000000000000 */
Bit22 = 1 << 22, /* 00000000001000000000000000000000 */
Bit23 = 1 << 23, /* 00000000010000000000000000000000 */
Bit24 = 1 << 24, /* 00000000100000000000000000000000 */
Bit25 = 1 << 25, /* 00000001000000000000000000000000 */
Bit26 = 1 << 26, /* 00000010000000000000000000000000 */
Bit27 = 1 << 27, /* 00000100000000000000000000000000 */
Bit28 = 1 << 28, /* 00001000000000000000000000000000 */
Bit29 = 1 << 29, /* 00010000000000000000000000000000 */
Bit30 = 1 << 30, /* 00100000000000000000000000000000 */
Bit31 = 1 << 31, /* 01000000000000000000000000000000 */
Bit32 = 1 << 32, /* 10000000000000000000000000000000 */
}
A: Use the FlagsAttribute. The MSDN documentation explains everything. No point repeating it here.
For your example, you'd say:
[Flags]
enum DisplayType {
None = 0,
Normal = 1,
Inverted = 2,
Italics = 4,
Bold = 8
}
A: See "Enumeration Types as Bit Flags" here: http://msdn.microsoft.com/en-us/library/cc138362.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: css form dropdown list problem On my site css file i have it so all form input backgrounds (textareas, dropdowns etc) have a background color black attribute.
However on one page I'm trying to do a color section dropdown, with the background of each option a different color, eg: blue
This works, when the dropdown is opened, but when i select it, it doesnt show the background color in the currently selected field. Im not sure if the CSS is overriding it or what.
Anyone know how to bypass this?
(Tried to explain best I could)
This is in my css file:
input,textarea,input,select,input,checkbox {
font-size:12px;
font-family:Verdana,Arial,Helvetica,sans-serif;
color:#98925C;
background-color:#000;
border:1px solid #413E22
}
and the code im using on my html page to make the form:
<select size="1" name="color">
<option value=blue style='background-color:blue'>blue</option>
<option value=red style='background-color:red'>red</option>
</select>
etc
A: When the <select> is open, you are seeing the <option> elements and their respective background colors. When you select an option, the <select> element closes its options, leaving you looking at only the <select> element. It makes sense that the <option> background-color does not affect the closed <select> element.
That being said, this looks like a solution:
<select onChange="this.style.backgroundColor=this.options[this.selectedIndex].style.backgroundColor">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Xquery on MarkLogic using OR This is a newbie MarkLogic question. Imagine an xml structure like this, a condensation of my real business problem:
<Person id="1">
<Name>Bob</Name>
<City>Oakland</City>
<Phone>2122931022</Phone>
<Phone>3123032902</Phone>
</Person>
Note that a document can and will have multiple Phone elements.
I have a requirement to return information from EVERY document that has a Phone element that matches ANY of a list of phone numbers. The list may have a couple of dozen phone numbers in it.
I have tried this:
let $a := cts:word-query("3738494044")
let $b := cts:word-query("2373839383")
let $c := cts:word-query("3933849383")
let $or := cts:or-query( ($a, $b, $c) )
return cts:search(/Person/Phone, $or)
which does the query properly, but it returns a sequence of Phone elements inside a Results element. My goal is instead to return all the Name and City elements along with the id attribute from the Person element, for every matching document. Example:
<results>
<match id="18" phone="2123339494" name="bob" city="oakland"/>
<match id="22" phone="3940594844" name="mary" city="denver"/>
etc...
</results>
So I think I need some form of cts:search that allows both this boolean capability but also allows me to specify what part of each document gets returned. At that point then I could further process the result with XPATH. I need to do this efficiently so for example I think it would NOT be efficient to return a list of document uri's and then query for each document in a loop. Thanks!
A: Your approach is not as bad as you might think. There are only a few changes necessary to make it work as you like.
First of all, you are better off using cts:element-value-query instead of cts:word-query. It will allow you to limit the searched values to a specific element. It performs best when you add an element range index for that element, but it is not required. It can rely on the always present word index as well.
Secondly, there is no need for the cts:or-query. Both cts:word-query and cts:element-value-query functions (as well as all other related functions) accept multiple search strings as one sequence argument. They are automatically treated as or-query.
Thirdly, the phone numbers are your 'primary key' in the result, so returning a list of all matching Phone elements is the way to go. You just need to realize that the resulting Phone element are still aware of where they came from. You can easily use XPath to navigate to parent and siblings.
Fourthly, there is nothing against looping over the search results. It may sound a bit weird, but it doesn't cost much extra performance. Actually, it is pretty much negligable, in MarkLogic Server that is. Most performance could be lost when you try to return many results (more than several thousands), in which case most time is lost in serializing it all. And if it is likely you will have to handle lots of search results, it is wise to start using pagination straight away.
To get what you ask, you could use the following code:
<results>{
for $phone in
cts:search(
doc()/Person/Phone,
cts:element-value-query(
xs:QName("Phone"),
("3738494044", "2373839383", "3933849383")
)
)
return
<match id="{data($phone/../@id)}" phone="{data($phone)}" name="{data($phone/../Name)}" city="{data($phone/../City)}"/>
}</results>
Best of luck.
A: Here's what I would do:
let $numbers := ("3738494044", "2373839383", "3933849383")
return
<results>{
for $person in cts:search(/Person, cts:element-value-query(xs:QName("Phone"),$numbers))
return
<match id="{data($person/@id)}" name="{data($person/Name)}" city="{data($person/City)}">
{
for $phone in $person/Phone[cts:contains(.,$numbers)]
return element phone {$phone}
}
</match>
}
First, there's an implicit OR when passing multiple values into word-query and value-query and their cousins, and this query is more efficiently resolved from the indexes, so do this when you can.
Second, an individual might match on more than one phone number, so you need that additional inner loop to effectively group by individual.
I would not create a range index for this - no need, and it isn't necessarily faster. There are indexes for element values by default, so you can leverage those with element-value-query.
You could do all of this with the SearchAPI and a little XSLT. That would make it easy to start combining names and numbers and other conditions in a single query.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jQuery: contains() always returning true I have a parent jQuery object and a child jQuery element.
I'd like to see if the child is already contained within the parent. I was thinking of using jQuery's contains() method. However, in Chrome and IE I always get true returned and in FF6 I get an error a.compareDocumentPosition is not a function
Am I using this incorrectly? Is there a better way to achieve this?
Fiddle
Code:
<div class="metroContainer">
<div class="metroBigContainer">
<div id="big1" class="metroBig">
Stuffs 1
</div>
<div id="big2" class="metroBig">
Stuffs 2
</div>
</div>
<div class="otherContainer">
</div>
// I expect false, returns true
$.contains($('.metroBigContainer'), $('.otherContainer'))
A: I believe contains takes dom elements, not jquery objects:
$.contains($('.metroBigContainer')[0], $('.otherContainer')[0])
A: also you could try testing the length
$('.metroBigContainer .otherContainer').length
if it is 1 (or greater then 1) then it exists if not then it doesn't exist.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7534219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.