text stringlengths 8 267k | meta dict |
|---|---|
Q: How to set initial values of NSPopUpButton at startup in Cocoa I must be missing something obvious here.
I'm trying to load a few items in an NSPopUpButton when the app starts. I added the following code in the init method:
NSArray *listOfProfiles = [[NSArray alloc] initWithObjects:@"My Item 0", @"My Item 1", nil];
[profileListPopUp addItemsWithTitles:listOfProfiles];
NSLog(@"item 0 %@", [profileListPopUp itemTitleAtIndex:0]);
NSLog(@"item 1 %@", [profileListPopUp itemTitleAtIndex:1]);
And the output I get is:
2011-09-24 08:27:39.147 MyApp[3794:707] item 0 (null)
2011-09-24 08:27:39.148 MyApp[3794:707] item 1 (null)
However, if I put the code in another method that's called when pressing a different button, it works fine.
It seems that the init method is called before the NSPopUpButton is created but, in that case, I'd expect it to crash when referencing it.
Where should I put my code?
Bonus question: how do I get rid of the default values (other than calling RemoveAll on the control) that are loaded in the NSPopUpButton: 'Item 1', 'Item2' and 'Item 3'.
A: If you've not heard of the -awakeFromNib or -windowDidLoadNibmethods, now would be a great time to read about them. My guess is your profileListPopUp pointer is at the time you're trying to add items to it because it's not been fully loaded from a nib yet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What HTML5 Tags exactly I can use with html5boilerplate? I am wondering can we use tags like <aside> with Html5Boilerplate. If yes will it browser compatible? and what other tags we can use without fear of older browsers specially IE7 and IE8
A: According to the HTML5BoilerPlate site, it includes Modernizr.
Modernizr is a Javascript library that checks the user's browser for compatibility with various features. It also includes a hack which allows IE6/7/8 to support HTML5 tags.
This hack tells IE that the new HTML5 tags are valid HTML. Without it, IE will ignore these tags. With the hack in place, IE will accept those tags as normal HTML.
But note that this in itself doesn't actually add any new features to IE. Therefore, the new semantic tags like <section> and <nav> are fine, but there still wouldn't be any point using tags which provide new HTML5 functionality such as <video> or <canvas>.
Also note that the hack will obviously only work if the end user has Javascript enabled.
See the Modernizr page for more info on how it works and what it does. See also HTML5Shiv, which is a stand-alone version the same hack.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I strip parenthesis from a string in Ruby? I have a string, like this:
"yellow-corn-(corn-on-the-cob)"
and I would like to strip the parenthesis from the string to get something like this:
"yellow-corn-corn-on-the-cob"
I believe you would use gsub to accomplish this, but I'm not sure what pattern I would need to match the parenthesis. Something like:
clean_string = old_string.gsub(PATTERN,"")
A: Without regular expression:
"yellow-corn-(corn-on-the-cob)".delete('()') #=> "yellow-corn-corn-on-the-cob"
A: Try this:
clean_string = old_string.gsub(/[()]/, "")
On a side note, Rubular is awesome to test your regular expressions quickly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: PHP XML. IP validation My Xml looks like this example:
<?xml version="1.0" encoding="UTF-8"?>
<Allvotes>
<vote score="2" ip="116.971.203.221"/>
<vote score="5" ip="32.97.233.5"/>
<vote score="3" ip="212.977.233.225"/>
<vote score="5" ip="2.80.233.225"/>
</Allvotes>
When on my flash website (AS2), somebody press "vote" button, script in PHP getting his IP... What I want is run specyfic function, depends on his IP exist in xml file or not.
If his IP already exist, PHP send message: "ALREADY VOTED!", when IP doesn't exist in XML, then I want to run function which store his vote score and IP in xml.
So far I know that this PHP script not works:
$dom = new DomDocument('1.0', 'UTF-8');
$myXML = "votes.xml";
$s="";
if ($_POST['todo']=="vote"){
$ip=$_SERVER['REMOTE_ADDR'];
$dom->load($myXML);
$allVotes= $dom->getElementsByTagName('vote');
foreach ($allVotes as $vote){
if ($vote->getAttribute('ip')==$ip){
$s.="&msg= Already Voted";
echo $s;
break;
}else{
doOtherStuff
}
}
}
The problem is that this loop fire "doOtherStuff" function when IP is not in first node...
Is there any magic trick to do that?
A: Why your code does not work
To answer the immediate question: you need to defer the "already voted?" test until you have iterated over all the records:
$alreadyVoted = false;
foreach ($allVotes as $vote){
if ($vote->getAttribute('ip')==$ip){
$alreadyVoted = true;
break;
}
}
if($alreadyVoted) {
$s.="&msg= Already Voted";
echo $s;
}
else {
// other stuff
}
Why you should not do it this way
Storing your data in XML like this is a really inefficient way of doing things. You should move the data store to a database (MySql is typically easiest to set up and work with from PHP).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Changing Property of a Style Dynamically I'm working on a WPF application. I have a Resource Dictionary in which I wrote custom Styles for the ToolTip and for the Button. Actually, for the button i've made two styles.
One of them, has included an image to appear to the left of the content in the buttoon.
<Style x:Key="ButtonImageStyle" TargetType="{x:Type Button}">
........
<TextBlock Margin="5.25,2.417,5.583,5.25" Foreground = White />
<Image x:Name="ButtonImage" Source="/MyProject;component/Images/icoMainMenu01.png" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="-100,0,0,0" Width="16" Height="16"/>
.... </Style
Now, in the MainWindow.xaml i have the following:
<Button Style="{DynamicResource ButtonImageStyle}" x:Name="JustButton" Click="JustButton_Click" Height="50" ToolTip="Press for 1" Content="1" Margin="310,282,400,238" />
I want to be able to change that Image. I will have like 8 buttons and I want each button to have a different image associated with it.
Do you guys have any idea ?
Thanks!
A: There are various options, from (ab)using properties like the Tag to subclassing or composition in a UserControl, you could also create an attached property.
The cleanest would probably be subclassing though, then you can create a new dependency property for the ImageSource to be used which you then can bind in the default template using a TemplateBinding.
To do the subclassing you can use VS, from the new items choose Custom Control (WPF), this should create a class file and add a base-style to a themes resource dictionary which usually is found in Themes/Generic.xaml. The class would just look like this:
//<Usings>
namespace Test.Controls
{
public class ImageButton : Button
{
public static readonly DependencyProperty ImageProperty =
DependencyProperty.Register("Image", typeof(ImageSource), typeof(ImageButton), new UIPropertyMetadata(null));
public ImageSource Image
{
get { return (ImageSource)GetValue(ImageProperty); }
set { SetValue(ImageProperty, value); }
}
}
}
Now the theme would be more complicated, you can just copy one of the default templates for a button and paste it into the the default style. Then you only need to add your image somewhere but with this binding:
<Image Source="{TemplateBinding Image}" .../>
When you use this control you will then no longer need to reference a style, as everything is in the default style, there is now a property for the image:
<controls:ImageButton Content="Lorem Ipsum"
Image="Img.png"/>
(To use the Tag you would just stick with the normal button and use a TemplateBinding to the tag and set the Tag of the buttons to the URL)
I forgot to mention another possiblity which uses dynamic resources, it's a bit verbose but very simple, see this answer of mine for an example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Matching two files with awk codes There are two files
first.file
*
*M1
*M2
*M3
...
second.file
*
*A1 M1
*A2 M1
*A2 M3
*A3 M2
*A3 M4
*A3 M5
....
I want to match first.file to second.file My result file should be like that:
result.file
*
*A1 M1
*A2 M1
*A2 M3
*A3 M2
How can I do that with awk codes ?
Thank you in advance
A: awk '
BEGIN { while (getline < "first.file") { file1[$0]=1 } }
$2 in file1 { print }
' <second.file
A: Use the below:
grep -f firstfile secondfile
grep is enough.
even though we can do this with awk too,i prefer grep
If you still insist on awk,Then i have a very simple solution in awk too.
awk 'FNR==NR{a[$0];next}($0 in a)' file2 file1
Explanation:
Put file2 entries into an array. Then iterate file1, each time finding those entries in the array.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Simple HTTP server in Ruby using TCPServer For a school assignment, I am trying to create a simple HTTP server using Ruby and the sockets library.
Right now, I can get it to respond to any connection with a simple hello:
require 'socket'
server = TCPServer.open 2000
puts "Listening on port 2000"
loop {
client = server.accept()
resp = "Hello?"
headers = ["HTTP/1.1 200 OK",
"Date: Tue, 14 Dec 2010 10:48:45 GMT",
"Server: Ruby",
"Content-Type: text/html; charset=iso-8859-1",
"Content-Length: #{resp.length}\r\n\r\n"].join("\r\n")
client.puts headers
client.puts resp
client.close
}
This works as expected. However, when I have the server tell me who just connected with
puts "Client: #{client.addr[2]}"
and use Chromium (browser) to connect to localhost:2000/ (just once), I get:
Client: 127.0.0.1
Client: 127.0.0.1
Client: 127.0.0.1
Client: 127.0.0.1
I assume this is Chromium requesting auxiliary files, like favicon.ico, and not my script doing something weird, so I wanted to investigate the incoming request. I replaced the resp = "Hello?" line with
resp = client.read()
And restarted the server. I resent the request in Chromium, and instead of it coming back right away, it just hung. Meanwhile, I got the output Client: 127.0.0.1 in my server output. I hit the "stop" button in Chromium, and then the server crashed with
server.rb:16:in `write': Broken pipe (Errno::EPIPE)
from server.rb:16:in `puts'
from server.rb:16:in `block in <main>'
from server.rb:6:in `loop'
from server.rb:6:in `<main>'
Obviously, I'm doing something wrong, as the expected behavior was sending the incoming request back as the response.
What am I missing?
A: I don't really know about chrome and the four connections, but I'll try to answer your questions on how to read the request properly.
First of all, IO#read won't work in this case. According to the documentation, read without any parameters reads until it encounters EOF, but nothing like that happens. A socket is an endless stream, you won't be able to use that method in order to read in the entire message, since there is no "entire" message for the socket. You could use read with an integer, like read(100) or something, but that will block at some point anyway.
Basically, reading a socket is very different from reading a file. A socket is updated asynchronously, completely independent of the time you try to read it. If you request 10 bytes, it's possible that, at this point in the code, only 5 bytes are available. With blocking IO, the read(10) call will then hang and wait until 5 more bytes are available, or until the connection is closed. This means that, if you try repeatedly reading packets of 10 bytes, at some point, it will still hang. Another way to read a socket is using non-blocking IO, but that's not very important in your case, and it's a long topic by itself.
So here's an example of how you might access the data by using blocking IO:
loop {
client = server.accept
while line = client.gets
puts line.chomp
break if line =~ /^\s*$/
end
# rest of loop ...
}
The gets method tries to read from the socket until it encounters a newline. This will happen at some point for an HTTP request, so even if the entire message is transferred piece by piece, gets should return a single line from the output. The line.chomp call will cut off the final newlines if they're present. If the line read is empty, that means the HTTP headers have been transferred and we can safely break the loop (you can put that in the while condition, of course). The request will be dumped to the console that the server has been started on. If you really want to send it back to the browser, the idea's the same, you just need to handle the lines differently:
loop {
client = server.accept
lines = []
while line = client.gets and line !~ /^\s*$/
lines << line.chomp
end
resp = lines.join("<br />")
headers = ["http/1.1 200 ok",
"date: tue, 14 dec 2010 10:48:45 gmt",
"server: ruby",
"content-type: text/html; charset=iso-8859-1",
"content-length: #{resp.length}\r\n\r\n"].join("\r\n")
client.puts headers # send the time to the client
client.puts resp
client.close
}
As for the broken pipe, that error occurs because the browser forcefully breaks the connection off while read is trying to access data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: android google maps import are not recognized i tried to run the project which i found on this link
http://www.anddev.org/google_driving_directions_-_mapview_overlayed-t826.html
i tried to run it on android-sdk_r13-windows . i resolved class path error but still there are some error which i am unable to resolve like
import com.google.android.maps.OverlayController
import com.google.googlenav.DrivingDirection
import com.google.googlenav.map.MapPoint
these import are not recognized by compiler . i used android Google API 2.1 and also i have this entry in my manifest file.
<uses-library
android:name="com.google.android.maps" />
any help on this?
A: The com.google.googlenav package is really old and outdated, it was in the SDK0.9 very very long time ago. If you want to do route calculation, you need to use the Google Maps Web API, not the native API. You can combine both native MapView and it's api (for map display) together with Google Maps Web API (for route calculation) though.
How to calculate and draw a route, see my reply (first one in the list) of thread How to draw a path on a map using kml file?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why unloaded class is still accessible in Cocoa? I loaded a class dynamically with [NSBundle load]. And unloaded it dynamically with [NSBundle unload]. Anyway it looks the class is still alive after unloading.
My code is:
// In separated bundle.
@implementation EEExampleBundle
+ (void)test
{
NSLog(@"TTTTT");
}
@end
// In executable file.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
@autoreleasepool
{
id EEExampleBundle = nil;
@autoreleasepool
{
NSString* path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"EEExampleBundle.framework"];
NSBundle* sampleBundle = [NSBundle bundleWithPath:path];
[sampleBundle load];
EEExampleBundle = (id)[sampleBundle classNamed:@"EEExampleBundle"];
[EEExampleBundle test];
BOOL r = [sampleBundle unload];
NSLog(@"unload result = %d", r);
}
[EEExampleBundle test];
}
return 0;
}
The output is:
2011-09-25 01:08:52.713 driver[2248:707] TTTTT
2011-09-25 01:08:52.714 driver[2248:707] unload result = 1
2011-09-25 01:08:52.716 driver[2248:707] TTTTT
Why the class code is still working? Is this normal? Or should I do any extra step to unload the code completely?
P.S
I'm not using ARC. I turned it off explicitly.
A: (more of a comment than an answer, nevertheless:) That's due to the inner @autoreleasepool block, no? You won't be able to create a new instance from your bundle, but you do keep the ones already created alive (else, that'd generate fancy bugs).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: No current session context set error in my Nhibernate Test project I'm getting the error:
No CurrentSessionContext configured (set the property current_session_context_class).
I'm not sure what to put there, I have this:
public class NhDbHelper
{
public NhDbHelper()
{
CreateSessionFactory();
}
private ISessionFactory _sessionFactory;
public ISessionFactory SessionFactory
{
get { return _sessionFactory; }
}
private void CreateSessionFactory()
{
_sessionFactory = Fluently
.Configure()
.Database((MsSqlConfiguration.MsSql2008 //
.ConnectionString(@"Server=.\SQLExpress;Database=abc;Uid=sa;Pwd=123;")
.ShowSql()))
.Mappings(m => m.FluentMappings
.AddFromAssemblyOf<UserMap>())
.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true))
.BuildSessionFactory();
}
}
Then in my repository I just use the SessionFactory property in the helper.
A: in your "Fluently", before the ".Mappings(----) statement, you need to specify CurrentSessionContext. To do so, assuming you're using it in a Web Context,you would insert above the ".Mappings" line as shown below. (I've also modified retrieving connection strings' value, thanks to Fluent:
private void CreateSessionFactory()
{
_sessionFactory = Fluently
.Configure()
.Database((MsSqlConfiguration.MsSql2008 //
.ConnectionString(c=>c.FromConnectionStringWithKey("abc"))
.ShowSql()))
.CurrentSessionContext("web")
.Mappings(m => m.FluentMappings
.AddFromAssemblyOf<UserMap>())
.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true))
.BuildSessionFactory();
}
A: I am guessing you are getting this property when you are trying to use sessionFactory.GetCurrentSesssion()
_config.ExposeConfiguration(cfg => cfg.Properties.Add("current_session_context_class", "thread"));
Also I would suggest you use sessionFactory.OpenSession()
A: For people using web session context: .CurrentSessionContext("web"), the session is stored in HttpContext.Items which will not exist for your unit tests.
.CurrentSessionContext("thread_static") can be used instead in unit tests.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Modifying a JSON object by creating a New Field using existing Elements I have a javascript object that goes like this:
var obj = {"data":
[
{"name":"Alan","height":1.71,"weight":66},
{"name":"Ben","height":1.82,"weight":90},
{"name":"Chris","height":1.63,"weight":71}
]
,"school":"Dover Secondary"
}
How do I create a new field called BMI using weight/(height)^2 such that the new object becomes:
var new_obj = {"data":
[
{"name":"Alan","height":1.71,"weight":66,"BMI":22.6},
{"name":"Ben","height":1.82,"weight":90,"BMI":27.2},
{"name":"Chris","height":1.63,"weight":71,"BMI":26.7}
]
,"school":"Dover Secondary"
}
A: var persons = obj.data;
var new_obj = {data: [], school: obj.school};
for(var i=0; i<persons.length; i++){
var person = persons[i];
new_obj.data.push({
name: person.name,
height: person.height,
weight: person.weight,
BMI: Math.round(person.weight / Math.pow(person.height, 2)*10)/10;
});
/* Use the next line if you don't want to create a new object,
but extend the current object:*/
//persons.BMI = Math.round(person.weight / Math.pow(person.height, 2)*10)/10;
}
After new_obj is initialised, a loop walks through array obj.data. The BMI is calculated, and added along with a copy of all properties to new_obj. If you don't have to copy the object, have a look at the commented part of the code.
A: Try with this code, in this below code I used same object to add one more field. We can also have copy of the original object by copying existing one to temp variable
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Modifying a JSON object by creating a New Field using existing Elements</title>
</head>
<body>
<h2>Modifying a JSON object by creating a New Field using existing Elements</h2>
<script type="text/javascript">
var obj = { "data":
[
{ "name": "Alan", "height": 1.71, "weight": 66 },
{ "name": "Ben", "height": 1.82, "weight": 90 },
{ "name": "Chris", "height": 1.63, "weight": 71 }
]
, "school": "Dover Secondary"
}
alert(obj.data[0].weight);
var temp=obj["data"];
for (var x in temp) {
var w=temp[x]["weight"];
var h=temp[x]["height"];
temp[x]["BMI"] = (w / (h) ^ 2) ;
}
alert(obj.data[1].BMI);
</script>
</body>
</html>
A: var data = obj['data'];
for( var i in data )
{
var person = data[i];
person.BMI = (person.weight/ Math.pow(person.height, 2)).toFixed(2) ;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Am I missing something? Reading from database in PHP seems long-winded So, if I want to pull some data from my database (PHP, MySql), whether I'm writing for a class or hard-coded, I've been doing something along the lines of:
$x = "SELECT <column(s)> FROM <table> WHERE <conditions>";
$y = mysql_query($x);
while($result = mysql_fetch_assoc($y))
{
echo $result['column']; // etc
}
Obviously I use a function or class (depending on design pattern) so pulling data like this is done in one line, I just wondered if I was doing 'too much work' and if there was a quicker way of doing this.
Thanks.
A: Looks good. you maybe can merge the first tow lines into "$y = mysql_query('SELECT FROM WHERE ');"
And notice that in PHP its faster (from compile time) to use single quotes (') rather that double quotes (").
It depends on the further work, but you might wanna consider loading the info into XML dom format. (If you want to do more sophisticated things that just representing the data)
A: You can get tighter code by using a more up-to-date PHP module to access your database.
The mysql_xxx() functions that you're using have been superseded by the mysqli_xxx() functions. This uses similar code, but provide more features and security than the older library:
$query = 'SELECT <column(s)> FROM <table> WHERE <conditions>';
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
print $row['column'];
}
}
You can find out more about MySQLi (including how it differs from the old MySQL library) here: http://php.net/manual/en/book.mysqli.php
But for really concise code, you might consider looking into the PDO library. Your query could be expressed with PDO like this:
$sql = 'SELECT <column(s)> FROM <table> WHERE <conditions>';
foreach ($conn->query($sql) as $row) {
print $row['column'];
}
...and if you really wanted to, the first two lines of that code could be combined as well.
Find out more about PDO at the PHP manual site: http://www.php.net/manual/en/book.pdo.php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the most bandwidth efficient video codec? Say I want to let my users upload videos to my website(using PHP) and also let them watch other videos. But I want it to work really bandwidth efficient and I want to somehow compress/convert the videos and make them smaller in size, with minimal loss of quality. Is there any particular extension which is pretty much what I want? Any additional information about conversion/extensions/file size/ bandwidth is also appreciated.
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Assembler and c++ output text How can I display text with assembler in c++ code? I want to make a function with a parameter the string which will be displayed.
A: In the assembler you can make the appropriate system calls to read or write. Your OS will have a description of the supported system calls, and generally there is some sort of operation (eg interrupt 80h or sys call instruction) to make a system call.
Without more details (eg operating system or hardware) that's as specific as I can get.
A: I suggest you write a sample application with a prinf in it and look at the compiled code. In VS you can easily do this while debugging, just go to "Show dissasembly". Not sure how you would do it under *nix, but I'm pretty sure it's doable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the right way to rewrite Mozilla Thunderbird's thread pane? I have an idea about alternate standard view of e-mail clients, like Mozilla Thunderbird. I need to display expanded message bodies in one feed (like Google Reader displays RSS) instead of headers list + one message body.
Let me visualize this. Standard view: http://i.stack.imgur.com/R5OZ4.jpg. Google reader view: http://i.stack.imgur.com/CRBoM.jpg
I suppose that correct way is to hide XUL elements like threadPaneBox and messagepanebox and instead insert one new element. On startup i will load current folder's messages and render them in this new container.
So, question is - Is it right way to customize message view in Thunderbird? What is the right way to do this? What is the right place to ask this question (maybe it will be better go to some Thunderbird developers forum)? And finally, is writing extension for Thunderbird is best method to bring my idea to live?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Rails: filter index via dropdown and checkboxes I'm trying to filter an index page of products via a dropdown menu (locations) and a set of checkboxes (categories) and not being very successful with it. I can filter via a dropdown for either location or category. I can also combine the two dropdowns within the one form but if I can't get a working solution to two separate forms.
What i'd like to achieve is a dropdown for location that submits onchange and the categories I'd like to have as checkboxes with a filter button.
The code I have at the moment provides the dropdown and checkboxes but there are some problems:
*
*the checkboxes list all the categories but when I filter based on these the params are passed as an array but no products are returned in the view
*whenever I filter by category i lose the previous location selection
Here's the relevant code:
Product Model
....
has_many :categorizations
has_many :categories, :through => :categorizations
has_many :localizations
has_many :locations, :through => :localizations
class Product < ActiveRecord::Base
default_scope :order => 'end_date'
scope :not_expired, where('end_date > ?', Time.now)
scope :location, lambda { |*location_id| {:include => :locations, :conditions => ["locations.id = ?", location_id]} }
scope :category, lambda { |*category_id| {:include => :categories, :conditions => ["categories.id = ?", category_id]} }
scope :unique, :group => "title"
Controller
class LibraryController < ApplicationController
def index
if params[:location_id] && params[:category_ids]
@products = Product.not_expired.unique.location(params[:location_id]).category(params[:category_ids]).paginate(:page => params[:page], :per_page => 9)
elsif params[:category_ids]
@products = Product.not_expired.unique.category(params[:category_ids]).paginate(:page => params[:page], :per_page => 9)
elsif params[:location_id]
@products = Product.not_expired.unique.location(params[:location_id]).paginate(:page => params[:page], :per_page => 9)
else
@products = Product.not_expired.unique.paginate(:page => params[:page], :per_page => 9)
end
end
end
Library index.html.erb
<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<div class="filter_options">
<form class="filter_locations", method="get">
<% @options = Location.all.map { |a| [ a.name, a.id ] } %>
<%= select_tag "location_id", options_for_select(@options), :onchange => "this.form.submit();", :include_blank => true %>
</form>
<form class="filter_categories", method="get">
<% for category in Category.all %>
<%= check_box_tag("[category_ids][]", category.id) %>
<%= category.name %>
<% end %>
<input type="submit" value="Filter" />
</form>
</div>
I've been going around in circles with this so any direction is greatly appreciated.
to part answer my own question I've modified the library index and used a hidden field in the category form that calls for the location_id param, if it exists, which means I can retain any location selection that's been made after selecting category checkboxes.
Further update is I've added a check for whether the category checkbox is checked by querying the params, updated library index.html.erb below.
Last edit with @rdvdijk input incorporated (Thanks)
library index.html.erb
.......
<%= form_tag( '', :method => :get ) do %>
<% @options = Location.all.map { |a| [ a.name, a.id ] } %>
<%= select_tag "location_id", options_for_select((@options), params[:location_id]), :onchange => "this.form.submit();", :include_blank => true %>
<% end %>
<%= form_tag( '', :method => :get ) do %>
<% if(params.has_key?(:location_id)) %>
<%= hidden_field_tag 'location_id', params[:location_id] %>
<% end %>
<% Category.all.each do |category| %>
<%= check_box_tag 'category_ids[]', category.id, params[:category_ids].to_s.include?(category.id_to_s) %>
<%= category.name %>
<% end %>
<%= submit_tag 'Filter' %>
<% end %>
.......
A: You have two forms, I think that is part of your problem. Whenever you change a location in the first form, only the location_id will be sent to your controller index action. Whenever your select a category and submit the second form, only the category_ids will be sent to your controller index action.
Use one form and see what happens. It should at least make the filtering work for a single submit.
The second problem I see is that you don't select the chosen location, or check the chosen categories.
Take a look at the documentation for options_for_select and check_box_tag to fix that.
A: In my case, product belongs_to :category and category has_many :products, I modified categories.id to category_id, it works!
scope :category, lambda { |*category_id| {:include => :categories, :conditions => ["category_id = ?", category_id]} }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why doesn't terse way of defining new hashes in Ruby work (they all refer to same object) I need to establish a number of Hashes, and I didn't want to list one per line, like this
a = Hash.new
b = Hash.new
I also new that apart from for Fixnums, I could not do this
a = b = Hash.new
because both a and b would reference the same object. What I could to is this
a, b, = Hash.new, Hash.new
if I had a bunch it seemed like I could also do this
a, b = [Hash.new] * 2
this works for strings, but for Hashes, they still all reference the same object, despite the fact that
[Hash.new, Hash.new] == [Hash.new] * 2
and the former works.
See the code sample below, the only error message triggered is "multiplication hash broken". Just curious why this is.
a, b, c = [String.new] * 3
a = "hi"
puts "string broken" unless b == ""
puts "not equivalent" unless [Hash.new, Hash.new, Hash.new] == [Hash.new] * 3
a, b, c = [Hash.new, Hash.new, Hash.new]
a['hi'] = :test
puts "normal hash broken" unless b == {}
a, b, c = [Hash.new] * 3
a['hi'] = :test
puts "multiplication hash broken" unless b == {}
A: In answer to the original question, an easy way to initialize multiple copies would be to use the Array.new(size) {|index| block } variant of Array.new
a, b = Array.new(2) { Hash.new }
a, b, c = Array.new(3) { Hash.new }
# ... and so on
On a side note, in addition to the assignment mix-up, the other seeming issue with the original is that it appears you might be making the mistake that == is comparing object references of Hash and String. Just to be clear, it doesn't.
# Hashes are considered equivalent if they have the same keys/values (or none at all)
hash1, hash2 = {}, {}
hash1 == hash1 #=> true
hash1 == hash2 #=> true
# so of course
[Hash.new, Hash.new] == [Hash.new] * 2 #=> true
# however
different_hashes = [Hash.new, Hash.new]
same_hash_twice = [Hash.new] * 2
different_hashes == same_hash_twice #=> true
different_hashes.map(&:object_id) == same_hash_twice.map(&:object_id) #=> false
A: My understanding is this. [String.new] * 3 does not create three String objects. It creates one, and creates a 3-element array where each element points to that same object.
The reason you don't see "string broken" is that you have assigned a to a new value. So after the line a = "hi", a refers to a new String object ("hi") while b and c still refer to the same original object ("").
The same occurs with [Hash.new] * 3; but this time you don't re-assign any variables. Rather, you modify the one Hash object by adding the key/value [hi, :test] (via a['hi'] = :test). In this step you've modified the one object referred to by a, b, and c.
Here's a contrived code example to make this more concrete:
class Thing
attr_accessor :value
def initialize(value)
@value = value
end
end
# a, b, and c all refer to the same Thing object
a, b, c = [Thing.new(0)] * 3
# Here we *modify* that object
a.value = 5
# Verify b refers to the same object as a -- outputs "5"
puts b.value
# Now *assign* a to a NEW Thing object
a = Thing.new(10)
# Verify a and b now refer to different objects -- outputs "10, 5"
puts "#{a.value}, #{b.value}"
Does that make sense?
Update: I'm no Ruby guru, so there might be a more common-sense way to do this. But if you wanted to be able to use multiplication-like syntax to initialize an array with a bunch of different objects, you might consider this approach: create an array of lambdas, then call all of them using map.
Here's what I mean:
def call_all(lambdas)
lambdas.map{ |f| f.call }
end
a, b, c = call_all([lambda{Hash.new}] * 3)
You can verify that this approach works pretty easily:
x, y, z = call_all([lambda{rand(100)}] * 3)
# This should output 3 random (probably different) numbers
puts "#{x}, #{y}, #{z}"
Update 2: I like numbers1311407's approach using Array#new a lot better.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Disable text input history
Possible Duplicate:
How do you disable browser Autocomplete on web form field / input tag?
I am building an application which will be accepting credit card data. I would like to make sure that the browser does not remember what has been typed into the text inputs for credit card number. I tried passing the following headers:
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
Still, once the page reloads, I can click the credit card text input field and it will let me see what I wrote in it before. How can I prevent this?
A: <input type="text" autocomplete="off"/>
Should work. Alternatively, use:
<form autocomplete="off" … >
for the entire form (see this related question).
A: <input type="text" autocomplete="off" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "116"
} |
Q: association id not getting set using accepts_nested_attributes_for and decent_exposure When I post a form to create a new inquiry with a child comment (in the app, inquiries can have multiple comments), the comment is not getting built. It works when remove the presence validations. So it has to do with the order in which things are built and saved. How to preserve the validations and keep the code clean?
(The following is an example so it may not be exactly runable)
models/inquiry.rb
class Inquiry < ActiveRecord::Base
has_many :comments
accepts_nested_attributes_for :comments
models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :inquiry
belongs_to :user
validates_presence_of :user_id, :inquiry_id
controllers/inquiry_controller.rb
expose(:inquiries)
expose(:inquiry)
def new
inquiry.comments.build :user => current_user
end
def create
# inquiry.save => false
# inquiry.valid? => false
# inquiry.errors => {:"comments.inquiry_id"=>["can't be blank"]}
end
views/inquiries/new.html.haml
= simple_form_for inquiry do |f|
= f.simple_fields_for :comments do |c|
= c.hidden_field :user_id
= c.input :body, :label => 'Comment'
= f.button :submit
database schema
create_table "inquiries", :force => true do |t|
t.string "state"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "comments", :force => true do |t|
t.integer "inquiry_id"
t.integer "user_id"
t.text "body"
t.datetime "created_at"
t.datetime "updated_at"
end
A: Basically, before saving you are also testing the presence of inquiry_id, the return association from comment to inquiry, that cannot be set until the comment is saved. An alternate way to achieve this and still have your validations intact would be the following:
comment = Comment.new({:user => current_user, :body => params[:body]
comment.inquiry = inquiry
comment.save!
inquiry.comments << comment
inquiry.save!
Or an alternate way would be
= simple_form_for inquiry do |f|
= f.simple_fields_for :comments do |c|
= c.hidden_field :user_id
= c.hidden_field :inquiry_id, inquiry.id
= c.input :body, :label => 'Comment'
= f.button :submit
Basically adding the following line in your comments form
= c.hidden_field :inquiry_id, inquiry.id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How do I get a column from mySQL to show up in a select box via PHP? I have a form with one select box (pulldown list). I need to get a column from mySQL to appear in the select box. How do i make the connection? Are there any examples out there?
A: <?php
// connect to MySQL
$query = "SELECT <col> FROM <table>";
$result = mysql_query($query);
?>
<select name="sel" id="sel">
<?php
while($row = mysql_fetch_assoc($result)){
echo "<option>{$row['<col>']}</option>";
}
?>
</select>
If you need to have the first option empty, just print this line after the select tag:
<option></option>
A: I've not clearly understood, what ever you want to say, but you can try the below solution.
<select name="example">
<?php
// Database connetcion goes here
$q=mysql_query("SELECT option1 FROM table"); /// where option1=the column you want to show
while ($sql=mysql_fetch_row($q)){
echo "<option value='".$q['0']."'>".$q['0']."</option>";
}
/// keep this code block wher you want to show the pull down select box
?>
</select>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Close Chrome with extension Is it possible to close the entire application within a chrome extension?
A: You would have to use the Chrome Windows API to close all windows:
chrome.windows.getAll({}, function(windows){
for(var i = 0; i < windows.length; i++)
chrome.windows.remove(windows[i].id);
});
To just close a tab, use chrome.tabs.remove().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Run java application with maximum "maximum heap size" available How can I calculate the maximum "maximum heap size" avalable for java application
*
*in Windows using cmd commands?
*in Linux using sh commands?
I want to set -Xmx value as large as possible.
I want to be sure that java will not complain that -Xmx value is too large.
From a linked answer to another question I learned the following values for 32-bit Java:
OS: Windows XP SP2, JVM: Sun 1.6.0_02, Max heap size: 1470 MB
OS: Windows XP SP2, JVM: IBM 1.5, Max heap size: 1810 MB
OS: Windows Server 2003 SE, JVM: IBM 1.5, Max heap size: 1850 MB
OS: Linux 2.6, JVM: IBM 1.5, Max heap size: 2750 MB
How do I automatically detect which OS and which Java is installed?
OK, I can default to the minimum value - 1470 MB.
But how can I be sure that in newer versions of Java this value will not shrink?
The question also remains open for 64-bit Java.
A: Try to run java with 2 gigabytes or memory, decrease the amount, repeat until java runs.
Linux:
#!/bin/sh
let mem=2000
while [ 1 ]
do
java "-Xmx"$mem"m" -version > /dev/null 2>&1
if [ $? -eq 0 ]
then
break
fi
let mem=$mem-100
if [ $mem -lt 100 ]
then
#// something went wrong with our test
let mem=700
break
fi
done
echo $mem
Windows:
@echo off
setlocal enabledelayedexpansion
set mem=2000
:decmem
set /a mem=mem-100
if !mem! == 0 (
rem // something went wrong with our test
set mem=700
goto start
)
java -Xmx!mem!m -version > nul 2> nul
if errorlevel 1 goto decmem
:start
echo !mem!
A: This question will never get a direct answer. There are a lot of variables in deciding maximum heap size. And of the top of my head, i can think of:
*
*OS you are using
*Ram size of your machine
*applications that are running. or other applications RAM usage
So what i can suggest is try to find the max. heap size your java application needs for running at most of the time.
Still if you need to find the max size, here are the facts i have heard or read about
*
*XP uses 1 GB RAM
*Vista/Seven uses at least 2-3 GB for smooth running
*I think Linux ram size was arround 1-2 GB
Now we can hope that your JAVA VM wont run the full time. So we can ignore the other machines running in your system for the time being.
So your RAM size - OS RAM size would give you your required heap size.
Still i would suggest you decide your heap size depending on your java application requirement.
A: There are a number of things to consider. There are two real limits for memory, first is the limit of maximum addressible memory and second is the total available virtual memory in your environment.
1) The virtual memory is (usually) made up of RAM plus swap space (disk-backed virtual memory). This memory pool is used by all processes running on your machine (including the OS). The total memory used must be less than the total available virtual memory (attempts to exceed this limit will result in errors in one or more processes).
2) The maximum addressible memory is a per-process limit on the amount of memory that can be mapped to that process. Some of the per-process memory map may be reserved for the OS/kernel. The main factor for what will be available is whether the process is 32- or 64-bit. Typically 64-bit processes don't need to worry about the limit (yet ;)) as it is very high (although this does depend on architecture).
Threoretically, 32-bit processes can address up to 4GigaBytes and 64-bit processes can address up to 16ExaBytes (in practice most 64-bit processors do not support the full amount).
Let's talk 32-bit from now on...
The OS/kernel will usually reserve a chunk of address space for its own use. For example, by default Windows reserves 2GB of address space (although there is a switch that will reduce this to 1GB). The Linux kernel will usually reserve 1GB (although this can be reduced to almost nothing with a kernel change).
So, this leaves you with 2GB on Windows 32-bit and 3GB on Linux 32-bit for your Java VM. Consider that there is a bunch of memory the JVM needs that is NOT part of the Java Heap, so your heap will have to be somewhat smaller than these amounts - how much will vary depending on your application and the JVM implementation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to remove margin from every element that is the last element in a row? How to remove margin from every <li> of last column? I'm asking for every <li> which comes in last column when I have 9 <li> and 3 in each column. I'm not asking just to remove margin from last item of last <li> of a <ul> which I already know :last-child { margin-right: 0 }
And if screen is small or user resize the browser then 3 + 3 + 3 can become to 4 + 5 or 2 + 2 + 2 + 2 + 1
So in any condition any <li> ( it can be one or more then one) which comes in last column. I want to remove margin-right.
All li are within a single ul
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
<li>item 5</li>
<li>item 6</li>
<li>item 7</li>
<li>item 8</li>
<li>item 9</li>
</ul>
I added jsfiddle here: http://jsfiddle.net/GnUjA/1/
A: Removing or adding stylings on a specific element of each row cannot be done with pure CSS unless you know exactly how many elements there are per row (via the nth-child() family of selectors).
Negative Margins
What you can to do in the case of margins is disguise them by adding negative margins on the parent element. This will give the illusion that your child elements fit inside the parent element while still having spacing between the individual elements:
http://codepen.io/cimmanon/pen/dwbHi
ul {
margin-left: -5px;
margin-right: -5px;
}
li {
margin-left: 5px;
margin-right: 5px;
}
Splitting the margin in half and setting it on both sides (margin-left: 5px; margin-right: 5px) may give better results than a single margin on one side (margin-right: 10px), particularly if your design needs to work with LRT and RTL directions.
Note: this may require adding overflow-x: hidden on an ancestor element to prevent horizontal scrolling, depending on how close the container element is positioned to the edge of the viewport.
Media Queries
If you can reasonably predict how many items there are going to be per row, you can use media queries to target the last item in the row via nth-child(). This is considerably more verbose than using negative margins, but it would allow you to make other style adjustments:
@media (min-width: 400px) and (max-width: 499px) {
li:nth-child(even) {
margin-right: 0;
border-right: none;
}
}
@media (min-width: 500px) and (max-width: 599px) {
li:nth-child(3n+3) {
margin-right: 0;
border-right: none;
}
}
@media (min-width: 600px) and (max-width: 799px) {
li:nth-child(4n+4) {
margin-right: 0;
border-right: none;
}
}
/* etc. */
A: I believe this is what you want (jquery):
http://jsfiddle.net/PKstQ/
If that fiddle demonstrates what you are looking to do (except with margin instead of background-color) then you can't do that with css. You will need javascript. If jquery is acceptable then that posted fiddle can easily be modified. Would be relatively trivial to turn it into pure js as well.
A: To me it makes more sense to give the left side of ul some padding that evens it out.
I added: ul { padding-left: 10px; } - http://jsfiddle.net/GnUjA/30/
Depends if it would be necessary but same really goes to the top:
ul { padding-top: 10px; padding-left: 10px; } - http://jsfiddle.net/GnUjA/31/
A: Edit: Answer rewritten after looking at sample HTML
What you want to do is not possible with CSS. The reason is that you want to style elements based on the rendered layout, which CSS only allows you to work based on the document structure.
Something like this is only achievable with client-side scripting (Javascript), which can query rendered layout properties and act accordingly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: HTML form data to XML and vice versa I have followed this tutorial and uploaded this on to my website and i am getting errors i would like to follow this example and understand it and create my own form that can save data to xml file and also display the xml data in the html page
my website page for the above tutorial uploaded link is this
The processform.asp code exactly in the server is as follows
http://www.xmlfiles.com/articles/michael/htmlxml/default.asp--> as the processform.asp no less no more
i am just getting error with out the error explanation i am new to this pls be clear in your answer thanks
A: I found this tutorial to be really useful and solved my problem but this requires C# proramming experience which i posses briefly
so this is the website
http://www.java2s.com/Code/ASP/XML/SaveformdatatoXMLfile.htm
you have to enable IIS on your windows system and run this by putting in the inetpub/wwwroot/(your own foldername)/(file name saved as .aspx)
also make sure that inetpub folder in the C: drive is granted permissions for IISUSers this can be done by following the below steps
right click the inetpub folder and go to security tab and click edit and click add and click advanced and click findnow and find IIS_IUSRS and grant full permissions to it so as to create the book.xml file dynamically
Then go to ur fav internet browser and type localhost/(your own foldername)/(file name saved as .aspx). Then you can see the page in action if any queries feel free to ask me personally i will try to help you to the best of my knoweledge..
I am not sure why people gave a negative point to this question
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: javascript closure tutorial from eloquent javascript the question is pretty similar to this thread Javascript..totally lost in this tutorial.
function findSequence(goal) {
function find(start, history) {
if (start == goal)
return history;
else if (start > goal)
return null;
else
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
}
return find(1, "1");
}
print(findSequence(24));
I got stuck at this part :
find(start * 3, "(" + history + " * 3)");
each time start goes beyond goal what does it do? it says it return null but when I test and put breakpoint on
if (start == goal) it shoes this on the console
history: "(((((1 + 5) + 5) + 5) + 5) + 5)"
start: 26
history: "(((((1 + 5) + 5) + 5) + 5) * 3)"
start: 63
it add up *3 and take off +5, I don't understand how.
A: The return statement:
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
is an expression involving the "||" operator. That operator will cause the left-hand side to be evaluated. If the result of that is not null, zero, false, or the empty string, then that value will be returned. If it is one of those "falsy" values, then the second expression is evaluated and returned.
In other words, that could be re-written like this:
var plusFive = find(start + 5, "(" + history + " + 5)");
if (plusFive !== null)
return plusFive;
return find(start * 3, "(" + history + " * 3)")
If "start" ever exceeds "goal", the function returns null. Of course, if both the alternatives don't work, then the whole thing will return null.
A: The expression:
find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)")
Will first attempt to evaluate:
find(start + 5, "(" + history + " + 5)")
If the returned value is not null, 0, false, or the empty string then the statement evaluates to the returned value.
If the returned value is null, 0, false, or the empty string then the following will be evaluated next:
find(start * 3, "(" + history + " * 3)")
If the returned value is not null, 0, false, or the empty string, then the statement evaluates to the returned value.
If the returned value is null, 0, false, or the empty string, then the statement evaluates to null, 0, false, or the empty string (whichever was returned by the *3 function call).
So the line:
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)")
is like saying "I'm going to try to find the solution by guessing that I add 5 at this step, and if that doesn't work I'll try to multiply by 3 at this step, and if that doesn't work I give up!"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CSS Webpage elements are not positioning correctly I am trying to code a design into HTML and CSS. It is a small snippet. I am having issues with the positioning and cant seem to put elements in their correct places.
My webpage can be found at http://www.sarahjanetrading.com/js/j/index.html
The design that I want to copy can be found here: http://www.sarahjanetrading.com/js/j/people-list.png
I also want the checkbox input to look like the one in the design. Can checkboxes be styled?
A: Change Your CSS like this :
#people-list #content h2 {
font-size: 16px;
float: left;
margin-left: 10px;
margin-top: 5px;
width: 355px;
}
#people-list #content small {
font-size: 12px;
color: #8F9092;
margin: 5px 0 8px;
display: block;
float: left;
width: 355px;
display: block;
margin-left: 9px;
}
#people-list #content .tags {
border-radius: 7px;
box-shadow: inset 0px 6px 2px 8px #f5f5f5;
border: 1px solid #E3E3E3;
padding: 2px;
font-size: 9px;
margin-right: 3px;
margin-left: 10px;
}
and Check this link for styling checkbox
http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/
A: yes ,checkbox can be styled, try to put the buttons in a div and change the display attribute to inline
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Using Open Graph API, can I see when users Add To Playlist or Star tracks in Spotify? How would I access when a user (and a friend of a user) adds a song to a playlist, or stars a song in Spotify, Rdio etc?
A: http://graph.facebook.com/me/music.listens
http://graph.facebook.com/me/music.playlists
You have to get the user_actions.music permission before you can read those.
A: The correct permissions is user_actions:music, not a dot.
*
*user_actions:music
*user_actions:video
*user_actions:news
http://graph.facebook.com/me/music.listens
http://graph.facebook.com/me/music.playlists
Those 2 endpoints still returns empty arrays.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: sqlite3_prepare_v2 no such table error I have a sqlite problem.
My code above:
-(NSString *) filePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"Yok_Artik.sqlite"];
return dbPath;
}
-(void) openDB {
if (sqlite3_open([[self filePath] UTF8String], &db) == SQLITE_OK) {
const char *sqlStatement = "SELECT content, image FROM yok_artik ORDER BY RANDOM() LIMIT 1;";
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(db, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
if (sqlite3_step(compiledStatement) == SQLITE_ROW) {
NSString *myContent = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
yaContent.text = myContent;
} else {
NSLog(@"Error (sqlite3_step): %s", sqlite3_errmsg(db));
}
} else {
NSLog(@"Error (sqlite3_prepare): %s", sqlite3_errmsg(db));
}
} else {
NSLog(@"Error (sqlite3_open): %s", sqlite3_errmsg(db));
}
}
I have error at sqlite3_prepare_v2 command
error message:
Error (sqlite3_prepare): no such table: yok_artik
How can I fix this problem?
BTW, sqlite3_open working fine.
A: My error is filePath. I change it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: UINavigationController back button action problem I have an UINavigationController and the first view is an UIView. I've setup two buttons and each one pushes another view , both UITableViewControllers.
The first buttons works just fine. The problem is: when I'm in the second TableViewController and I tap on the back button it tries to push the view again and only the second time it goes back to the Main View.
I also have an UITabBarController setup and I noticed that if I am in my first tab(the Main View with the two buttons pushing the two tableviews and precisely in the second view ) and i tap on another tab then tap back on the first - it shows me the content of my first UITableViewController and when I tap back it shows the second UITableViewController(that is supposed to be displayed) and only the second time i tap it goes to the Main View.
I don't know if it's understandable what I just said, here is also the code for the back button and the action for it:
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *back= [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *backImage = [[UIImage imageNamed:@"backb.png"]
stretchableImageWithLeftCapWidth:10 topCapHeight:10];
[back setBackgroundImage:backImage forState:UIControlStateNormal];
[back addTarget:self action:@selector(cancel:)
forControlEvents:UIControlEventTouchUpInside];
back.frame = CGRectMake(0, 0, 37, 26);
UIBarButtonItem *cancelButton = [[[UIBarButtonItem alloc]
initWithCustomView:back] autorelease];
self.navigationItem.leftBarButtonItem = cancelButton;
}
-(IBAction)cancel:(id)sender{
[self.navigationController popViewControllerAnimated:YES];
}
The back button in the first UITableViewController is setup the same and works just fine...what could be the problem?
I've just added another UITableViewController and obviously now when I'm in the third view and I try to go back to the Main View it loads the view two times and the first UITableViewController before it goes back...
A: There are chances that you have pushed the second view controller twice. While you push multiple instances of view controllers at the same time, you won't see any difference in the pushing animation. It'd look like only one controller is being pushed. This is because you push the next view controller before the previous view controller was pushed completely.
Check your code if you are pushing the second view controller twice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Bundler installs sqlite3 every time, but there's not sqlite in Gemfile Bundler keeps install sqlite3 every time, but i'm not using it in my project. I've chosen Postgres, but can not deploy it to Heroku. Bundler is the reason for that. Why it is? And what should i do?
I was trying to make separate gemset for that. I cleared and reinstalled all gems. But every time sqlite comes to my "bundle install" log:
.......
Using sqlite3 (1.3.4)
Using sqlite3-ruby (1.3.3)
Using taps (0.3.23)
Using thin (1.2.11)
Using turn (0.8.2)
Using uglifier (1.0.3)
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.
My Gemfile:
source 'http://rubygems.org'
gem 'rails', '3.1.0'
gem "jquery-rails"
gem 'sorcery'
gem 'simple_form'
gem 'cocoon'
gem 'thin'
gem 'heroku'
gem 'taps'
gem 'pg'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', " ~> 3.1.0"
gem 'coffee-rails', "~> 3.1.0"
gem 'uglifier'
end
group :development do
gem "cucumber-rails"
gem "capybara"
gem "rspec-rails", ">= 2.0.1"
end
group :test do
gem 'turn', :require => false
gem "cucumber-rails"
gem "capybara"
gem "rspec-rails", ">= 2.0.1"
gem "database_cleaner"
gem "factory_girl_rails"
end
Help pls, what's wrong?
UPDATE:
Added Gemfile.lock:
GEM
remote: http://rubygems.org/
specs:
actionmailer (3.1.0)
actionpack (= 3.1.0)
mail (~> 2.3.0)
actionpack (3.1.0)
activemodel (= 3.1.0)
activesupport (= 3.1.0)
builder (~> 3.0.0)
erubis (~> 2.7.0)
i18n (~> 0.6)
rack (~> 1.3.2)
rack-cache (~> 1.0.3)
rack-mount (~> 0.8.2)
rack-test (~> 0.6.1)
sprockets (~> 2.0.0)
activemodel (3.1.0)
activesupport (= 3.1.0)
bcrypt-ruby (~> 3.0.0)
builder (~> 3.0.0)
i18n (~> 0.6)
activerecord (3.1.0)
activemodel (= 3.1.0)
activesupport (= 3.1.0)
arel (~> 2.2.1)
tzinfo (~> 0.3.29)
activeresource (3.1.0)
activemodel (= 3.1.0)
activesupport (= 3.1.0)
activesupport (3.1.0)
multi_json (~> 1.0)
addressable (2.2.6)
ansi (1.3.0)
arel (2.2.1)
bcrypt-ruby (3.0.1)
builder (3.0.0)
capybara (1.1.1)
mime-types (>= 1.16)
nokogiri (>= 1.3.3)
rack (>= 1.0.0)
rack-test (>= 0.5.4)
selenium-webdriver (~> 2.0)
xpath (~> 0.1.4)
childprocess (0.2.2)
ffi (~> 1.0.6)
cocoon (1.0.12)
coffee-rails (3.1.1)
coffee-script (>= 2.2.0)
railties (~> 3.1.0)
coffee-script (2.2.0)
coffee-script-source
execjs
coffee-script-source (1.1.2)
cucumber (1.0.6)
builder (>= 2.1.2)
diff-lcs (>= 1.1.2)
gherkin (~> 2.4.18)
json (>= 1.4.6)
term-ansicolor (>= 1.0.6)
cucumber-rails (1.0.5)
capybara (>= 1.1.1)
cucumber (~> 1.0.6)
nokogiri (>= 1.5.0)
daemons (1.1.4)
database_cleaner (0.6.7)
diff-lcs (1.1.3)
erubis (2.7.0)
eventmachine (0.12.10)
execjs (1.2.8)
multi_json (~> 1.0)
factory_girl (2.1.2)
activesupport
factory_girl_rails (1.2.0)
factory_girl (~> 2.1.0)
railties (>= 3.0.0)
faraday (0.6.1)
addressable (~> 2.2.4)
multipart-post (~> 1.1.0)
rack (< 2, >= 1.1.0)
ffi (1.0.9)
gherkin (2.4.21)
json (>= 1.4.6)
heroku (2.8.4)
launchy (>= 0.3.2)
rest-client (~> 1.6.1)
rubyzip
term-ansicolor (~> 1.0.5)
hike (1.2.1)
i18n (0.6.0)
jquery-rails (1.0.14)
railties (~> 3.0)
thor (~> 0.14)
json (1.6.1)
json_pure (1.6.1)
launchy (2.0.5)
addressable (~> 2.2.6)
mail (2.3.0)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
mime-types (1.16)
multi_json (1.0.3)
multipart-post (1.1.3)
nokogiri (1.5.0)
oauth (0.4.5)
oauth2 (0.4.1)
faraday (~> 0.6.1)
multi_json (>= 0.0.5)
pg (0.11.0)
polyglot (0.3.2)
rack (1.3.3)
rack-cache (1.0.3)
rack (>= 0.4)
rack-mount (0.8.3)
rack (>= 1.0.0)
rack-ssl (1.3.2)
rack
rack-test (0.6.1)
rack (>= 1.0)
rails (3.1.0)
actionmailer (= 3.1.0)
actionpack (= 3.1.0)
activerecord (= 3.1.0)
activeresource (= 3.1.0)
activesupport (= 3.1.0)
bundler (~> 1.0)
railties (= 3.1.0)
railties (3.1.0)
actionpack (= 3.1.0)
activesupport (= 3.1.0)
rack-ssl (~> 1.3.2)
rake (>= 0.8.7)
rdoc (~> 3.4)
thor (~> 0.14.6)
rake (0.9.2)
rdoc (3.9.4)
rest-client (1.6.7)
mime-types (>= 1.16)
rspec (2.6.0)
rspec-core (~> 2.6.0)
rspec-expectations (~> 2.6.0)
rspec-mocks (~> 2.6.0)
rspec-core (2.6.4)
rspec-expectations (2.6.0)
diff-lcs (~> 1.1.2)
rspec-mocks (2.6.0)
rspec-rails (2.6.1)
actionpack (~> 3.0)
activesupport (~> 3.0)
railties (~> 3.0)
rspec (~> 2.6.0)
rubyzip (0.9.4)
sass (3.1.7)
sass-rails (3.1.2)
actionpack (~> 3.1.0)
railties (~> 3.1.0)
sass (>= 3.1.4)
sprockets (~> 2.0.0)
tilt (~> 1.3.2)
selenium-webdriver (2.7.0)
childprocess (>= 0.2.1)
ffi (>= 1.0.7)
json_pure
rubyzip
sequel (3.20.0)
simple_form (1.5.2)
actionpack (~> 3.0)
activemodel (~> 3.0)
sinatra (1.0)
rack (>= 1.0)
sorcery (0.6.1)
bcrypt-ruby (~> 3.0.0)
oauth (~> 0.4.4)
oauth (~> 0.4.4)
oauth2 (~> 0.4.1)
oauth2 (~> 0.4.1)
sprockets (2.0.0)
hike (~> 1.2)
rack (~> 1.0)
tilt (!= 1.3.0, ~> 1.1)
sqlite3 (1.3.4)
sqlite3-ruby (1.3.3)
sqlite3 (>= 1.3.3)
taps (0.3.23)
rack (>= 1.0.1)
rest-client (< 1.7.0, >= 1.4.0)
sequel (~> 3.20.0)
sinatra (~> 1.0.0)
sqlite3-ruby (~> 1.2)
term-ansicolor (1.0.6)
thin (1.2.11)
daemons (>= 1.0.9)
eventmachine (>= 0.12.6)
rack (>= 1.0.0)
thor (0.14.6)
tilt (1.3.3)
treetop (1.4.10)
polyglot
polyglot (>= 0.3.1)
turn (0.8.2)
ansi (>= 1.2.2)
tzinfo (0.3.29)
uglifier (1.0.3)
execjs (>= 0.3.0)
multi_json (>= 1.0.2)
xpath (0.1.4)
nokogiri (~> 1.3)
PLATFORMS
ruby
DEPENDENCIES
capybara
cocoon
coffee-rails (~> 3.1.0)
cucumber-rails
database_cleaner
factory_girl_rails
heroku
jquery-rails
pg
rails (= 3.1.0)
rspec-rails (>= 2.0.1)
sass-rails (~> 3.1.0)
simple_form
sorcery
taps
thin
turn
uglifier
A: (Even though you've figured it out, i'll put it here incase for some reason people don't read the comments)
The 'taps' gem (http://rubygems.org/gems/taps) that you've required in your Gemfile has a runtine dependancy on the 'sqlite3-ruby' gem.
You can ususally find out where strange dependencies come from by looking in your Gemfile.lock file, as you can see here...
taps (0.3.23)
rack (>= 1.0.1)
rest-client (< 1.7.0, >= 1.4.0)
sequel (~> 3.20.0)
sinatra (~> 1.0.0)
sqlite3-ruby (~> 1.2)
Each gem will be listed with its runtime dependencies along with the version that it needs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Partial template specialization - member specialization Say I have this template class:
template<typename T> class MyClass{
public:
MyClass(const T& t):_t(t){}
~MyClass(){}
void print(){ cout << _t << endl; }
private:
T _t;
};
And I want to specialize it, so similarly I define:
template<> class MyClass<double>{
public:
MyClass(const double& t):_t(t){}
~MyClass(){}
void print(){ cout << _t << endl; }
private:
double _t;
};
Now, this is ok as long as we're talking about small classes. If I have a very long class, it would be a lot smarter to specialize print() alone. I know how to do it with non-member function. Is there any way to do it with member functions?
A: One straightforward solution is, define base class template containing things which you want to specialize, and then specialize this class template instead (it would be a small class, after all):
template<typename T>
struct printable
{
protected:
void print(const T & _t) { }
};
template<>
struct printable<double>
{
protected:
void print(const double & _t) { }
};
And then derived from it:
template<typename T>
class MyClass : public printable<T>
{
typedef printable<T> base;
public:
MyClass(T t&):_t(t){}
~MyClass(){}
void print(){ base::print(_t); } //forward
private:
T _t;
};
You don't need to specialize this class template anymore; make it as huge as you want (and reasonable).
Another alternative is policy-based design in which you pass policy-class(es) as template argument(s) to your class template (called host class).
For example,
//lets define few policy classes
struct cout_print_policy
{
template<typename T>
static void print(T const & data)
{
std::cout << "printing using cout = " << data << std::endl;
}
};
struct printf_print_policy
{
static void print(int data)
{
std::printf("printing int using printf = %d\n", data);
}
static void print(double data)
{
std::printf("printing double using printf = %f\n", data);
}
};
//now define the class template (called host class) that
//accepts policy as template argument
template<typename T, typename TPrintPolicy>
class host
{
typedef TPrintPolicy print_policy;
T data;
public:
host(T const & d) : data(d) {}
void print()
{
print_policy::print(data);
}
};
Test code:
int main()
{
host<int, cout_print_policy> ic(100);
host<double, cout_print_policy> dc(100.0);
host<int, printf_print_policy> ip(100);
host<double, printf_print_policy> dp(100.0);
ic.print();
dc.print();
ip.print();
dp.print();
}
Output:
printing using cout = 100
printing using cout = 100
printing int using printf = 100
printing double using printf = 100.000000
Online demo : http://ideone.com/r4Zk4
A: In your example, you are using full specialization. In that case, you can do it like this:
template <>
void MyClass<double>::print()
{
cout << _t << endl;
}
but it doesn't work for partial specialization.
A: You can specialize your print member function specially for double:
template< typename T >
class MyClass{
public:
MyClass(T t&):_t(t){}
~MyClass(){}
void print(){}
private:
T _t;
};
template< typename T >
void MyClass< T >::print(){/* your specific implementation*/}
template<>
void MyClass< double >::print(){/* your specific implementation*/}
A: in class.h
// declaration of template class
template<typename T>
class MyClass
{
public:
MyClass(T t&):_t(t){}
~MyClass(){}
void print(); // general "declaration".
// don't use inline definition for these case
private:
T _t;
};
// specialization "declaration" of wanted member function
template<>
void MyClass<double>::print();
#include "class.inl" // implementation of template class
in class.inl
// general "definition" of wanted member function
template<typename T>
void MyClass<T>::print()
{
cout << _t << endl;
}
in class.cpp
#include "class.h"
// specialization "definition" of wanted member function
// specialization definition of anyone must be here.. not inl file..
void MyClass<double>::print()
{
cout << "double specialization " << _t << endl;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: curl can not get complete response from a url i use curl in centos 5.5 and curl like below to get the response from the url:
curl 7.21.2 (x86_64-unknown-linux-gnu) libcurl/7.21.2 OpenSSL/0.9.8b zlib/1.2.3 libidn/0.6.5
Protocols: dict file ftp ftps gopher http https imap imaps pop3 pop3s rtsp smtp smtps telnet tftp
Features: IDN IPv6 Largefile NTLM SSL libz
http://www.51buy.com/portal.html, and i can get the response but it's not complete, for example you can not find '934', but '934' is really on that html source code.
on the other hand on my windows, i used the curl version like below
curl 7.21.2 (i386-pc-win32) libcurl/7.21.2 OpenSSL/0.9.8o zlib/1.2.5 libidn/1.18 libssh2/1.2.7 librtmp/2.3
Protocols: dict file ftp ftps gopher http https imap imaps ldap pop3 pop3s rtmp rtsp scp sftp smtp smtps telnet tftp
Features: AsynchDNS IDN Largefile NTLM SSL SSPI libz
and to get the same url, it can get the complete response.
can anyone give me some clue to help me to resolve the issue?
Thank you in advance.
A: Most often when you get different responses, it is because the site tries to do different things depending on your user-agent or similar.
To counterfeit that, figuring out the exact request your browser sends and then trying to mimic that as closely as possible is often a winning approach.
In this case, since the windows version of curl seems to work, you could try to set the user-agent in the linux case to look like the windows curl version...
As you didn't include any specific protocol details, we can't guess any further about the actual contents.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create a function that returns an acronym in matlab I need to create an m-file in Matlab that contains the following function:
function acr = acronym(phrase)
This function should compute and returns the acronym of the phrase as the result of the function; that is, if someone types any phrase in Matlab, this function should return an acronym consisting of the first letter of every word in that phrase. I know that it’s a simple function, but my coding experience is very limited and any help would be appreciated; thanks in advance.
A: This is a great place to use regular expressions. The function regexp takes in a string and a regular expression and returns the starting indices for each substring that matches the regular expression. In this case, you want to match any character that starts a word. \<expr matches expr when it occurs at the start of a word (See the documentation for regexp). A period matches any character. So the regular expression to match the first character of any word is \<..
Thus,
regexp(phrase,'\<.')
will return the indices for the first letter of each word in phrase. So an acronym function could be:
function acr = acronym(phrase)
ind = regexp(phrase, '\<.');
acr = upper(phrase(ind));
end
Or even just
function acr = acronym(phrase)
acr = upper(phrase(regexp(phrase, '\<.')));
end
A: You can use textscan to read a formatted text file as well as a formatted string. Then you just have to keep the first letter of each word:
phrase='ceci est une phrase';
words=textscan(phrase,'%s','delimiter',' ');
words=words{:};
letters=cellfun(@(x) x(1),words);
acronym=upper(letters');
A: function output = acronym( input )
words_cell = textscan(input,'%s','delimiter',' ');
words = words_cell{ : };
letters = cellfun(@(x) textscan(x,'%c%*s'), words);
output = upper(letters');
end
EDIT: Just noticed a very similar answer has already been given!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Solving errors with a stacktrace I got an error that its stacktrace doesn't reveal where in my classes (& line number) the error lies.
Is there another way I can locate the code that causes this error?
I understand the error itself... but there are a couple of places in my code that could cause this and I can't reproduce it... (got the stacktrace from a user report).
Here's the stacktrace:
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@462e1370 is not valid; is your activity running?
at android.view.ViewRoot.setView(ViewRoot.java:509)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.Dialog.show(Dialog.java:241)
at android.app.AlertDialog$Builder.show(AlertDialog.java:802)
at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:566)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:144)
at android.app.ActivityThread.main(ActivityThread.java:4937)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Thank you!
A: You are probably trying to show a dialog when the user has paused or killed the app. Check all your alertDialogs and how you show these. Make sure your activity is running. For example you could use isFinishing
A: Comment is now an answer as requested:
I'm thinking that the exception is coming from a different thread. This seems to be the event thread of Android while you execute code in the worker thread that results in code being executed in the event thread. Like slayton suggested in his comment add some comments. However, also try to comment out parts of the code and see what line causes that exception.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Django seamless upgrades with CDN [I'm using AWS but I think this question is relevant to all CDNs]
I'm looking to seamless deploy my Django server to the AWS cloud.
All static content (e.g. images, javascript, etc.) go to the Amazon Cloudfront CDN.
The problem is that I'm trying to make the upgrade as "atomic" as possible, while I have very little control over the timing of CDN object invalidation.
According to TFM, the solution is to version my objects, i.e. rename them adding a version id, e.g. arrow_v123.png. Obviously if the new server points to arrow_v124.png I have complete control over the timing of the entire distribution.
I checked and from what I can tell the big boys are doing that - Facebook static content objects have a hashed name (and path).
BUT HOW DO I AUTOMAGICALLY DO THIS IN DJANGO?
I need to somehow:
*
*Generate a new version number
*Change all the names of all the objects that are static
*Change all the templates and python code to use those new names
Or somehow integrate with the development process:
*
*I edit a picture or a javascript file
*I save it and it gets a new name?!?! and all references to it are auto-corrected?!?!
I'm using Fabric for deployments, so it makes sense I need to modify my fabfile somehow.
Please help.
Tal.
A: http://www.allbuttonspressed.com/projects/django-mediagenerator provides asset versioning. It provides a function and a template tag to give you the versioned filename from the actual filename. It also has some nice extras like js/css minification and concatenation.
A: Have a look at html5boilerplate, has ant build scripts which as well as doing a lot of other things rename your static js/CSS references to a random number and changes any references in your template files to these new random numbered js/CSS. I don't think it does the same for image assets but I suppose the ant files could be changed to perform the same.
Django port of html5boilerplate is here: https://bitbucket.org/samkuehn/django-html5-boilerplate
A: Seems to me the last part (change all templates and python code to use the new names) is easy. Store the current style "version number" in your settings. Make sure this version number is passed to your templates using the template context. Then, use that when rendering the templates to select the real URL to static files.
The steps involved in publishing a new set of static files is:
*
*publish the new files to your CDN
*edit your settings file
*re-load your application settings
You can achieve the same type of effect using a similar scheme by storing the version number in the database rather than in the settings. This avoids the reload and changes are immediate, but will add a DB query at each view render.
How you integrate each of these steps into your development process is up to you. It might be possible to (conditionally) automate publishing to the CDN, editing the settings file and restarting the application. To "edit" the settings file easily, you can store the version number in a separate file and have the settings file read that on start-up.
A: I'd append a random string to the end of all the static assets you update often.
Example: style.css will become style.css?ASFDSF34343SDSFDSF
In debug mode, I ensure that the random string changes on each request, so my changes take effect right away. (this prevents browser caching)
In production, the random string is ONLY generated once on start-up and reused thereafter.
You can have it so the random string sticks around after a restart of your web server too.
This has been working very well for me, both during the development as well as in production.
Mind you that I keep my assets on S3 and have not enabled the CloudFront yet.
Here is the actual example:
http://static.outsourcefactor.com/css/main.css?ASDFASFASF434434
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: click through yes/no questions from OPML one at a time Based on a flowchart noted as OPML nodes in my xhtml, I would like to dynamically (using jquery, without refreshing the page) get questions shown one by one, depending on the yes/no answer of the previous one, until a final message in the OPML is reached. For example;
Q: Do you have a pet? A: yes
Q: Is it big? A: yes
Q: Is it a dog? A: yes
Final:Please note that dogs are not allowed at this event!
The mechanism is similar to the one proposed in this SO question. However it needs to be coded for each question and reply. I am looking for a way to code something at which you can trow any OPML at, and it will automagically creates that behavior.
[edit] As a readable fallback when javascript is switched off, and to avoid parsing external OPML, it might be better to use XOXO an outline microformat instead of OPML.
A: You could do something like this: http://jsfiddle.net/kayen/fGrT2/
HTML:
<div id="petTest">
<fieldset>
<legend>Do you have a pet?</legend>
<ul>
<li><label for=""><input type="radio" name="petstatus" value="Yes" /> Yes</label></li>
<li><label for=""><input type="radio" name="petstatus" value="No" /> No</label></li>
</ul>
</fieldset>
<fieldset>
<legend>Is it big?</legend>
<ul>
<li><label for=""><input type="radio" name="petsize" value="Yes" /> Yes</label></li>
<li><label for=""><input type="radio" name="petsize" value="No" /> No</label></li>
</ul>
</fieldset>
<fieldset>
<legend>Is it a dog?</legend>
<ul>
<li><label for=""><input type="radio" name="pettype" value="Yes" /> Yes</label></li>
<li><label for=""><input type="radio" name="pettype" value="No" /> No</label></li>
</ul>
</fieldset>
<fieldset>
<legend>Please note that dogs are not allowed at this event!</legend>
</fieldset>
</div>
JQuery:
$("#petTest fieldset")
.hide()
.eq(0).show()
.end()
.find("input[value='Yes']")
.click(function() {
$(this).parents("fieldset").next().show(300);
})
.end()
.find("input[value='No']")
.click(function() {
$(this).parents("fieldset").nextAll().hide(300, function(){
$(this).find("input").attr("checked", false);
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to iterate over an object in javascript with an unordered index I'm creating a playlist system where each song has a unique ID. When you add a song to the playlist array, its index is registered as its ID.
Normally when looping over a javascript array, you grab the length and count up through the index. Is there a way to loop through an array with unused indexes? Is that bad practice for any reason?
A: var obj = {"123": "Lalala",
"456": "dum dum"};
for(var i in obj){
//i = ID
// obj[i] = "song"
}
Use for(var i in obj) to loop through an object. See the comments above to understand the meaning of this for-statement.
You're talking about Objects, not arrays, by the way:
var array = [7, 5, 9];
An array can be simulated in this way, so that a for(var i=0; i<array_like.length; i++) can be used. Array functions (such as pop) cannot be used on them, unless you define it:
var array_like = {0:7, 1:5, 2:9, length:3};
A: You can access the object's properties one of two ways. Either using a "." such as:
var my prop = obj.property;
Or via bracket notation:
var my prop = obj["property"];
Now, that doesn't really answer your question. So, here are a few ways:
Utilize jQuery's each function:
$.each(obj, function(key, value){
//Do something with your key and value.
});
Utilize the Javascript for function:
for(var key in obj)
{
var value = obj[key];
//Do something with your key and value.
}
Hope that helps!
A: You can also do just for each to iterate over properties values only:
var obj = {"key1": "val1",
"key2": "val2"};
for each(var value in obj) {
....
}
But in this case, you are not able to access a property name.
A: Assuming your array is in the form:
array['id1'] = 'val1';
array['id2'] = 'val2';
array['id3'] = 'val3';
You can iterate over the values by using:
for (var id in array) {
document.write(id + ' – ' + array[id]);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How can I expose C functions to a custom virtual machine? I'm working on a virtual machine which I would like to be able to interface with C. Going the other way and exposing virtual machine functions to C code is fairly easy, what I can't wrap my head around is exposing C functions to a virtual machine.
I'd like to be able to dynamically register C functions with the virtual machine like so:
vm_register(printf);
Then in my virtual machine, push the arguments to the stack, and:
call printf
The problem is that without knowing how many arguments the function requires, and of what type, I'm not sure function pointers can be used.
Is there a generic function pointer type that can be used in this situation? Can someone steer me in the right direction?
A: The general answer is that you have to implement it yourself using assembly. After linking with libc, you have the address of the function you want to call, and you have to pass the parameters to the function manually (using the calling convention of whatever platform your virtual machine is running on).
Luckily there's a library, libffi, that does exactly what you want. It's pretty easy to use as well, its source includes some documentation and examples. If you're interested to see how it works, you can take a look at its code (e.g. calling a function using the unix calling convention).
Regarding the parameter types, you usually have to let the user describe them for you and blindly accept that and pass them further on to libffi (or to the hardware if you do it without libffi). Another way would be to parse the C header file for the function to call, which is less error prone - but in any case, there's really no safe way as the binary code for the function doesn't describe its interface (with printf and its variable parameter list even more so).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Concatenate where queries with or operator in a QueryBuilder QueryBuilder is defined in Microsoft.Windows.Data.DomainServices.
It allows you to create a Query on a collection of type T and apply it later.
When I need to concatenate where queries by && it is easy, for example you can do
var query = new QueryBuilder<Customer>();
if (!string.IsNullOrEmpty(this.CustomerFirstName))
query = query.Where(c => c.FirstName == this.CustomerFirstName);
if (!string.IsNullOrEmpty(this.CustomerLastName))
query = query.Where(c => c.LastName == this.CustomerLastName);
if (!string.IsNullOrEmpty(this.CustomerPhone))
query = query.Where(c => c.Phone == this.CustomerPhone);
if (!string.IsNullOrEmpty(this.CustomerMail))
query = query.Where(c => c.Mail == this.CustomerMail);
I can't find out how should I concatenate those Where queries by || (or)??
I have a query that loads all Products in a database, since products are organized by category and a user can select only a sub-set of categories (the one he is interested in)
I would like to load only products in categories that the user has specified
I know I could do it concatenating Where() by && where I exclude unselected categories
example
query.Where(c => c.CategoryName != "MyCategory");
but I don't like it.
I would like to do it in a foreach loop
private void LoadProducts()
{
var query = new QueryBuilder<Product>();
//Get Only Products in specified categories
if (!string.IsNullOrEmpty(WebContext.Current.User.SelectedCategoriesCSV))
{
foreach (string cat in WebContext.Current.User.SelectedCategoriesCSV.Split(';'))
{
????//query.Where(c => c.CategoryName == cat || );
}
}
.....
A: You need to dynamically build your where expression and then pass it once to the query.Where(). Check out the PredicateBuilder that provides Or method to accomplish that. Hope this helps.
A: You can use Dynamic LINQ operator that are available at this link:
http://msdn.microsoft.com/en-us/bb330936.aspx
(download the c# example and get the code in the \LinqSamples\DynamicQuery directory)
A: You can use PredicateBuilder class developed by Monty’s Gush.
Try this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: CSS positioning for jquery plugin element The layout in question is here: http://www.davedaranjo.com/media.html
This is probably an issue in standard positioning with css, but I've tried every positioning combination I can think of to achieve this:
http://i.imgur.com/y1qRU.jpg
Every time I try to move the player anywhere on the page, it positions itself at the bottom, even below the footer image. I've even tried putting the content in a table with the links and video in the left td and the player in the right, but the player won't even sit in the table. I've also tried a number of positioning tags in the css file and at best, it will move if I give it a fixed position, but because the rest of the layout isn't fixed (and isn't on the rest of the site), that's not a viable solution.
I realize this is probably something fundamental that I'm missing here, but any suggestions would be extremely helpful. There's a lot of positioning in the css from the plugins download files and I can't seem to decipher them all.
Thank you!
A: you have to put your javascript at the place you want it in the page.
I think you can position it like this.
<div id="left">
<img src="media/MediaTextBanner.jpg" alt="" width="596" height="58">
<table>
<tr>
<td>
<img src="media/Transcriptions.jpg" width="547" height="39">
<br><a href="media/mmbtab.html">TABLATURE: Me & My Bass Guitar: Victor Wooten</a>
<br><a href="media/Circles - Gwizdala - Bass Parts.pdf"> Circles: Janek Gwizdala - Bass Notes</a>
<br><a href="media/That Stern Look - Gwizdala - Bass Parts.pdf">That Stern Look: Janek Gwizdala - Bass Notes</a>
<br><a href="media/flyback.html">Fly Back [2009 Redux]: Dave D'aranjo / The Ocean Band</a>
<p>
<img src="media/VideoBanner.jpg" width="547" height="39">
<p>
<iframe src="http://player.vimeo.com/video/21755863?title=0&byline=0&portrait=0&autoplay=0" width="398" height="224" frameborder="0"></iframe>
<br><a href="http://vimeo.com/darangatang" target="_blank"><img src="contact/thumbs/Vimeo.jpg" width="90" height="81"></a>
<a href="http://www.youtube.com/profile?user=DaveDaranjo" target="_blank"><img src="contact/thumbs/YouTube.jpg" width="90" height="81"></a>
<br><img src="media/OceanBanner.jpg" width="547" height="39">
<br><a href="http://www.myspace.com/oceanband" target="_blank">The Ocean Band - MySpace</a>
<br><a href="http://www.youtube.com/profile?user=theoceanbandsg" target="_blank">The Ocean Band - YouTube</a>
<br><a href="http://www.cdbaby.com/Artist/TheOceanBand" target="_blank">The Ocean Band - CDBaby.com </a>
</p>
</td>
<td position: relative; vertical-align: top;><center>
<div id="title" align="right"></div></center>
</td>
</tr>
</table>
<center>
<img src="/ambigram.jpg" alt="" width="113" height="61"><br>
<font color="CC0000"> © 2011 DaveDaranjo.com<br>
All Rights Reserved.</font></p>
</center>
</div>
<div id="right">
<script type="text/javascript">
$(document).ready(function(){
var description = 'Solo bass work, videos, and songs from bands. ';
$('body').ttwMusicPlayer(myPlaylist, {
autoPlay:false,
tracksToShow:12,
description:description,
jPlayer:{
swfPath:'../js' //You need to override the default swf path any time the directory structure changes
}
});
});
</script>
</div>
This puts the text and images you want to the left in a box and the player in another box.
You now have to position the boxes to floating boxes so they can be next to eachother in css:
#left {
float: left;
}
#right {
float: right;
}
That should do it!
A: I checked your source code and you still use the align HTML attribute. That attribute is deprecated. It does not work in HTML 4.01 or XHTML 1.0 and it won't work in HTML 5 either.
Instead use CSS rules to do your alignment. Use text-align, padding, margin, float, clear and positioning rules to get your HTML elements to appear where you want them to on the page.
Source: http://www.w3schools.com/tags/att_div_align.asp
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wordpress 4 Column menu on footer Does anyone know of any plugins or a simple way to have a 4 column menu on the wordpress footer populated with Categories / and or Pages please?
Thanks
A: If you have custom menus activated in your functions file in your theme you can add a custom menu to your footer quite easily, like so:
<ul id="nav" class="bottom">
<?php wp_nav_menu(array('menu' => 'Nav Bottom')); ?>
</ul>
If you don't have custom menus already activated, make sure to place this bit of code in your functions.php file:
//Wordpress custom menu support
if (function_exists('add_theme_support')) {
add_theme_support('menus');
}
A: Add this to your functions.php:
//register custom menu
function register_my_menus() {
register_nav_menus(
array( 'g-nav' => __( 'Global Navigation' ), 'f-nav' => __( 'Footer Navigation'))
);
}
As you can see in the above code, you can:
*
*Register as many custom menus as you like
*Name the custom menu as you like (the name that will appear on the left of the Custom Menu section will be the one that you define within ('') in the code above.
Following on from there, add the following snippet to the area you wish for the custom menu to appear:
<ul id="menu">
<li><?php wp_nav_menu(array('menu' => 'g-nav')); ?><li>
</ul>
Next go to your CSS and style it according to how you'd like the columns to come out. It could be something like this:
#menu ul{
list-style-type:none;
}
#menu li{
display:inline;
padding:5px;
}
Once you're done, you just need to go to your Dashboard and look for the Custom Menu module and select it. You should be able to figure the rest yourself as it's pretty straightforward from there on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Customizing Model Validation Feedback I want to change the way a validation message appears to the user in my nopCommerce web application. Currently, it appears as so:
I want to change that, so that if and when the login credentials are incorrect, the input fields get a red border, and the text [ wrong credentials ] to be set as Placeholder for the input fields.
I tried disabling the code:
@Html.ValidationSummary(true, T("Account.Login.Unsuccessful").Text)
But that just took away all validation feedback. How can I achieve what I mentioned above?
A: Here is the complete Updated code
CSS
.validation-error
{
border: 1px solid #ff0000;
background-color: #ffeeee;
}
Jquery code to check the login using $.ajax
$(function () {
$('#btnLogin').click(function (e) {
var email = $('#Email').val(); // this your username textbox value
var password = $('#Password').val(); // this is your password textbox value
var postdata =
{
"Email": email,
"Password": password
};
$.ajax({
tyep: 'POST',
url: '@Url.Action("LogIN","Account")', // your controller action will be called to check for the login details
data: postdata, // this data you have to post to controller for validation
success: function(value) { // if ajax call complete, controller action will return boll value true here
if(valeu) {
$('#divLoginError').addClass("validation-error"); // this will add class class to your textboxes with red broder
$('divLoginError').html('Please check your username / password');
}
},
error: function(errorData) // if any error while calling Ajax. this method is gonna call
{
$('#divLoginError').show().html(errorData);
}
});
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: c# generates JS to fill webform: how to verify it works? as continuation to:
WebBrowser Control in a new thread
how to fill an external web form with c# application?
I want to fill a website (i.e. gmail) web-form.
I thought to avoid the WebBrowser control overhead. I used JS.
but the following code doesn't work (as the Navigation_completed handler is called too many times). How can I verify the following code works? Is there any faster way to do so ?
static void Main(string[] args)
{
runBrowserThread(new Uri("https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F%3Fui%3Dhtml%26zy%3Dl&bsv=llya694le36z&ss=1&scc=1<mpl=default<mplcache=2&hl=iw&from=logout"));
}
private static void runBrowserThread(Uri url)
{
var th = new Thread(() =>
{
var br = new WebBrowser();
br.DocumentCompleted += browser_DocumentCompleted;
br.Navigate(url);
br.Navigate("javascript: void(document.getElementsByName('Email')[0].value = 'Name';document.getElementsByName('Passwd')[0].value = 'Pass'; document.getElementsByName('signIn')[0].click();)");
Application.Run();
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
}
static void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var br = sender as WebBrowser;
if (br.Url == e.Url)
{
Console.WriteLine("Natigated to {0}", e.Url);
// Application.ExitThread(); // Stops the thread
}
}
TIA
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Raven DB Replication Setup Issue Can any one help me in setting up Raven DB Replication? Tried a lot of
ways a lot of time but no success.
Here is the story:
1) I downloaded the raven bundle. Make a copy of it. Run
Raven.Server.Exe from both of the folders. Both instances run
successfully on individual port. Then I created a document with name
as "Raven/Replication/Destinations" and document as
{
"Destinations": [{"Url":"http://vishal-pc:8081"}],
"Id": "Raven/Replication/Destinations"
}
But it's not working. Please some one put some light no How can I
setup replication.
One more thing I want to mention here is, I was able to run the
replication by running "start raven.ps1" from samples/
Raven.Sample.Replication from bundle.Both instances are already has
the Raven/Replication/Destinations" document like below (no url in
destination node):
{
"Destinations": [],
"Id": "Raven/Replication/Destinations"
}
Then I updated one instance with url of another instance. After
updating document was like below:
{
"Destinations": ["Url":"http://vishal-pc:8081"],
"Id": "Raven/Replication/Destinations"
}
and replication works fantastically.
I am not able to figure out what is the difference here. Why It's not
able to replication When I run two instances separately and why it is
working fine by running "start raven.ps1".
Please please please some one put some light here.
Note : I am using web interface to make changes in document.
Thanks
Vishal
A: Look in the folder of the Raven.Server.exe file you are executing. Make sure you have a subdirectory called Plugins and that it contains the replication bundle DLL.
This blog post walks you through that process pretty well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Last element in xml not getting picked up I have a python 3 script below that is supposed to download an xml file and split it into smaller files with only 500 items each. I am having two problems:
*
*the last item in the original xml is not present in the split files
*if the original xml was 1000 items long it will create a 3rd empty xml file.
Can anyone tell me where there could be such an error in my code to cause these symptoms?
import urllib.request as urllib2
from lxml import etree
def _yield_str_from_net(url, car_tag):
xml_file = urllib2.urlopen(url)
for _, element in etree.iterparse(xml_file, tag=car_tag):
yield etree.tostring(element, pretty_print=True).decode('utf-8')
element.clear()
def split_xml(url, car_tag, save_as):
output_file_num = 1
net_file_iter = _yield_str_from_net(url, car_tag)
while True:
file_name = "%s%s.xml" % (save_as, output_file_num)
print("Making %s" % file_name)
with open(file_name, mode='w', encoding='utf-8') as the_file:
for elem_count in range(500): # want only 500 items
try:
elem = next(net_file_iter)
except StopIteration:
return
the_file.write(elem)
print("processing element #%s" % elem_count)
output_file_num += 1
if __name__ == '__main__':
split_xml("http://www.my_xml_url.com/",
'my_tag',
'my_file')
A: The second one is no error but by design. After reading 1000 elements the iterator does not yet know that there is no further item and thus continues with the while True loop.
It would be great if iterators would have a hasNext then you could replace it by while hasNext in order to overcome this issue. Unfortunately there is no such thing in python.
For the first question: currently I can't see anything in your code explaining this issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQGrid clicking ENTER on EDIT popup I have a form that i use in jqgrid in add/edit popup
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { id = "formId" }))
{
//...
}
When i click a row that form opens. If i press the textbox and click ENTER this form submits. And it submits as a regular post request, not by using jqgrid. But if i click on the Save button it works as required.
buttons: {
'Save': function () {
if ($('#formId').valid()) {
$.ajax({
type: 'POST',
url: '@Url.Action( "Action", "Controller" )',
data: $('#formId').serialize(),
success: function (json) {
$("#grid").trigger("reloadGrid");
},
error: function (e) {
alert("Unable to save." + e);
},
dataType: "application/JSON"
});
$("#divForm").dialog('close');
}
},
But i want that when i click ENTER that will be as the save button click.
A: Try subscribing for the submit event of the form:
<div id="formContainer">
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { id = "formId" }))
{
...
}
</div>
and then:
$('#formContainer').delegate('#formId', 'submit', function (evt) {
evt.preventDefault();
if ($(this).valid()) {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function (json) {
$('#grid').trigger("reloadGrid");
},
error: function (e) {
alert("Unable to save." + e);
},
});
}
});
and now in the Save button click force the form submission:
'Save': function () {
$('#formId').submit();
}
but probably it would be better to use the form's submit button to submit a form.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Custom control not being rendered The idea behind the control below is to be able to show a Label inside of a TextBox when there isn't any text. To do this, I just took a working control that is similar, a SearchTextBox, but has too much going on for what I need here.
I suspect the control template in the style below but I don't see any thing obviously wrong with it. I could easily be missing something that is obvious to someone with more experience though.
How do I fix or trouble shoot this?
Cheers,
Berryl
Code
/// <summary>Light weight version of a <see cref="SearchTextBox"/></summary>
public class LabelTextBox : TextBox
{
#region Dependency Properties
#region Label Text
/// <summary>Sets the 'watermark' text that acts as a label, identifying what this will search for.</summary>
public static readonly DependencyProperty LabelTextProperty =
DependencyProperty.Register("LabelText",
typeof (string), typeof (LabelTextBox), new PropertyMetadata("Search"));
public string LabelText
{
get { return (string) GetValue(LabelTextProperty); }
set { SetValue(LabelTextProperty, value); }
}
/// <summary>Brush for the label text.</summary>
public static readonly DependencyProperty LabelTextColorProperty =
DependencyProperty.Register("LabelTextColor", typeof (Brush), typeof (LabelTextBox));
public Brush LabelTextColor
{
get { return (Brush)GetValue(LabelTextColorProperty); }
set { SetValue(LabelTextColorProperty, value); }
}
#endregion
#region Has Text
private static readonly DependencyPropertyKey HasTextPropertyKey =
DependencyProperty.RegisterReadOnly("HasText",
typeof (bool), typeof (LabelTextBox), new PropertyMetadata());
/// <summary>True if the user has typed in text.</summary>
public static readonly DependencyProperty HasTextProperty = HasTextPropertyKey.DependencyProperty;
public bool HasText
{
get { return (bool)GetValue(HasTextProperty); }
private set { SetValue(HasTextPropertyKey, value); }
}
#endregion
#endregion
#region Construction
static LabelTextBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof (LabelTextBox), new FrameworkPropertyMetadata(typeof (LabelTextBox)));
}
#endregion
#region Event Handlers
protected override void OnTextChanged(TextChangedEventArgs e)
{
base.OnTextChanged(e);
HasText = Text.Length != 0;
}
#endregion
}
Style
<Style x:Key="{x:Type cc:LabelTextBox}" TargetType="{x:Type cc:LabelTextBox}">
<Setter Property="Background" Value="{StaticResource SearchTextBox_Background}" />
<Setter Property="BorderBrush" Value="{StaticResource SearchTextBox_Border}" />
<Setter Property="Foreground" Value="{StaticResource SearchTextBox_Foreground}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="LabelText" Value="Search" />
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="LabelTextColor" Value="{StaticResource SearchTextBox_LabelTextColor}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type cc:LabelTextBox}">
<Border x:Name="Border" BorderBrush="{TemplateBinding BorderBrush}" Padding="2"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
>
<Grid x:Name="LayoutGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ActualHeight}" />
</Grid.ColumnDefinitions>
<ScrollViewer x:Name="PART_ContentHost" Grid.Column="0" />
<Label x:Name="LabelText" Grid.Column="0"
Foreground="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=LabelTextColor}"
Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=LabelText}"
Padding="2,0,0,0" FontStyle="Italic"
/>
</Grid>
</Border>
<ControlTemplate.Triggers>
<!--input triggers (mouse over && keyboard focused-->
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="BorderBrush" Value="{StaticResource SearchTextBox_BorderMouseOver}" />
</Trigger>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="BorderBrush" Value="{StaticResource SearchTextBox_BorderMouseOver}" />
</Trigger>
<!--Once the user has typed in search text-->
<Trigger Property="HasText" Value="True">
<!--Hide the label text-->
<Setter Property="Visibility" TargetName="LabelText" Value="Hidden" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<!--
Error display
-->
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel LastChildFill="True">
<TextBlock DockPanel.Dock="Right" Text=" *"
Foreground="Red"
FontWeight="Bold" FontSize="16"
ToolTip="{Binding ElementName=placeholder, Path=AdornedElement.(Validation.Errors).CurrentItem.ErrorContent}"/>
<Border BorderBrush="Red" BorderThickness="1">
<AdornedElementPlaceholder Name="placeholder"></AdornedElementPlaceholder>
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="Background" Value="LightYellow"/>
</Trigger>
</Style.Triggers>
</Style>
A: This seems to be working. All I did was to copy your code in a class called LabelTextBox and your Style in a Generic.xaml resource dictionary in Themes folder placed at project root (I changed the brush colors to LightBlue, LightGray, Blue etc.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: OpenGL and multiple GPUs - General possibility I was wondering, is it possible to run a multi-window OpenGL application on more than one GPU simultaneously? To be more specific, let's say I've created an application with two windows each sharing it's GL context between each other. Now if I'd move one of those windows from display 1 (running on GPU 1) to display 2 (running on GPU 2), would this actually work? Would sharing contexts alone do the trick?
My first guess would be no. And if this is really not that simple, is there a way to accomplish this? I could also imagine that it depends on whether the two GPUs are controlled by the same driver or not (or even worse, let the machine have an ATI as well as an nVidia card, both supporting different GL versions).
I would appreciate any insights on this topic, purely informational since I can't find anything after quick googling. Does anyone know the possibilities?
EDIT: By the way, unfortunately I don't have a machine with multiple GPUs available at the moment, so I would test around a little bit.
A: Short Answer: yes.
Long Answer:
Windows/Mac OS X: The windows are always updated by one GPU, and possibly the pixels are copied to another GPU.
Linux: If Xinerama is off, you can't move the window between screens (GPUs). If Xinerama is on, iirc at least the nVidia drivers send GL commands to both GPUs simultaneously so you can move them.
There are ways to control GPU selection and GPU-GPU copies programmatically. More information here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Solr apply filters on stored data Is it possible to apply filters to stored data like we can apply filter when indexing. For example I use KeepWordFilter on a filed during indexing. But I don't want filtered data to be even stored.
<fieldType name="text" class="solr.TextField"
positionIncrementGap="100">
<analyzer type="index">
<tokenizer class="solr.WhitespaceTokenizerFactory" />
<!--
in this example, we will only use synonyms at query time <filter
class="solr.SynonymFilterFactory" synonyms="index_synonyms.txt"
ignoreCase="true" expand="false"/>
-->
<filter class="solr.StopFilterFactory" ignoreCase="true"
words="stopwords.txt" />
....
Is there an analyser type stored? If not what are the alternatives?
A: There is no analyzer for stored. The values are stored as is without any modifications.
You would need to add the handling before the data is fed to Solr, probably at the client side.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: mysql get real row number i have this table
mysql> select name from test;
+---------+
| name |
+---------+
| foo |
| bar |
| foobar |
| anton |
| budi |
| anton S |
+---------+
6 rows in set (0.00 sec)
how to know if first 'anton' is record number 4?
is there any faster query than this...
select rank from (select @rownum:=@rownum+1 rank,p.name from test p, (SELECT @rownum:=0) r) a, (select * from test where name like 'anton%' limit 1) b where b.NAME = a.name
A: No.
There is no such thing as a "row number" in a table; only in an ordering imbued by ORDER BY (or possibly GROUP BY).
Records in tables have no inherent ordering, even though without an ORDER BY clause you may often happen to see them presented in insertion order for implementation reasons.
If you want to make use of insertion order, add an auto-incrementing ID column and use that.
A: The only "fast" way to have a "row number" is to add a "row counter" column :)
The problem there is that you have to keep your records up to date when you delete some of them. If there is no DELETE action (or they are very limited) , a column would be an acceptable choice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: z-index problem with helper clone This is my code (please see http://jsfiddle.net/VCfSc/1/):
$('.first').draggable({
cancel: null,
helper: 'clone'
});
$('.second').droppable({
over: function(event, ui) {
$(this).css('z-index', 1);
ui.helper.css('z-index', 0);
}
});
I am trying to have the helper clone go under the droppable element when it is dragged over it. What am I doing wrong?
A: When you drag the .first element, the generated draggable element is positioned absolutely and added after the .second element. An absolutely positioned element gets a higher precedence. To fix this, use ui.helper.css('z-index', "-1"); instead of ui.helper.css('z-index', 0);.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: If you have equals/hashcode based on int, what's the optimal way to match a "full" object from another collection? Say you had this DTO class:
public class MyObj{
private int id;
private String displayName;
private String backendData;
public boolean equals(Object obj){
return id.equals(obj);
}
private int hashCode(){
return id.hashCode();
}
}
Lets say a user got to pick several instances of MyObj from a list that only showed the displayName and the id# is associated in the background. To save bandwidth, you don't send backendData. When they submit their selection back to you, the client just sends you the id#.
Now, you've maintained the list of original options server side in a Collection<MyObj>. The naive approach to geting the "full" object back from the collection would be to iterate through the Collection and call ".equals()" on every object. This scales in O(n) though :(
It seems like with constant time operations collections like HashSet, I should be able to retrieve an object in constant time, if I know it's identity. But HashSet only has a "contains()" method and doesn't return the object it found.
Any advice? As always, thanks a bunch stackOverFlow!
A: I assume id is unique across the collection?
You are almost there use a Map<Integer, MyObj> then map.get(id) is asymptotically constant time.
A: You're object doesn't work (because you can't call methods on primitive data types). Change your id into an Integer, and use it in a hashed collection.
Map<Integer, T> objectMap = ...;
Integer id = someidfromfrontend;
T anObj = objectMap.get(id);
A: hashCode is intended to just get a quick number for an object. equals should do a full comparison of all the fields that you want to verify for object equality.
public class MyObj
{
private final Integer id;
private String displayName;
private String backendData;
public boolean equals(Object obj)
{
final MyObj other;
if(obj == null || obj.getClass() != MyObj.class)
{
return (false);
}
other = (MyObj)obj;
if(!(displayName.equals(other.displayName))
{
return (false);
}
if(!(backendData.equals(other.backendData))
{
return (false);
}
return (true);
}
private int hashCode()
{
return id.hashCode();
}
}
This assumes none of the fields can be null, it is a bit more complex in the if statements if they can be null.
A: Your question presents multiple issues IMHO: first off don't use the db id as a hash key, you could get in trouble if that thing is autogenerated. Second hashset/map use hashcode and equals methods to retrieve objects (when u use the getmethod). First the hashcode is used to quickly find the bucket where your object might be. Then if there were collisions in your hash collection and there s multiple objects in the in that bucket then equals will be used to retrive the object. So when u use get with an instance of your class here only the fields that are used in hashcode and equals need to have the correct value in order to retrieve your object. In this case if ur object has the right id (but wrong other field) it could be used to retrieve its counterpart with the otherfield populated. That or u can use a map.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Reversed breadcrumb issue My navigation table looks like this.
It based on a parent<->child scheme.
I'm using following code to generate breadcrumb.
function makeBreadcrumb($current, $lang, $db){
$q = $db->query("SELECT id, parent, $lang AS name FROM nav WHERE id = '$current'");
$row=$q->fetch_object();
echo "<li>";
echo '<a href="?id=' . $row->id . '">' . $row->name . '</a>';
echo "</li>\n\n";
if($row->parent) makeBreadcrumb($row->parent, $lang, $db);
}
But getting reversed breadcrumb: it shows child>parent instead of parent>child
.How to fix that?
A: The solution is very easy...you can simply put the recursive call before the echo statment, like this:
function makeBreadcrumb($current, $lang, $db){
$q = $db->query("SELECT id, parent, $lang AS name FROM nav WHERE id = '$current'");
$row=$q->fetch_object();
if($row->parent) makeBreadcrumb($row->parent, $lang, $db);
echo "<li>";
echo '<a href="?id=' . $row->id . '">' . $row->name . '</a>';
echo "</li>\n\n";
}
But I raccomend you not to do a query for each node in the tree. It could be very resource-expenshive.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: .NET exception not caught I have a function that looks like this:
try
{
_dbManager.InsertSearch(some data);
}
catch (Exception ex)
{
//do logging
}
_dbManager uses LINQ to insert data to a SQL database. Yesterday, the machine that hosts the database ran out of hard disk space and my program crashed. I got a crash dump which shows that there was a SqlClient.SqlException raised with an exception message reading something like "Database transaction log is full...".
My question is: Why didn't the exception get caught in the catch block above? The weird thing is, when I tried to reproduce the issue, I could get the same exception, but it was caught by the catch block. What could be the issue?
Second, related question: Imagine if we use a third party library and we don't want any exception thrown. We can use try-catch block, but this only works on calling thread. What if the third party starts new thread and an exception is thrown there? Is there a way to handle this? I know I can register our UnhandledExceptionHandler, but that seems to be a different from what I wanted.
A:
My question is: Why didn't the exception get caught in the catch block above?
As David Stratton suggests, the system might have been out of disk space and not able to write to log file. There is also a chance that the process was terminated due to Corrupted State Exception that will not be delivered to your catch-all block in .NET 4. The exception that terminated process might have also been thrown from the thread that did not have catch-all.
Second, related question: Imagine if we use a third party library and
we don't want any exception thrown.
I think that you will have to stop right there and rethink it. What you saying is that you are absolutely 100% sure that nothing ever can go wrong in the thirdparty library. There are certain exceptions (like OutOfMemoryException) that you should not be catching because your code simply does not know how to recover from them. The rule of thumb with exception handling is that you should only catch the exceptions that you fully understand and know how to recover from. Please take a look at this answer and the links in it.
What if the third party starts new thread and an exception is thrown
there? Is there a way to handle this?
The best way to handle this is to rely on default CLR policy that will terminate your application. The only reasonable thing you can do is try to log it by subscribing to AppDomain.UnhandledException.
A: Is it possible that there is another try/catch block inside that InsertSearch method, which has conditional throw statement.
The implementer of the 'DBManager' class, chose not to throw in case there is not enough space to write on the disk. Just a thought.
A: If you use Code contracts runtime checking I advice you to check compiled version of your DLL.
Read this for details Why .net exception is not caught?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: ListFragment and menu options I have added an options menu to a ListFragment, and I need to show a new ListFragment when users click on it. Is there something wrong with this? I am a bit confused on the correct way to start fragment..
A: Use a Transaction with the FragmentManager.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java Jease CMS, Index page setup I have converted my static website into Jease, through localhost:8080/cms, and I can access my website using the URL localhost:8080/index.html and from there I can browse around my entire website. What I am not sure about, how can I configure Jease to directly go to index.html page as soon as I type localhost:8080? Because once I make it globally available I want to make sure the index.html page is accessed through mywebsite.com URL.
Any hints would be appreciated.
Thanks
A: I am using JeaseCMS 2.8 and the default page already is index.html according to web.xml file.
But this welcome file isn't necessary.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it better to use linq2sql to generate classes for stored procedures, or to call the stored procedures directly? I see tons of questions on LINQ to SQL vs Stored Procs. I'm more curious about the benefits of using them in tandem as relates to object mapping.
I have my business objects defined, and I have stored procedures for all of my CRUD transactions.
Is it better to plop all the stored procs into a DBML file and call them from there, and then map the results to my business objects, or is it better to just use a DataReader and map it from there?
It's annoying to me because I want my objects as I define them, rather than use MyStoredProcResult objects as linq2sql generates, so I feel I'm doing the same field by field mapping as I would with a data reader.
Performance isn't necessarily key here (unless it's ridiculously slow). I'm looking to create a standard way for all our developers to load data from a database into an object in the simplest fashion with the least amount of code.
A: Not direct answer to your question, but if you want your objects as result of query, you probably have to consider code first schemas. Linq2SQL does not support this, but Entity Framework and NHibernate does.
Direct answer is that DataReader will obviously has less overhead, but at the same time it will have much more magic strings. Overhead is bad in terms of perfomance(in your case not that big). Magic strings are bad in terms maintaining code. So definetly this will be your personal choise.
A: Mapping to LINQ2SQL has a serious advantage in being type-safe - you don't really have to worry about parsing the results or adding command parameters. It does it all for you.
On the other hand with calling stored procedures directly with SQLcommand and DataReader proves to have better performance (especially when reading/changing a lot of data).
Regardless of which you choose it is better to build a separate Data Access Layer as it allows more flexibility. The logic of accessing/changing database should not be built into your business objects cos if you are forced to change means of storing you data it updating you software will be painful.
A: LINQ2SQL can provide your objects populated with the results of the query. You will have to build child objects in such a way as to support either a List(Of T) or List depending on your language choice.
Suppose you have a table with an ID, a Company Name, and a Phone Number for fields. Querying that table would be straight-forward in either LINQ or a stored procedure. The advantage that LINQ brings is the ability to map the results to either anonymous types or your own classes. So a query of:
var doSomething = from sList in myTableRef select sList;
would return an anonymous type. However, if you also have a class like this:
public class Company
{
public integer ID;
public string Company;
public string PhoneNumber;
}
changing your query to this will populate Company objects as it moves through the data:
List<Company> companies = (from sList in myTableRef select new Company
{ .ID = sList.id,
.Company = sList.company,
.PhoneNumber = sList.phonenumber }).ToList();
My C# syntax may not be 100% correct as I mainly code in VB, but it will be close enough to get you there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: What does /;/ and /^ +/ denote? I recently came across the statement :
var cookies = document.cookie.split(/;/);
and
var pair = allCookies[i].split("=", 2);
if (pair[0].replace(/^ +/, "") == "lastvisit")
In the first statement what does /;/ in the argument of split denote ?
In the second statement what does /^ +/ in the argument of replace denote ?
A: These are Regular Expressions.
Javascript supports them natively.
In this particular example:
*
*.split(/;/) uses ; as the split character;
*.replace(/^ +/, "") removes ("") any (+) leading (^) whitespace ().
In both examples, / surround or delimit the regular expression (or "regex"), informing Javascript that you're providing a regex.
Follow the links provided above for more information; regexes are broad in scope and worth learning.
A: Slashes delimit a regular expression, just like quotes delimit a string.
/;/ matches a semi-colon. Specifically:
var cookies = document.cookie.split(/;/);
Means we split the document.cookie string into an array, splitting it where there are semicolons. So it would take something like "a;b;c" and turn it into ["a", "b", "c"].
pair[0].replace(/^ +/, "")
Just strips all leading whitespace. It turns
" lastvisit"
into
"lastvisit"
The caret ^ means "beginning of line", it's followed by space, and the + means to repeat the space one or more times, as many as possible.
A: The // syntax denotes a regular expression (also known as a 'regex').
Regex is a syntax for searching and replacing strings.
The first example you gave is /;/. This is a very simply regex which just searches the string for semi-colons, and then splits it into an array based on the result. Since this is not using any special regex functionality, it could just as easily have been expressed as a simple string, ie split(";") (as has been done with the equal sign in your other example), without making any difference to the result.
The second example is /^ +/. This is more complex and requires a bit of knowledge of how regex works. In short, what it is doing is searching for leading spaces on a string, and removing them.
To learn more about regex, I recommend this site as a good starting point: http://www.regular-expressions.info/
Hope that helps.
A: I think that /^ +/ means: one or more no-" " characters
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: working with IQueryable; not working I'm using linq-to-EF and I have this:
public IQeuryable<base01> GetData()
{
var u = this.ObjectContext.base01;
IQueryable<base01> u2 = u.OrderBy(o => o.article)
.Select(l => new { Id = l.Id, article = l.article, lot = l.lot}) as IQueryable<base01>;
return u2;
}
Basically, u contains the result of a query and I'm looking to sort and rearrange the columns. When I replace return u2 with return u I get what the result set filled but whe I go for return u2 I get a null.
What's the problem that I'm not seeing?
Thanks.
A: as IQueryable<base01>
The problem is as - you are projecting to an anonymous type in your query not to base01 - so as will return null. Instead create new instances of base01 in your projection and remove the as operator:
IQueryable<base01> u2 = u.OrderBy(o => o.article)
.Select(l => new base01()
{ Id = l.Id, article = l.article, lot = l.lot });
Edit:
If u is already an IQueryable<base01> and base01 is one of your entities you do not need the Select() projection at all since you already have the type you want:
IQueryable<base01> u2 = u.OrderBy(o => o.article);
return u2;
A: You cannot cast this way, use code below.
IQueryable<base01> u2 = u.OrderBy(o => o.article)
.Select(l => new base01 { Id = l.Id, article = l.article, lot = l.lot});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Running a macro till the end of text file in Emacs I have a text file with some sample content as shown here:
Sno = 1p
Sno = 2p
Sno = 3p
What i want is to remove the p from each of the columns.
With this intention i write a macro:
M-x //go to buffer
C-x (//start the macro
C-s = // search for equalto sign
RET C-f C-f // reach to te alphabet 'p'
DEL // Delete
C-n C-x )//go to new line and Close the macro definition
C-x e
Pressing e twice will remove p, but in case i want to do the same stuff till the end of file, how can i do it i can't keep pressing e if i have 20000 such lines. What should be done??
Please donot suggest regex, as this is a sample example, not the actual case.
Please donot suggest any elisp, i am comfortable with remembering shortcutf for emacs.
A: M-0 C-x e to repeat last macro until an error happens (after the final line, either C-s = or C-n will be an error).
You may hear an annoying beep.
A: I usually give a name to the macro after defining it with M-x name-last-kbd-macro, so I can call it with M-x conveniently. And then I call it with a numeric prefix. E.g.
M-1000 M-x macroname
The files I work on usually don't have 1000 places where the macro can act, so 1000 is large enough and it will stop automatically at the end of the file. You can use, say, 1000000 as a prefix if you have larger files, and if it's still not enough then you can call it again with 1000000 as prefix.
A: You can use the "apply-macro-to-region-lines" function to apply the last defined keyboard macro to all lines in a region. So, the steps you follow are:
*
*Define your keyboard macro (which you had already done but I've added another C-f to the 3rd line):
C-x (
C-s =
RET C-f C-f C-f
DEL
C-n C-x )
*Select the whole buffer with the "mark-whole-buffer" command (by default, it's bound to C-x h). Alternatively, if you just want to change a certain number of lines, just select the lines you want changed.
*Run the "apply-macro-to-region-lines" function (by default, it's bound to C-x C-k r).
All the p's will be removed.
A: you may try: M-20000 C-x e so as to do the stuff for 20000 times, after you define the macro.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "43"
} |
Q: Strategies for simplifying math expressions I have a well-formed tree that represents a mathematical expression. For example, given the string: "1+2-3*4/5", this gets parsed into:
subtract(add(1,2),divide(multiply(3,4),5))
Which is expressed as this tree:
What I'd like to be able to do is take this tree and reduce it as much as possible. In the case above, this is pretty simple, because all of the numbers are constants. However, things start to get trickier once I allow for unknowns (denoted with a $ followed by an identifier):
"3*$a/$a" becomes divide(multiply(3,$a), $a)
This should simplify to 3, since the $a terms should cancel each other out. The question is, "how do I go about recognizing this in a generic manner?" How do I recognize that min(3, sin($x)) is always going to be sin($x)? How do I recognize that sqrt(pow($a, 2)) is abs($a)? How do I recognize that nthroot(pow(42, $a), $a) (the ath root of 42 to the ath power) is 42?
I realize this question is pretty broad, but I've been beating my head against this for a while and haven't come up with anything satisfactory enough.
A: You probably want to implement a term rewriting system. Regarding the underlying math, have a look at WikiPedia.
Structure of a term rewrite module
Since I implemented a solution recently...
*
*First, prepare a class CExpression, which models the structure of your expression.
*Implement CRule, which contains a pattern and a replacement. Use special symbols as pattern variables, which need to get bound during pattern matching and replaced in the replacement expression.
*Then, implement a class CRule. It's main method applyRule(CExpression, CRule) tries to match the rule against any applicable subexpression of expression. In case it matches, return the result.
*Finaly, implement a class CRuleSet, which is simply a set of CRule objects. The main method reduce(CExpression) applies the set of rules as long as no more rules can be applied and then returns the reduced expression.
*Additionally, you need a class CBindingEnvironment, which maps already matched symbols to the matched values.
Try to rewrite expression to a normal form
Don't forget, that this approach works to a certain point, but is likely to be non complete. This is due to the fact, that all of the following rules perform local term rewrites.
To make this local rewrite logic stronger, one should try to transform expressions into something I'd call a normal form. This is my approach:
*
*If a term contains literal values, try to move the term as far to the right as possible.
*Eventually, this literal value may appear rightmost and can be evaluated as part of a fully literal expression.
When to evaluate fully literal expression
An interesting question is when to evaluate fully literal expression. Suppose you have an expression
x * ( 1 / 3 )
which would reduce to
x * 0.333333333333333333
Now suppose x gets replaced by 3. This would yield something like
0.999999999999999999999999
Thus eager evaluation returns a slightly incorrect value.
At the other side, if you keep ( 1 / 3 ) and first replace x by 3
3 * ( 1 / 3 )
a rewrite rule would give
1
Thus, it might be useful to evaluate fully literal expression late.
Examples of rewrite rules
Here is how my rules appear inside the application: The _1, _2, ... symbols match any subexpression:
addRule( new TARuleFromString( '0+_1', // left hand side :: pattern
'_1' // right hand side :: replacement
)
);
or a bit more complicated
addRule( new TARuleFromString( '_1+_2*_1',
'(1+_2)*_1'
)
);
Certain special symbols only match special subexpressions. E.g. _Literal1, _Literal2, ... match only literal values:
addRule( new TARuleFromString( 'exp(_Literal1) * exp(_Literal2 )',
'exp( _Literal1 + _Literal2 )'
)
);
This rule moves non-literal expression to the left:
addRule( new TARuleFromString( '_Literal*_NonLiteral',
'_NonLiteral*_Literal'
)
);
Any name, that begins with a '_', is a pattern variable. While the system matches a rule, it keeps a stack of assignments of already matched symbols.
Finally, don't forget that rules may yield non terminating replacement sequences.
Thus while reducing expression, make the process remember, which intermediate expressions have already been reached before.
In my implementation, I don't save intermediate expressions directly. I keep an array of MD5() hashes of intermediate expression.
A set of rules as a starting point
Here's a set of rules to get started:
addRule( new TARuleFromString( '0+_1', '_1' ) );
addRule( new TARuleFromString( '_Literal2=0-_1', '_1=0-_Literal2' ) );
addRule( new TARuleFromString( '_1+0', '_1' ) );
addRule( new TARuleFromString( '1*_1', '_1' ) );
addRule( new TARuleFromString( '_1*1', '_1' ) );
addRule( new TARuleFromString( '_1+_1', '2*_1' ) );
addRule( new TARuleFromString( '_1-_1', '0' ) );
addRule( new TARuleFromString( '_1/_1', '1' ) );
// Rate = (pow((EndValue / BeginValue), (1 / (EndYear - BeginYear)))-1) * 100
addRule( new TARuleFromString( 'exp(_Literal1) * exp(_Literal2 )', 'exp( _Literal1 + _Literal2 )' ) );
addRule( new TARuleFromString( 'exp( 0 )', '1' ) );
addRule( new TARuleFromString( 'pow(_Literal1,_1) * pow(_Literal2,_1)', 'pow(_Literal1 * _Literal2,_1)' ) );
addRule( new TARuleFromString( 'pow( _1, 0 )', '1' ) );
addRule( new TARuleFromString( 'pow( _1, 1 )', '_1' ) );
addRule( new TARuleFromString( 'pow( _1, -1 )', '1/_1' ) );
addRule( new TARuleFromString( 'pow( pow( _1, _Literal1 ), _Literal2 )', 'pow( _1, _Literal1 * _Literal2 )' ) );
// addRule( new TARuleFromString( 'pow( _Literal1, _1 )', 'ln(_1) / ln(_Literal1)' ) );
addRule( new TARuleFromString( '_literal1 = pow( _Literal2, _1 )', '_1 = ln(_literal1) / ln(_Literal2)' ) );
addRule( new TARuleFromString( 'pow( _Literal2, _1 ) = _literal1 ', '_1 = ln(_literal1) / ln(_Literal2)' ) );
addRule( new TARuleFromString( 'pow( _1, _Literal2 ) = _literal1 ', 'pow( _literal1, 1 / _Literal2 ) = _1' ) );
addRule( new TARuleFromString( 'pow( 1, _1 )', '1' ) );
addRule( new TARuleFromString( '_1 * _1 = _literal', '_1 = sqrt( _literal )' ) );
addRule( new TARuleFromString( 'sqrt( _literal * _1 )', 'sqrt( _literal ) * sqrt( _1 )' ) );
addRule( new TARuleFromString( 'ln( _Literal1 * _2 )', 'ln( _Literal1 ) + ln( _2 )' ) );
addRule( new TARuleFromString( 'ln( _1 * _Literal2 )', 'ln( _Literal2 ) + ln( _1 )' ) );
addRule( new TARuleFromString( 'log2( _Literal1 * _2 )', 'log2( _Literal1 ) + log2( _2 )' ) );
addRule( new TARuleFromString( 'log2( _1 * _Literal2 )', 'log2( _Literal2 ) + log2( _1 )' ) );
addRule( new TARuleFromString( 'log10( _Literal1 * _2 )', 'log10( _Literal1 ) + log10( _2 )' ) );
addRule( new TARuleFromString( 'log10( _1 * _Literal2 )', 'log10( _Literal2 ) + log10( _1 )' ) );
addRule( new TARuleFromString( 'ln( _Literal1 / _2 )', 'ln( _Literal1 ) - ln( _2 )' ) );
addRule( new TARuleFromString( 'ln( _1 / _Literal2 )', 'ln( _Literal2 ) - ln( _1 )' ) );
addRule( new TARuleFromString( 'log2( _Literal1 / _2 )', 'log2( _Literal1 ) - log2( _2 )' ) );
addRule( new TARuleFromString( 'log2( _1 / _Literal2 )', 'log2( _Literal2 ) - log2( _1 )' ) );
addRule( new TARuleFromString( 'log10( _Literal1 / _2 )', 'log10( _Literal1 ) - log10( _2 )' ) );
addRule( new TARuleFromString( 'log10( _1 / _Literal2 )', 'log10( _Literal2 ) - log10( _1 )' ) );
addRule( new TARuleFromString( '_Literal1 = _NonLiteral + _Literal2', '_Literal1 - _Literal2 = _NonLiteral' ) );
addRule( new TARuleFromString( '_Literal1 = _NonLiteral * _Literal2', '_Literal1 / _Literal2 = _NonLiteral' ) );
addRule( new TARuleFromString( '_Literal1 = _NonLiteral / _Literal2', '_Literal1 * _Literal2 = _NonLiteral' ) );
addRule( new TARuleFromString( '_Literal1 =_NonLiteral - _Literal2', '_Literal1 + _Literal2 = _NonLiteral' ) );
addRule( new TARuleFromString( '_NonLiteral + _Literal2 = _Literal1 ', '_Literal1 - _Literal2 = _NonLiteral' ) );
addRule( new TARuleFromString( '_NonLiteral * _Literal2 = _Literal1 ', '_Literal1 / _Literal2 = _NonLiteral' ) );
addRule( new TARuleFromString( '_NonLiteral / _Literal2 = _Literal1 ', '_Literal1 * _Literal2 = _NonLiteral' ) );
addRule( new TARuleFromString( '_NonLiteral - _Literal2 = _Literal1', '_Literal1 + _Literal2 = _NonLiteral' ) );
addRule( new TARuleFromString( '_NonLiteral - _Literal2 = _Literal1 ', '_Literal1 + _Literal2 = _NonLiteral' ) );
addRule( new TARuleFromString( '_Literal2 - _NonLiteral = _Literal1 ', '_Literal2 - _Literal1 = _NonLiteral' ) );
addRule( new TARuleFromString( '_Literal1 = sin( _NonLiteral )', 'asin( _Literal1 ) = _NonLiteral' ) );
addRule( new TARuleFromString( '_Literal1 = cos( _NonLiteral )', 'acos( _Literal1 ) = _NonLiteral' ) );
addRule( new TARuleFromString( '_Literal1 = tan( _NonLiteral )', 'atan( _Literal1 ) = _NonLiteral' ) );
addRule( new TARuleFromString( '_Literal1 = ln( _1 )', 'exp( _Literal1 ) = _1' ) );
addRule( new TARuleFromString( 'ln( _1 ) = _Literal1', 'exp( _Literal1 ) = _1' ) );
addRule( new TARuleFromString( '_Literal1 = _NonLiteral', '_NonLiteral = _Literal1' ) );
addRule( new TARuleFromString( '( _Literal1 / _2 ) = _Literal2', '_Literal1 / _Literal2 = _2 ' ) );
addRule( new TARuleFromString( '_Literal*_NonLiteral', '_NonLiteral*_Literal' ) );
addRule( new TARuleFromString( '_Literal+_NonLiteral', '_NonLiteral+_Literal' ) );
addRule( new TARuleFromString( '_Literal1+(_Literal2+_NonLiteral)', '_NonLiteral+(_Literal1+_Literal2)' ) );
addRule( new TARuleFromString( '_Literal1+(_Literal2+_1)', '_1+(_Literal1+_Literal2)' ) );
addRule( new TARuleFromString( '(_1*_2)+(_3*_2)', '(_1+_3)*_2' ) );
addRule( new TARuleFromString( '(_2*_1)+(_2*_3)', '(_1+_3)*_2' ) );
addRule( new TARuleFromString( '(_2*_1)+(_3*_2)', '(_1+_3)*_2' ) );
addRule( new TARuleFromString( '(_1*_2)+(_2*_3)', '(_1+_3)*_2' ) );
addRule( new TARuleFromString( '(_Literal * _1 ) / _Literal', '_1' ) );
addRule( new TARuleFromString( '(_Literal1 * _1 ) / _Literal2', '(_Literal1 * _Literal2 ) / _1' ) );
addRule( new TARuleFromString( '(_1+_2)+_3', '_1+(_2+_3)' ) );
addRule( new TARuleFromString( '(_1*_2)*_3', '_1*(_2*_3)' ) );
addRule( new TARuleFromString( '_1+(_1+_2)', '(2*_1)+_2' ) );
addRule( new TARuleFromString( '_1+_2*_1', '(1+_2)*_1' ) );
addRule( new TARuleFromString( '_literal1 * _NonLiteral = _literal2', '_literal2 / _literal1 = _NonLiteral' ) );
addRule( new TARuleFromString( '_literal1 + _NonLiteral = _literal2', '_literal2 - _literal1 = _NonLiteral' ) );
addRule( new TARuleFromString( '_literal1 - _NonLiteral = _literal2', '_literal1 - _literal2 = _NonLiteral' ) );
addRule( new TARuleFromString( '_literal1 / _NonLiteral = _literal2', '_literal1 * _literal2 = _NonLiteral' ) );
Make rules first-class expressions
An interesting point: Since the above rules are special expression, which get correctly evaluate by the expression parser, users can even add new rules and thus enhance the application's rewrite capabilities.
Parsing expressions (or more general: languages)
For Cocoa/OBjC applications, Dave DeLong's DDMathParser is a perfect candidate to syntactically analyse mathematical expressions.
For other languages, our old friends Lex & Yacc or the newer GNU Bison might be of help.
Far younger and with an enourmous set of ready to use syntax-files, ANTLR is a modern parser generator based on Java. Besides purely command-line use, ANTLRWorks provides a GUI frontend to construct and debug ANTLR based parsers. ANTLR generates grammars for various host language, like JAVA, C, Python, PHP or C#. The ActionScript runtime is currently broken.
In case you'd like to learn how to parse expressions (or languages in general) from the bottom-up, I'd propose this free book's text from Niklaus Wirth (or the german book edition), the famous inventor of Pascal and Modula-2.
A: You're wanting to build a CAS (compute algebra system) and the topic is so wide that there is an entire field of study dedicated to it. Which means there are a few books that will probably answer your question better than SO.
I know some systems build trees that reduce constants first and then put the tree into a normalized form and then use a large database of proven/known formulas to transform the problem into some other form.
A: I believe you have to "brute force" such trees.
You will have to formulate a couple of rules that describe possible simplifications. Then you habe to walk through the tree and search for applicable rules. Since some simplifications might lead to simpler results than others you will have to do a similar thing that you do for finding the shortest route on a subway plan: try out all possibilities and sort the results by some quality criteria.
Since the number of such scenarios is finite you might be able to discover the simplification rules automatically by trying out all combinations of operators and variables and again have a genetic algorithm that verifies that the rule has not been found before and that it actually simplifies the input.
Multiplications can be represented as additions, so one rule might be that a - a cancels itself out: 2a-a = a+a-a
Another rule would be to first multiply out all divisions because those are fractions. Example:
1/2 + 3/4
Discover all the divisions and then multiply each fraction with the divisor on both sides of all other fractions
4/8 + 6/8
Then all elements have the same divisor and so can the unified to
(4+6)/8 = 10/8
Finally you find the highest common divisor between top and bottom
5/4
Applied to your tree the strategy would be to work from the bottom leaves upwards simplifying each multiplication first by converting it to additions. Then simplifying each addition like the fractions
All the while you would check agains your shortcut rules to discover such simplifcations. To know that a rule applies you probably have to either try out all permutations of a subtree. E.g. The a-a rule would also apply for -a+a. There might be a a+b-a.
Just some thoughts, hope that gives you some ideas...
A: This task can become quite complicated (besides the simplest transformation). Essentially this is what algebra software does all the time.
You can find a readable introduction how this is done (rule-based evaluation) e.g. for Mathematica.
A: You actually can't in general do this because, although they are the same mathematically, the may not be the same in computer arithmetic. For instance, -MAX_INT is undefined, so --%a =/= %a. Similarly for floats, you have to deal with NaN and Inf appropriately.
A: My naive approach would be to have some sort of data structure with inverses of each function (i.e. divide and multiply). You would obviously need further logic to make sure they are actually inverse since multiplying by 3 and then dividing by 4 is not actually an inverse.
Although this is primitive, I think it's a decent first pass at the problem and would solve a lot of the cases you noted in your question.
I do look forward to seeing your full solution and staring in awe at is mathematical brilliance :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "75"
} |
Q: JavaScript adds 0.000000002 to calculation Source: Pastebin
Screenshot: Image
<input alt="Flyer|49.80" type="checkbox" class="price" id="cb3" name="price_3" />
<input alt="CMS|199.99" type="checkbox" class="price" id="cb1" name="price_1" />
Hey folks!
Maybe someone can give me a little hint to the problem in my source.
It adds 0.000000002 to my total sum, when adding 49.8 + 199.99.
Thanks for any suggestions!
A: You need to understand how floating point numbers work and round your answers to the nearest two digits.
The short answer is that this is how JavaScript, and all languages that use floating point numbers, works. You can't "fix" it. All you can do is accept that floating point numbers aren't exact and deal with it.
A: Yes, as @duffymo alluded to, the problem has to do with floating point numbers - specifically, the root of the issue (and this is not peculiar to JavaScript) is that there is no way to map 0.1 to a finite binary floating point number.
A: var val = 49.8 + 199.99;
alert(val.toFixed(2));
A: The issue is that javascript stores numbers as 64-bit floating point numbers. This means that there are some additions where numbers that would add to 100.00 in decimal math won’t in floating point math.
For more refer to the links:
Is floating point math broken?
http://www.scribd.com/doc/5836/What-Every-Computer-Scientist-Should-Know-About-FloatingPoint-Arithmetic
You can avoid this by multiplying all inputs by 100, adding them, then comparing to 10,000. This will work because all integers between 2^-52 and 2^52 can be exactly represented in a double precision floating point numbers, but fractions may not be.
http://en.wikipedia.org/wiki/Double_precision_floating-point_format
Another approach is to roll your own decimal addition function to work on number strings.
A: It can be help for you.
Math.floor(val *10) / 10
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: library using Quartz PDF rendering routines statically compiled and then ported to Windows? is it possible to compile statically a c++ library under OSX which calls Quartz routines for PDF rendering and use it under Windows to be linked to a Windows c++ project?
A: If you have added another compiler to OSX that targets Windows then possibly, otherwise no.
The standard compilers for OSX cannot compile for a Windows target.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Generate Random Number in .NET without using any Inbuilt Functions I was wondering how the Random functions in every programming language works so I want to generate a number by myself i.e. I don't want to use any inbuilt classes or functions.
A: If you are curious how it works you can start with Wikipedia: Random number generation and List of random number generators. The second link will give you list of few popular algorithms (like Mersenne Twister) that you can implement by yourself.
You can also decompile System.Random with .Net Reflector and compare given algorithms with what is implemented natively in .Net
Also, Art of Computer Programming by D. Knuth has a chapter on random numbers and their generation.
A: For simplicity and speed, it's hard to beat the Xorshift random number generator. Whether it generates a good distribution is another question.
One example in C#: http://www.codeproject.com/KB/cs/fastrandom.aspx
Different languages and environments use different random number generators. As others have pointed out, there are lots of ways to generate pseudo-random numbers.
See C# Normal Random Number and other similar Stack Overflow questions.
A: As someone else commented, you really want to rely on framework functionality for this. If this is for academic purposes or out of pure interest, there are a number of RNG algorithms that are easy to implement. One is the multiply-with-carry (MWC) algorithm, which can be easily implemented in C#:
public class RNG
{
// Seeds
static uint m_w = 362436069; /* must not be zero */
static uint m_z = 521288629; /* must not be zero */
public int NextRandom()
{
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
return (int)((m_z << 16) + m_w);
}
}
For details on MWC, see http://www.bobwheeler.com/statistics/Password/MarsagliaPost.txt
A: To Generate the Random number without using Random() method
using System;
public class GenerateRandom
{
private int max;
private int last;
static void Main(string[] args)
{
GenerateRandom rand = new GenerateRandom(10);
for (int i = 0; i < 25; i++)
{
Console.WriteLine(rand.nextInt());
}
}
// constructor that takes the max int
public GenerateRandom(int max)
{
this.max = max;
DateTime dt = DateTime.Now;//getting current DataTime
int ms = dt.Millisecond;//getting date in millisecond
last = (int) (ms % max);
}
// Note that the result can not be bigger then 32749
public int nextInt()
{
last = (last * 32719 + 3) % 32749;//this value is set as per our requirement(i.e, these is not a static value
return last % max;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SSH troubles pushing with Git I'm trying to set up a git repository on Assembla (assembla.com) and I'm having trouble making my first "push". I'm fairly ignorant of git, but I've previously successfully pushed to a repository on github. I'm using git on Windows Vista. When I run git bash from the relevant directory and type "git push", I get:
The authenticity of host 'git.assembla.com (64.250.188.42)' can't be established.
RSA fingerprint is 31:06:...(omitted)...:07:e6.
Are you sure you want to continue connecting (yes/no)?
Entering "yes" is no good, it doesn't accept the passphrase.
I know that this has something to do with SSH keys, but I can't figure out what might be wrong with mine. My git name and email on my local machine match up with the ones I've entered on Assembla, and I've tried generating a new SSH key and uploading the id_rsa.pub file to Assembla to no effect.
A search turned up this forum thread: http://forum.assembla.com/forums/3/topics/2754
As far as I can tell none of the suggestions raised by the administrator in the final post apply. 1 and 2 shouldn't apply because this is a vanilla account on the site and I haven't changed any settings. 3, 4 and 5 I believe I have done. 6 I have done, although I deleted the line "GSSAPIAuthentication" because it generated an additional error message.
NB. I have another open question on StackOverflow regarding Git. This question is unrelated and concerns a different Windows machine. I have not abandoned my other question.
Edit:
Output of ssh -v git@git.assembla.com:
$ ssh -v git@git.assembla.com
OpenSSH_4.6p1, OpenSSL 0.9.8e 23 Feb 2007
debug1: Reading configuration data /c/Users/Philip/.ssh/config
debug1: Applying options for git.assembla.com
debug1: Connecting to git.assembla.com [64.250.188.42] port 22.
debug1: Connection established.
debug1: identity file /c/Users/Philip/.ssh/id_rsa.pub type 1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.1p1 Debian-5-assembla
debug1: match: OpenSSH_5.1p1 Debian-5-assembla pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_4.6
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
The authenticity of host 'git.assembla.com (64.250.188.42)' can't be established.
RSA key fingerprint is 31:06:3b:0d:cd:23:1a:41:dc:f2:c5:7d:9c:24:07:e6.
Are you sure you want to continue connecting (yes/no)?
Output of git remote -v:
$ git remote -v
origin git@git.assembla.com:ksv.git (fetch)
origin git@git.assembla.com:ksv.git (push)
The password prompt:
$ git push
The authenticity of host 'git.assembla.com (64.250.188.42)' can't be established.
RSA key fingerprint is 31:06:3b:0d:cd:23:1a:41:dc:f2:c5:7d:9c:24:07:e6.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'git.assembla.com,64.250.188.42' (RSA) to the list of known hosts.
Enter passphrase for key '/c/Users/Philip/.ssh/id_rsa.pub':
A: It looks from the error message as if the problem is that you're specifying your public key (id_dsa.pub) as IdentityFile in your .ssh/config file instead of your private key, which would be just id_dsa.
The questioner has confirmed in the comments above that this was the problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Need some help with a RegEx query Given the following string:
someObject.SomeFunction.parameters[0] = new Thing('ValueName', 0);
How to I get just the ValueName value? - using C#
A: You can use String.Substring method or using regex:
(?<=')(?:\\'|[^'])*(?=')
e.g.:
Regex.Match(input, @"(?<=')(?:\\'|[^'])*(?=')").Value
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Retrieve a cookie set in Python serverside G'day,
I'm following a guide found here: http://www.doughellmann.com/PyMOTW/Cookie/
which has the code:
c = Cookie.SimpleCookie()
c.load(HTTP_COOKIE)
to retrieve a cookie previously set (by the server), but my server does not have the HTTP_COOKIE variable, so how else can I do it?
I would prefer to continue using the above guide's method, but if there is something far better I am willing to consider it.
Otherwise, I'm not using any frameworks (just raw .py files) and would like to keep it that way.
Cheers
A: The way discussed in the comments is:
import os
def getcookies():
cookiesDict = {}
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
for cookie in cookies:
cookie = cookie.split('=')
cookiesDict[cookie[0]] = cookie[1]
return cookiesDict
which would then return a dictionary of cookies as key -> value
cookies = getcookies()
userID = cookies['userID']
and obviously you would then add error handling
However there are also other methods, eg., using the cookie module
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using delegate() for dynamically added container Could you explain me how I can catch click event for dynamically added checkbox? I can do it, but can't understand one thing - why can't use delegate() for dynamically added container for checkbox. Code is like that:
<p style="blue">
<input type="checkbox" name="first" />
</p>
Example here.
In this example I never catch the message ".blue CLICK" but only see "#ch CLICK".
A: In your example - When the delegate is initialised the p element with the blue class does not exist. The container you setup the delegate on needs to exist in the dom.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Where can i find a CMS UML example? There are plenty of people saying that is it useless to develop your own CMS. I deduce that 'computer science' has enough experience in developing CMS. But I can not find an example of the UML of a CMS. An open source CMS or whatever, I need 'inspiration'.
If you have a link, feel free to post it.
A: I'm afraid the best you'll find is the database schema for existing CMSs like wordpress or drupal. You could see this schema as a UML class diagram (some CMSs don't use foreign keys, in those cases, you'll need to complement the schema info to deduce the associations between classes).
You could also try a reverse engineering tool and apply it to the CMS you want to get some diagrams out of it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: left shift magic I have code:
signed short a = -32740;
float c;
float b;
b = (signed short)(a << 4);
c = a << 4;
printf("(signed short)(a << 4): %f\n", b);
printf("(a << 4): %f\n", c);
output:
(signed short)(a << 4): 448.000000
(a << 4): -523840.000000
Why 16 senior registers not reset after the shift (c = a << 4;)?
Program executed on x86 machine with 32-bit linux.
A:
b = (signed short)(a << 4);
This line does the following:
*
*Calculate (a << 4). The calculation is done with integers (default in C). The result is: -523840
*Truncate the result (by dropping bits) to 16 bit by casting to signed short. (result is 448)
*convert the result to float (no change in value)
c = a << 4;
This line does the following:
*
*Calculate (a << 4). The calculation is done with integers (default in C). The result is: -523840
*convert the result to float (no change in value)
The fact that 'a' is declared as a signed short does not make a difference because all calculations are always done with the int datatype. I assume that your system has 32 bit integers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Free Powershell debugging tools Quest Power GUI Script Editor is a nice free tool for writing and debugging Powershell script.
We have Windows XP SP2. Is there any similar debugger that let's you debug step through scriptthat is provided free of charge by Microsoft that works on XP? I suspect that it'll be easier to get a MS add on tool approved than a 3rd party.
A: Build-in Windows PowerShell ISE (GUI for Powershell) has debugging support.
A: There's also the new Editor on the block, PowerSE
http://powerwf.com/products/powerse.aspx
A: Since your question of june there were few changes. The actual PowerGUI script editor (version 3.0.0) doesn't work with PowerShell V1.0. But you can use a version before 2.0 . I'am using PowerGUI 1.9.5.966 which works perfectly with PowerShel V1.0. I give you a copy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: R bindings for Mapnik? I frequently find myself doing some analysis in R and then wanting to make a quick map. The standard plot() function does a reasonable job of quick, but I quickly find that I need to go to ggplot2 when I want to make something that looks nice or has more complex symbology requirements. Ggplot2 is great, but is sometimes cumbersome to convert a SpatialPolygonsDataFrame into the format required by Ggplot2. Ggplot2 can also be a tad slow when dealing with large maps that require specific projections.
It seems like I should be able to use Mapnik to plot spatial objects directly from R, but after exhausting my Google-fu, I cannot find any evidence of bindings. Rather than assume that such a thing doesn't exist, I thought I'd check here to see if anyone knows of an R - Mapnik binding.
A: The Mapnik FAQ explicitly mentions Python bindings -- as does the wiki -- with no mention of R, so I think you are correct that no (Mapnik-sponsored, at least) R bindings currently exist for Mapnik.
You might get a more satisfying (or at least more detailed) answer by asking on the Mapnik users list. They will know for certain if any projects exist to make R bindings for Mapnik, and if not, your interest may incite someone to investigate the possibility of generating bindings for R.
A: I would write the SpatialWotsitDataFrames to Shapefiles and then launch a Python Mapnik script. You could even use R to generate the Python script (package 'brew' is handy for making files from templates and inserting values form R).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to cache mvc3 webgrid results (so that col sort click doesn't? Can somebody please tell me how I can cache my webgrid results so that when I sort by column it doesn't re-run my stored procedure query every time?
When clicking on a column link to sort, the stored proc (which is a little slow) that populates the table/grid is re-executed every time and hits the database. Any caching tips and tricks would be greatly appreciated.
Thx!
A: Well inside the controller action which is invoking the method on your repository supposed to query the database you could check whether the cache already contains the results.
Here's a commonly used pattern:
public ActionResult Foo()
{
// Try fetching the results from the cache
var results = HttpContext.Cache["results"] as IEnumerable<MyViewModel>;
if (results == null)
{
// the results were not found in the cache => invoke the expensive
// operation to fetch them
results = _repository.GetResults();
// store the results into the cache so that on subsequent calls on this action
// the expensive operation would not be called
HttpContext.Cache["results"] = results;
}
// return the results to the view for displaying
return View(results);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Implementing a javascript function to search in a div, getting textrange for the search How do I get the textrange to do a search for a div (or a form)? Are there scripts already available, or jquery functions that search the text of a div?
I append a form to a div with this code:
$('#'+card_id).append('<form id="frm_search" name="frm_search" class="editableToolbar frm_search_links"> <input type="text" placeholder="Type a string..." name="linkcard_search_string" class="txt_form"> <a href="#" title="Search" class="ico_search btn_form" onClick="search_links(\''+card_id+'\', this.form); "></a> <a href="#" title="Close" class="ico_delete btn_form" onClick="close_search(\''+card_id+'\', this.form); "></a> </form>');
I'd like to have a search function that will only look for a string in that div. I specify the text range like this.
txt = window.document.body.getelementbyid(card_id).createTextRange();
The search function is one that I found on the net and that I am trying to update to search the div instead of the entire page. There will be several divs on the page and I want the search to be specific to each. I call that function from search_links(card_id);.
function search_links (card_id, form) {
var search_str = document.frm_search.linkcard_search_string.value;
/* alert('search_links '+search_str); */
return search_linkcard(search_str, card_id);
}
var IE4 = (document.all);
var n = 0;
function search_linkcard(str, card_id) {
alert (card_id + ' ' + str);
var txt, i, found;
if (str == "")
return false;
// Find next occurance of the given string on the page, wrap around to the
// start of the page if necessary.
if (IE4) {
txt = window.document.body.getelementbyid(card_id).createTextRange();
// Find the nth match from the top of the page.
for (i = 0; i <= n && (found = txt.findText(str)) != false; i++) {
txt.moveStart("character", 1);
txt.moveEnd("textedit");
}
// If found, mark it and scroll it into view.
if (found) {
txt.moveStart("character", -1);
txt.findText(str);
txt.select();
txt.scrollIntoView();
n++;
}
// Otherwise, start over at the top of the page and find first match.
else {
if (n > 0) {
n = 0;
search_linkcard(str, card_id);
}
// Not found anywhere, give message.
else
alert("Not found.");
}
}
return false;
}
My specific questions are those at the beginning of the question: How do I specify a text range for the div? Is the syntax I have right? Are there scripts that already do what I want, i.e. search the contents of a specific div?
A: Did the search with :contains. Did not do one match at a time. Highlighted all matches.
// Open search
function open_search(card_id) {
$('#'+card_id).append('<form id="frm_search" name="frm_search" class="editableToolbar frm_search_links"> <input type="text" placeholder="Type a string..." name="linkcard_search_string" class="txt_form" onclick="clear_search(\''+card_id+'\', this.form);"> <a href="#" title="Search" class="ico_search btn_form" onClick="search_links(\''+card_id+'\', this.form); "></a> <a href="#" title="Close" class="ico_delete btn_form" onClick="close_search(\''+card_id+'\', this.form); "></a> </form>');
var frm_elements = frm_search_link.elements;
for(i=0; i<frm_elements.length; i++) {
field_type = frm_elements[i].type.toLowerCase();
switch (field_type)
{
case "text":
frm_elements[i].value = "";
break;
default:
break;
}
}
}
// Close search
function close_search(card_id, form) {
$('form.frm_search_links', $('#'+card_id)).remove();
var card_select = '#'+card_id;
$('.link',$(card_select)).removeClass('search_results');
}
// Search links
function search_links (card_id, form) {
var search_str = document.frm_search.linkcard_search_string.value;
var search_select = '.link:contains('+search_str+')';
var card_select = '#'+card_id;
var result = $(search_select,$(card_select)).addClass('search_results');
if (result.length == 0 || result.length == null) document.frm_search.linkcard_search_string.value = 'Not found.';
}
// Clear search
function clear_search (card_id, form) {
document.frm_search.linkcard_search_string.value = '';
var card_select = '#'+card_id;
$('.link',$(card_select)).removeClass('search_results');
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: deflate and inflate (zlib.h) in C I am trying to implement the zlib.h deflate and inflate functions to compress and decompress a char array (not a file).
I would like to know if the following syntax is correct ? Am I missing something or defined something incorrectly ?
char a[50] = "Hello World!";
char b[50];
char c[50];
// deflate
// zlib struct
z_stream defstream;
defstream.zalloc = Z_NULL;
defstream.zfree = Z_NULL;
defstream.opaque = Z_NULL;
defstream.avail_in = (uInt)sizeof(a); // size of input
defstream.next_in = (Bytef *)a; // input char array
defstream.avail_out = (uInt)sizeof(b); // size of output
defstream.next_out = (Bytef *)b; // output char array
deflateInit(&defstream, Z_DEFAULT_COMPRESSION);
deflate(&defstream, Z_FINISH);
deflateEnd(&defstream);
printf("Deflate:\n%lu\n%s\n", strlen(b), b);
// inflate
// zlib struct
z_stream infstream;
infstream.zalloc = Z_NULL;
infstream.zfree = Z_NULL;
infstream.opaque = Z_NULL;
infstream.avail_in = (uInt)sizeof(b); // size of input
infstream.next_in = (Bytef *)b; // input char array
infstream.avail_out = (uInt)sizeof(c); // size of output
infstream.next_out = (Bytef *)c; // output char array
inflateInit(&infstream);
inflate(&infstream, Z_NO_FLUSH);
inflateEnd(&infstream);
printf("Inflate:\n%lu\n%s\n", strlen(c), c);
A: You can't printf the deflated output like this. It's not null terminated. You can't strlen it either.
Since your input is a string though you probably do want to only pass the content of the string including the null terminator. So set avail_in to strlen(a) + 1.
You need to examine the next_out and avail_out fields after you call deflate to see how much data was written to the output buffer.
See documentation here under the deflate call.
Here's your modified code. Note if you're compressing something that is not a string you'll need to change this and also with strings you may compress without the terminating zero and add it back after decompressing.
char a[50] = "Hello World!";
char b[50];
char c[50];
// deflate
// zlib struct
z_stream defstream;
defstream.zalloc = Z_NULL;
defstream.zfree = Z_NULL;
defstream.opaque = Z_NULL;
defstream.avail_in = (uInt)strlen(a)+1; // size of input, string + terminator
defstream.next_in = (Bytef *)a; // input char array
defstream.avail_out = (uInt)sizeof(b); // size of output
defstream.next_out = (Bytef *)b; // output char array
deflateInit(&defstream, Z_DEFAULT_COMPRESSION);
deflate(&defstream, Z_FINISH);
deflateEnd(&defstream);
// This is one way of getting the size of the output
printf("Deflated size is: %lu\n", (char*)defstream.next_out - b);
// inflate
// zlib struct
z_stream infstream;
infstream.zalloc = Z_NULL;
infstream.zfree = Z_NULL;
infstream.opaque = Z_NULL;
infstream.avail_in = (uInt)((char*)defstream.next_out - b); // size of input
infstream.next_in = (Bytef *)b; // input char array
infstream.avail_out = (uInt)sizeof(c); // size of output
infstream.next_out = (Bytef *)c; // output char array
inflateInit(&infstream);
inflate(&infstream, Z_NO_FLUSH);
inflateEnd(&infstream);
printf("Inflate:\n%lu\n%s\n", strlen(c), c);
A: zlib already has a simple inflate/deflate function you can use.
char a[50] = "Hello, world!";
char b[50];
char c[50];
uLong ucompSize = strlen(a)+1; // "Hello, world!" + NULL delimiter.
uLong compSize = compressBound(ucompSize);
// Deflate
compress((Bytef *)b, &compSize, (Bytef *)a, ucompSize);
// Inflate
uncompress((Bytef *)c, &ucompSize, (Bytef *)b, compSize);
When in doubt, check out the zlib manual.
My code is crappy, sorry =/
A: The zpipe example (http://zlib.net/zpipe.c) pretty much covers it, just remove the file ops(the f prefixed function), and you replace in and out with your in-memory buffers, though it may be enough to only replace in or keep the buffers as-is depending on you usage. Just note that you will need to make your out buffer resizeable to account for decompression of arbitrarily sized data, if you are planning on having unknown sized chunks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Is it better to have two separate user tables or one? My web app is going to have two types of users that are 100% different - in fields, functions, and purpose on the site. The purpose of one type of user is to post blogs, and the purpose of the other is to read them and "follow" the posters.
The ONLY stuff they have in common are the need for an id, email, password and a couple other bits of meta data such as date joined, etc.
Should I attempt to stem them from the same account table, or make one table for each?
NOTES
-One potential thing to think about is that, to prevent user confusion, I think emails between the two types of accounts should be unique.
-Readers and Authors will have different sets of data that will need to be stored about them aside from the normal "account" meta data.
A: I would separate them.
TABLE User {
id
email
password
salt
created
modified
}
TABLE follower {
user_id
...
}
TABLE author {
user_id
...
}
Over time your application will grow. Perhaps now you have two destinct roles - but it may change in the future. You may have authors that also follow other authors, or followers that are "upgraded" to authors. You might also start adding other "roles" and want something like this:
TABLE user_role {
user_id
role_id
}
TABLE role {
id
name
}
A: Define "user". If a user is somebody who has registered him or herself on your site, using an e-mail address, password and nickname, and who can log on, then stick everyone in the users table.
The things users can or can not do on a site does not differ for a user. It's their permissions that are different. Map permissions to users in a separate table. Don't create a table for each type of user.
Otherwise, when you're adding a new kind of permission in the future, you don't have to add a new table for that type of user (and alter all (sql) code that handles with users: logging in, resetting passwords, and so on). You just add a new type of permission, and map that to their respective users.
A: it will save you allot of work to just have one table and have a single column in the table that defines which type they are .
A: No, make one table for each. It will be easier to manage, it'll be scalable
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to pass String from 2 activities to one? I have two activitys with lists.
One for tablet's and one for regular density phones.
When an item in the list is clicked it launches the same activity for either activity with list's.
The problem is when an item is clicked i have getter and setter class that gets the URL for a particular item and passes it to the launching activity like this...
private String URL = null;
try{
URL = com.fttech.AbstractFeedsActivity.feed_url;
}
catch(IllegalArgumentException e){
e.printStackTrace();
URL = com.fttech.ItemsActivity.url;
}
As you see what i tried to do is try and catch.
So if the first one isnt found then the second one will be retrieved.
But it doesnt seem to work.
It returns null each time.
For what i have describe what is the best way to implement this?
Is my way logic? Or is there a better way.
Thanks
A: Try this,
private String URL = null;
try{
URL = com.fttech.AbstractFeedsActivity.feed_url;
if(TextUtils.isEmpty(URL)){
URL = com.fttech.ItemsActivity.url;
// Pass this URL
}
else{
// If its not empty then it will pass the first URL
}
}
catch(IllegalArgumentException e){
e.printStackTrace();
}
A: No need to pass String to 2 activities, if you want to just pass strings to one or as many activities as you want, just put them in SharedPreferences or declare a variable in static class and then set/get it whenever you want.
A: Passing values from one Activity to another:
Intent intent = new Intent(context, CalledActivity.class);
intent.putExtra(key, value);
startActivity(intent);
If you want some data back from called Activity then you can use startActivityForResult() as:
Intent intent = new Intent(context, CalledActivity.class);
intent.putExtra(key, value);
startActivityForResult(intent, requestCode);
In called activity you can set data as:
setResult(RESULT_OK, intent);
Note: Here you set the value in intent and pass it to setResult().
On returning back to calling Activity you can get data by overriding:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
//Get data from Intent "data" and do your task here....
}
}
Note: You can pass primitive data type values thru Intent and if you want to pass other types then you have to use Bundle like this.
Bundle data = new Bundle();
data.putIntArray(key, value);
//same way you can set other values.......
//Now set this Bundle value to Intent as you do for primitive type....
Intent intent = new Intent(context, CalledActivity.class);
intent.putExtra(data);
startActivity(intent);
Receiving data in Activity:
//For primitive values:
DataType var_name = getIntent().getExtras().get(key);
//For Bundle values:
Bundle var_name = getIntent().getExtras().getBundle(key);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: 2 divs problem with box shadow I have 2 divs where the first is on top and the second is below that...
I have added shadow to the first div which is on top and looks well.
box-shadow: 0px 5px 5px #000000;
-moz-box-shadow: 0px 5px 5px #000000;
-webkit-box-shadow: 0px 5px 5px #000000;
But when i add a gradient css on the second div which is below, the first loses its shadow... or i dont know whats going on...
I need to be able to see the shadow of the first without adding margin to the second div below.
Thanks
EDIT:
My mark up is:
<div id="header">
<div class="960width"></div>
</div>
<div id="content">
<div class="960width"></div>
</div>
My css is:
#content{
background: #e5e5e5;
background: -moz-linear-gradient(top, #e5e5e5 0%, #ffffff 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#e5e5e5), color-stop(100%,#ffffff));
background: -webkit-linear-gradient(top, #e5e5e5 0%,#ffffff 100%);
background: -o-linear-gradient(top, #e5e5e5 0%,#ffffff 100%);
background: -ms-linear-gradient(top, #e5e5e5 0%,#ffffff 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e5e5e5', endColorstr='#ffffff',GradientType=0 );
background: linear-gradient(top, #e5e5e5 0%,#ffffff 100%);
padding-top:15px;
}
#header{
background: #ffffff;
background: -moz-linear-gradient(top, #ffffff 0%, #e5e5e5 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#e5e5e5));
background: -webkit-linear-gradient(top, #ffffff 0%,#e5e5e5 100%);
background: -o-linear-gradient(top, #ffffff 0%,#e5e5e5 100%);
background: -ms-linear-gradient(top, #ffffff 0%,#e5e5e5 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#e5e5e5',GradientType=0 );
background: linear-gradient(top, #ffffff 0%,#e5e5e5 100%);
padding:5px;
box-shadow: 0px 5px 5px #000000;
-moz-box-shadow: 0px 5px 5px #000000;
-webkit-box-shadow: 0px 5px 5px #000000;
}
A: This is HTML tags :
<div id="top">
<div id="back">
[Content]
</div>
</div>
your CSS was fine, you only need to change your HTML tag, if you do this, your problem is fix ... look at this Fiddle , i think this is what you meant ...
PS: if you gave width to the top DIV, you will see the shadow in right and left ...
PS2 : i changes the "ID"s name ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: To find the Nth node from last when visited nodes are getting deleted So the question is : find kth node frm last in a linked list if nodes a disappearing once read.This should be done in one pass only.
Try avoiding extra memory .
I am aware of the trivial solution to this problem where two pointers(P and Q lets say) to the header node are taken and P of them is incremented N times and after that both pointers are incremented.The pointer Q points to the Nth last element.
But the question is somewhat different here .here the nodes are disappearing once they are read so there is no way the two pointer way could be used .
And kindly don't close the question before reading it. because this question is different .
Thanks
A: Keep on storing K elements somewhere, for example if K is 6, then store 6 latest read nodes somewhere as you traverse the linked list, and on reading next node, store that and remove the oldest read node from those you have stored. Once the linked list ends, you will have the last K elements stored (use a linked list or an array etc for this), and the Kth element from the last will be the oldest stored element.
this may not be the most efficient solution as i was typing while i was thinking, but it should work.
A: *
*Create a queue of size K
*Sequentially read each element of the list.
*As each node is read, make a copy of node and enqueue onto the queue. If queue is full, dequeue the queue as well.
*After reading the last node in the list, dequeue the queue. This is the K-to-last element.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Changing Xxs in IntelliJ Idea I am working with IntelliJ Idea and I need to change the -Xxs. Where should I change it from?
A: idea.vmoptions file under /bin in IntelliJ installation directory.
A: For IDEA itself or for your app? If the first, see reply from Tomasz. If the latter, edit the VM options in the Run/Debug configuration.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: A special text on a web site Assume that there is a web site which includes 3 different pages.
I want to show a text one of the pages randomly, with is formatted with css.
For instance the pages are below:
hello-world.aspx
hi-sun.aspx
good-night-moon.aspx
* When John enters to the site, the text will appear on hi-sun.aspx,
* When Elmander enters to the site, the text will appear on hello-world.aspx
And when one enters the page which includes a special text, even if come again, it shouldn't appear.
Psedue Code:
if(Session["first"] == "1")
{
//show the text in a random page
}
else
{
//text.visible = false
}
in the if block
how can I supply the text in a random page. (it shouldn't appear in every page, should appear only one page)
How can I do? Are there any suggestions?
Thank you.
A: I don't fully understand what you want to do, but I think it's something like this:
You have a couple of different sites (3), and you have a text (welcome or something) you only want to show once. But after typing in your url the user should see one of the sites randomly.
For the first (if you don't want the user to log in) you can either save some flag in the Session object or create a cookie for the user (saying he has seen the text) and check this every time you want to show it.
The session will on the server but will be lost so the user might see the same message later again if he revisits your site. But while staying he will see it only once.
The second is on the client. If he accepts the cookie he will never see the message again if not he might see it everytime because you cannot know. Maybe you want some combination of these both.
For the second you will have to send a redirect if you don't want to get fancy with a deep dive into System.Web.
In the case above you can just do:
if(Session["first"] == null)
{
Session["first"] = true;
//show the text in a random page
}
else
{
text.Visible = false
}
but note that the session will not stay forever for the current user.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: CM7 for Milestone - build from source while kernel.org is down for maintenance I want to build CM7 for my Milestone but kernel.org being down makes that hard for me since all howtos and repos I found rely on it's existence - anyone knows a quick workaround?
I already asked this question here: http://android.doshaska.net/cm7build - but got no feedback - so perhaps I am lucky here
A: There is a copy of CyanogenMod sources on github.com: https://github.com/CyanogenMod
Get the kernel source form there.
A: If you only need a vanilla kernel source, you can extract it from a Debian package called linux-source-2.6.x. Search for linux-source on packages.debian.org. Note that not all versions are available. Ubuntu has similar packages in Launchpad.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Silverlight 5 Application cannot get HasElevatedPermissions to be true I am using Silverlight 5 RC on a Windows 7 x64 OS running IE9.
I am trying to get HasElevatedPermissions=True.
I have made the necessary change to the Windows registry and signed the xap using a test certificate as documented here :
http://pitorque.de/MisterGoodcat/post/Silverlight-5-Tidbits-Trusted-applications.aspx
I even chose the Use Local IIS Web Server option on the Web project and a project Url with a localhost domain.
I still get HasElevatedPermissions=False.
When I checked the two boxes to Require Elevated trust both outside and in the browser, I got this message:
{System.TypeLoadException: Inheritance security rules violated while overriding member: 'System.Collections.ObjectModel.Collection`1.Add(System.__Canon)'. Security accessibility of the overriding method must match the security accessibility of the method being overriden.
at System.Windows.Controls.DomainDataSource.InitializeView()
at System.Windows.Controls.DomainDataSource..ctor()}
Someone kindly tell me what I am missing here.
A: Try updating the registry keys or include "Trusted Root Certification Authorities" in your certificate as explained below:
http://www.silverlightshow.net/items/10-Laps-around-Silverlight-5-Part-10-of-10.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Javascript : 'Variable Not Defined' inside a self invoking function I wrote the following code that outputs the sum of squared iterating numbers:
(function () {
var i = 4, sum = 0;
while(i--) sum+=i*i;
})();
console.log(sum);
The problem is I get the following error in console: sum is undefined unless I take the sum out and declare it as global scope:
//this works but this is not what I want.
sum = 0;
(function ( ) {
var i=4
while(i--) sum+=i*i;
})();
console.log(sum);
Could some one help me understand?
Thanks
A: var sum = (function ( ) {
var i=4, sum = 0;
while(i--) sum+=i*i;
return sum;
})();
console.log(sum);
You created a local variable called sum and want to use it outside it's scope. You don't want to declare it in a higher scope so you have to export it.
The only way to export local (primitive) variables is the return statement.
A: A self-invoking function has its own scope (i.e. place to live for variables), so sum ceases to exist after the function and all dependent closures finished executing and it is not accessible from outside. In fact, having a separate scope that won't spoil the global or any other scope is the main reason why People use self executing functions.
A: Because you are accessing sum outside your function scope at the line:
console.log(sum), where sum is not visible.
If you do not want to put sum in global scope, then you got to take the statement console.log(sum) within the function scope.
A: you are defining sum inside the function which is local variable. and printing the sum outside the function which is out of scope.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to add an object file to every link There is a bug in RHEL5's gcc-4.3.2 with which we are stuck. As a work-around we have extracted the missing object and put it in an object file. Adding this object file to every link makes the problem go away.
While adding it directly to LDFLAGS seems like a good solution, this doesn't work since e.g. libtool cannot cope with non-la files in there.
A slightly more portable solution seems to be to directly patch the gcc spec to add this to every link. I came up with
*startfile:
+ %{shared-libgcc:%{O*:%{!O0:/PATH/TO/ostream-inst.o}}}
where ostream-inst.o is added to the list of startfiles used in the link when compiling a shared library with optimizations.
Trying to compile boost with this spec gives some errors though since its build directly sets some objects with ld's --startgroup/--endgroup.
How should I update that spec to cover that case as well, or even better, all cases?
A: Go through this URL Specifying subprocesses and the switches to pass to them and GCC Command Options
If this help you, thats great.
A: I know this is not the answer you want to hear (since you specified otherwise in your question), but you are running into trouble here and are likely to run into more since your compiler is buggy. You should find a way of replacing it, since you'll find yourself writing even more work-around code the next time some obscure build system comes along. There's not only bjam out there.
Sorry I can't help you more. You might try simply writing a .lo file by hand (it's a two-liner, after all) and insert it into your LDFLAGS.
A: If it is a bug of GCC 4.3, did you try to build (by compiling from sources) and use a newer GCC. GCC 4.6.2 is coming right now. Did you consider using it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: I want to prompt a user for the first 5 characters of a file then have it search for the files I'm trying to write a script that will prompt the user for the first 5 charters of a file name then have it search the directories for any files that start with that. Then I want it to check to see if a folder is created with the file names and if not create one then move the files there. But if there is a directory for it already then to just move the files too the folder.
A: Break it down step by step:
"prompt the user for the first 5 characters of a file name" -- you can use the shell read command to get the data. Try a simple shell script:
#!/bin/bash
read foo
echo "foo = $foo"
"if a folder is created with the file names" -- you can use find to see if a file exists. for example:
find . -name abcde\*
"But if there is a directory for it already then to just move the files too the folder." -- the command mkdir takes a -p option so that, if the directory already exists, it won't do anything.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Encountering errors when replacing JPanels I'm in the process of creating a menu with several panels that are removed/added as the user navigates by clicking on buttons.
After trying various things, I came to one that made the most sense to me but gives me errors.
My error-producing "solution":
public void actionPerformed (ActionEvent evt) {
Object source = evt.getSource();
if (source == jButton1) {
changePanels(jPanel1, singlePanel1);
}
}
public void changePanels (JPanel a, JPanel b) {
getContentPane().removeAll();
getContentPane().add(b);
validate();
repaint();
}
For some reason, it produces these errors:
$Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java:1041)
at java.awt.Container.add(Container.java:365)
at phantasma.OriginalFrame.changePanels(OriginalFrame.java:156)
at phantasma.OriginalFrame.actionPerformed(OriginalFrame.java:149)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6288)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6053)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4651)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4481)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4481)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:643)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:602)
at java.awt.EventQueue$1.run(EventQueue.java:600)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:616)
at java.awt.EventQueue$2.run(EventQueue.java:614)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:613)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
I've run through various troubleshooting, but I'm not sure what the issue is. Help is greatly appreciated, thank you.
A: NullPointerException is one of the easiest problems to diagnose, because it tells you the source file and the line number at which it occurs.
In your case, it's
phantasma.OriginalFrame.changePanels(OriginalFrame.java:156)
Open your IDE, go to that line, and look for dereferenced object references. One of them is null; you assumed it wasn't.
If that's not enough, set a breakpoint and navigate to that spot in the debugger. It'll tell you exactly what's null.
Once you figure that out, think about why that object isn't initialized properly and fix it.
A: 1) you can't declare for getContentPane() is useless from Java5 and higher
2) is isn't there declared any LayoutManager (probably your case) then JFrame , JDialog or JWindow has by default BorderLayout, all another JComponents have got ba default FlowLayout
3) if is there BorderLayout and isn't there declared decision Area (CENTER, NORTH...), then Component is by default placed to the CENTER area
4) for switch between JComponents and only if is there used BorderLayout, is required call only
myContainer.add(someComponent, BorderLayout.DECISION_AREA);
revalidate();
repaint();
and in you case is only
add(someComponent);
revalidate();
repaint();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Which comments documentation format is better for JavaScript? Is there are any comments documentation format for JavaScript and processor for this format which generates HTML documentation?
Currently I am using VSDoc xml comments for providing IntelliSense help at developing time, but as I know there is no documentation generator for such comments.
So alternatively my question may sounds like: Is there are any utility which translates VSDoc comments from JavaScript files to HTML?
A: Have you looked at auto generated documentation from JavaDoc or VSDoc or JSDoc or anything like that.
They are all ugly and un-readable.
The solution is two fold
*
*annotate your code with docco
*Make your API documentation hand written.
There is a third option which is to revolutionize the way we do auto generated documentation, if you can then please do.
A: I've used Natural Docs for a few projects. The syntax is nice for reading the inline, but since it doesn't have "full language support" for JavaScript, you have to be somewhat explicit about each function/constant/class/whatever you want to document.
A: There is a utility that parses Javascript files and outputs the same XML format NDoc and Sandcastle use: AjaxDoc
That way you get the VS intellisense from the same comments and can output any format that you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Adding comments mod into Smarty Template PHP site My site is built around X-Cart 4.2.3, which is built around Smarty Templates. I am trying to figure out a way to add Facebook Comments to my dynamic product pages (https://developers.facebook.com/docs/reference/plugins/comments/). These have to have unique URLs for each product page. I found an X-cart wiki on how to add the LIKE button, which I did successfully. This was the code for the LIKE button:
<iframe src="//www.facebook.com/plugins/like.php?href={$php_url.url|escape:"url"}&send=false&layout=standard&width=350&show_faces=true&action=like&colorscheme=light&font=verdana&height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:300px; height:80px;" allowTransparency="true"></iframe>
The code above is exactly the same as what Facebook's tool spits out, except for the dynamic URL variable: {$php_url.url|escape:"url"}
I wanted to basically repeat the same process for the COMMENTS module, but that one is strictly xfbml, rather than iframe, which creates two problems:
Problem 1: even if I paste the xfbml code verbatim into my product.tpl template, I can't get the comments mod to show up on the front end of the store. Same thing happens with the xfbml code of the LIKE button. Only iframe seems to work.
Problem 2: even if I solve the first problem, how to I utilize the URL variable in the fb tag, since it has quotes around the URL?
Any thoughts?
Below is the standard comments code:
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<fb:comments href="example.com" num_posts="10" width="500"></fb:comments>
A: I think you want the Smart Literal tag. You should turn if on/off inside JS and may be effecting your URL issue too. You can see find details here:
http://www.smarty.net/docsv2/en/language.function.literal
A: Colin,
brilliant call on your part. You solved the problem! This code actually works perfectly:
<div id="fb-root"></div>
{literal}
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
{/literal}
<fb:comments href="{$php_url.url|escape:"url"}" num_posts="10" width="730"></fb:comments>
One small problem... the comment mod sometimes appears at the bottom of articles, and sometimes not. I've noticed this only in the latest version of IE. It's as if sometimes the pages load fully, but sometimes they don't. Could be a problem on my end, I hope. If you have a moment, take a look at these articles: http://horrorunlimited.com/Fresh-Blood-and-Crumpets/
Dima
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Remove html tags from string using jquery i want to know how to remove html tags from a string using jquery, html looks like this
var string = '<p><marquee> some text </marquee>/p>';
now i want to remove all html tags and just want the plain text from it.
thank you
A: jQuery text() will help you like this :
var willbeequaltosometext = $("marquee").text();
A: You could do this yust like this:
$('<p><marquee> some text </marquee></p>').text()
A: try:
alert($('<li>Some text...</li>').text());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: drupal form to calculate date I need a function to be able to retrieve the selected date from a date_popup in drupal form this is my form and the code that i've tried,Im doing a form for pregnancy calculator and im new in drupal i need to know how to implement the date calculation in my form.As testing i written a function to read value selected but it's giving me the 1970-01-01 date
<?php
/*
*Implementing hook_menu
*/
function Pregnancy_menu() {
$items['form/Pregnancy'] = array(
'title' => 'Pregnancy Calculator',
'page callback' => 'drupal_get_form',
'page arguments' => array('Pregnancy_form'),
'access callback' => TRUE,
);
return $items;
}
function Pregnancy_form($form_type) {
$form['Pregnancy_Period'] = array(
'#type' => 'date_popup',
'#title' => 'Date of your last menstrual period',
'#date_format' => 'Y-m-d',
'#date_text_parts' => array('year'),
'#date_increment' => 30,
'#date_year_range' => '-1:0',
'#default_value' => date(Y) . date(M) . date(D),
);
$form['Calculate_Forward'] = array(
'#type' => 'submit',
'#value' => t('Calculate Forward'),
);
$form['Reset_form'] = array(
'#type' => 'submit',
'#value' => t('Reset this Form'),
);
$form['Conception_result'] = array(
'#type' => 'textfield',
'#title' => t('Conception Occurred:(about two weeks after last menstrual period)'),
'#prefix' => '<div style="float:left;">',
'#suffix' => '</div>',
);
$form['First_trimester_Ends'] = array(
'#type' => 'textfield',
'#title' => t('First Trimester Ends :(12 weeks)'),
'#prefix' => '<div style="float:left;">',
'#suffix' => '</div>',
);
$form['Second_trimester_Ends'] = array(
'#type' => 'textfield',
'#title' => t('Second Trimester Ends :(27 weeks)'),
'#prefix' => '<div style="float:left;">',
'#suffix' => '</div>',
);
$form['Due_Date'] = array(
'#type' => 'date_popup',
'#title' => 'Estimated Due Date (40 weeks)',
'#date_format' => 'Y-m-d',
'#date_text_parts' => array('year'),
'#description' => t('Plus or Minus 2 weeks'),
'#date_increment' => 30,
'#date_year_range' => '+1:+1',
'#default_value' => date(Y) . date(M) . date(D),
);
$form['Calculate_Backward'] = array(
'#type' => 'submit',
'#value' => t('Calculate Backward'),
);
return $form;
}
function Pregnancy_form_submit($form, &$form_state) {
//what should I write here to get the value of the selected date and to add on it a specific time.For testing im using:
$selected_time= $_POST[''Pregnancy_Period'];
$output=$selected_time;
drupal_set_message($output);//but it's showing 1970-01-01
}
A: You don't want to access $_POST variables directly when using Drupal's form API, instead use the $form_state variable, specifically the values key.
In your submit function, $form_state['values']['Due_Date'] will contain the value inputted in the text box, $form_state['values']['Second_trimester_Ends'] will contain the input for that field, and so on.
To get the individual date parts you can use:
list($year, $month, $day) = explode('-', $form_state['values']['Due_Date']);
To add an amount of time to that value use a combination of strtotime and mktime:
// Prepare a timestamp based on the received date at 00:00:00 hours
$date = mktime(0, 0, 0, $month, $day, $year);
$new_date = strtotime('+2 hours', $date);
$new_date_formatted = date('Y-m-d', $new_date);
There are lots of options for the strtotime function, just have a look a the documentation page linked above.
Hope that helps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ' Div Wrapper ' Issue I am wanting to wrap all my content within a div wrapper. I want my content to be wrapped within a div wrapper that's width is 1040px. The problem is, I want the navigation bar to have a with of 100% so that it spans ones screen/ full resolution. By the way, the navigatioon bar will be below the header.
Any suggestions?
Thank you
A: here is solution http://jsfiddle.net/YeruE/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to assign tasks in Bugzilla? i intend to use bugzilla eclipse plugin for collaborating in my project
we are a team working together in one project
and i was wondering how can i assign task to another colleague in the project using bugzilla
please guide me since, tutorials are very brief.
A: Browse to the issue, type in your colleague's email in the Assignee field, click Save Changes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: File IO on a remote Windows system Given a Perl script that can be running on unix or Windows, how can I best read/write to a file on a windows host? Is there anything similar to File::Remote?
A: I would try to mount the remote folder and then use the standard perl functions:
use constant W_REMOTE_FOLDER = '\\server\share';
use constant W_LOCAL_FOLDER = 'x:\share\';
use constant L_REMOTE_FOLDER = 'smb://server/share';
use constant L_LOCAL_FOLDER = '/mnt/share/';
my $localfolder = '';
if ($am_i_windows)
{
system('net use ...');
$localfolder = W_LOCAL_FOLDER;
}
if ($am_i_linux)
{
system('mount ...');
$localfolder = L_LOCAL_FOLDER;
}
die "What am I? if ($localfolder eq '');
open(HANDLE, "$localfolder/$filename");
# read/write (...)
close(HANDLE);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: NSPredicate compare with Integer How can I compare two NSNumbers or a NSNumber and an Integer in an NSPredicate?
I tried:
NSNumber *stdUserNumber = [NSNumber numberWithInteger:[[NSUserDefaults standardUserDefaults] integerForKey:@"standardUser"]];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"userID == %@", stdUserNumber];
Well, this doesn't work ... anyone has an idea how to do it?
I'm sure it's pretty easy but I wasn't able to find anything ...
A: If you are using predicateWithSubstitutionVariables: and value you want to predicate is NSNumber with integer value then you need to use NSNumber in predicate instead of NSString as substitution value. Take a look at example:
NSPredicate *genrePredicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"genreID == $GENRE_ID"]]; //if we make only one NSPredicate if would look something like this: [NSPredicate predicateWithFormat:@"genreID == %d", [someString integerValue]];
NSPredicate *localPredicate = nil;
for(NSDictionary *genre in genresArray){
localPredicate = [genrePredicate predicateWithSubstitutionVariables:@{@"GENRE_ID" : [NSNumber numberWithInteger:[genre[@"genre_id"] integerValue]]}];
}
A: NSNumber is an object type. Unlike NSString, the actual value of NSNumber is not substitued when used with %@ format. You have to get the actual value using the predefined methods, like intValue which returns the integer value. And use the format substituer as %d as we are going to substitute an integer value.
The predicate should be,
predicateWithFormat:@"userID == %d", [stdUserNumber intValue]];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
} |
Q: Help with nth-child(), selecting all children I might have missed something completely stupid, but I can't figure this out.
I am working on some simple jquery practice and was looking to select the specified children from an aside element to get the width. However, when I would select it, the return value was null. So I tried a few things, and I switch nth child value to 2 and the method to html() to see if that would do anything and yes infact, when I use nth-child(2) it selects all children in the aside element.
Javascript:
var modOneWidth = $('aside:nth-child(1)').width();
console.log(modOneWidth); //returns null
var modOneWidth = $('aside:nth-child(2)').html();
console.log(modOneWidth); //returns html of all children in aside
Aside Element and it's children (which are placed in a <section> element):
<aside>
<article>
<h2>Module 1</h2>
<p>ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</article>
<article>
<h2>Module 2</h2>
<p>riosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur</p>
</article>
<article>
<h2>Module 3</h2>
<p>ipsum dolor sit arud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat.</p>
</article>
</aside>
Again, can't figure out what I'm doing wrong, can it be HTML5 elements? Any help would be greatly appreciated. Thanks a lot
A: You're applying the :nth-child() selector to the <aside> elements, so your selector ends up matching the <aside> element which is the nth child of its parent.
You should match the <article> elements instead:
var modOneWidth = $("aside article:nth-child(1)").width();
A: try
$('aside').children('article:eq(0)').html();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: validation error - Google +1 button I'm trying to remove the counter from the google +1 button, but am getting this result:
there is no attribute "g:plusone:count"
Here is the code:
<div id="add" class="addthis_toolbox addthis_default_style addthis_32x32_style">
<a class="addthis_button" href="http://www.addthis.com/bookmark.php">
<img src="/images/add.jpg" width="32" height="32" alt="Share" /></a>
<a class="addthis_button_preferred_1"></a>
<a class="addthis_button_preferred_2"></a>
<a class="addthis_button_preferred_3"></a>
<a class="addthis_button_google_plusone" g:plusone:count="false"></a>
</div>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-4d766a8d31dffc91"></script>
<script type="text/javascript">
var addthis_config = {
services_exclude: 'print'
}
</script>
Anyone know how I can keep the counter off and still validate in xhtml strict?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JQuery UI Dialog Issue with Multiple Dialogs I have several dialogs (jquery-ui-ified), they all look something like this:
$('#options_dlg').dialog({
modal:true,
stack:true,
autoOpen:false,
resizable:false,
title:'Options',
height:620,
width:520,
zIndex:20000
});
The issue I am experiencing is that when i have a dialog open, and then I open another dialog, or close another dialog, it re-positions the first dialog - sometimes moving it so I can no longer access the title-bar to move it around.
There are of course numerous things going on in the script that may be the culprit - although nothing that is obvious to me -- meaning, I have no code that specifies that by opening or closing a dialog, than it should relocate any other dialogs.
So my question is, has anyone experienced this before in any capacity, and/or does anyone have any insight as to what could cause this to happen -- anything at all I can use to begin tracking down the culprit would be helpful.
Thanks -
A: I did have similar issues in and only in IE with jquery-ui 1.8.16. It looks like a known issue and I used the following method
$dialog.parent().css({position:"fixed"}).end().dialog('open');
from this solution and solved it. You might have a try, too.
A: Try setting the position of the dialog box when you open it.
$('#options_dlg').dialog({
modal:true,
stack:true,
autoOpen:false,
resizable:false,
title:'Options',
position: [x,y],
height:620,
width:520,
zIndex:20000
});
And before you set up the dialog, initialize x and y to be offsets depending on where you want the dialog to appear.
For example:
x = $(cell).offset().left + $(cell).outerWidth();
y = $(cell).offset().top - $(document).scrollTop();
You'll have to figure out how to determine the x and y offsets for your application, but that should fix the dialog position so that it does not move randomly when other dialogs are used.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Print various conformation of string in 2-D array I am presently trying to code a protein folding project in c.
Where I will be given a 3-4 length string lets say BWB or BBWW…
I have to store this string in 2-D array and print all possible combinations with this string.
if the length of the string is n the length of the matrix is 2n. and I am storing the 1st element at the center of the array.
What I have tried so far is as follows-
I am able to print the number of conformation of a particular input-let's say for 3 letter string it ll generate 12 combinations..for 4 it ll generate 36 combinations..like this..
so my 1st letter ll be at center of the matrix, then second word can be at any position-top,left,right,down of this one..and depending on this second one third one can be at top,right,left or any 3 combinations…
in total i ll have 12 combinations..
I have tried many things till now …and whatever I tried is
#include<string.h>
#include<math.h>
#include<stdio.h>
main()
{
int n=3;
//printf("enter the number of inputs:\t");
//scanf("%d",&n);
int i=4;
int temp=pow((i-1),(n-2));
int comb=i*temp;
//printf("total number of combination is : %d",comb);
char str[3]="ABC";
int size=2*n;
int p;
char mat[size][size];
int j,k;
int a=size/2;
int b=size/2;
for(j=0;j<size;j++)
{
for(k=0;k<size;k++)
{
mat[j][k]='*';
}
}
mat[a][b]=str[0];
int q;
int r;
for(r=1;r<3;r++)
{
for(q=1;q<=4;q++)
{
switch(q)
{
case 1:a=a+1;
break;
case 2:a=a-1;
break;
case 3:b=b+1;
break;
case 4:b=b-1;
break;
}
mat[a][b]=str[r];
}
}
for(p=0;p<comb;p++)
{
for(j=0;j<size;j++)
{
for(k=0;k<size;k++)
{
printf("%c",mat[j][k]);
}
printf("\n");
}
printf("\n");
}
printf("total number of combination is : %d",comb);
}
Output I am getting is
******
******
******
***CC*
***C**
******
******
******
******
***CC*
***C**
******
******
******
******
***CC*
***C**
******
******
******
******
***CC*
***C**
******
******
******
******
***CC*
***C**
******
******
******
******
***CC*
***C**
******
******
******
******
***CC*
***C**
******
******
******
******
***CC*
***C**
******
******
******
******
***CC*
***C**
******
******
******
******
***CC*
***C**
******
******
******
******
***CC*
***C**
******
******
******
******
***CC*
***C**
******
total number of combination is : 12
Any Help will be appreciated!
A: You are filling in the array once, and then printing it 12 times. Presumably you want to fill it in 12 different ways and print each one.
Often, this type of problem is done with recursion:
*
*Place the current character of the string in a possible position, skipping the position if it is already filled.
*If this was the last character in the string, print out the array. Otherwise, recur on the next character.
*Remove the character that was just placed.
*go to 1
For the recurring function, you will probably want to pass in the current position in the array, and the next index in the string. Something like
void do_next(int i, int j, int str_index)
{
if(str_index >= strlen(str))
{
print_array();
return;
}
if(arr[i+1][j] == '*')
{
arr[i+1][j] = str[str_index];
do_next(i+1, j, str_index+1);
arr[i+1][j] = '*';
}
// three similar blocks for the other positions
// don't use "else". Each block should be executed once
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is c function prototype mismatch merely a warning please take a look at my codes below
#include <stdio.h>
void printOut()
{
static int i = 0;
if (i < 10)
{
printOut(i);
}
}
int main(int argc, char *argv[])
{
return 0;
}
i guess there should be an error due to my invoking the non-existed function prototype.Actually, the code compiles well with mingw5 compiler, which is weird for me, then i change to Borland Compiler, i get a warning message said that no printOut function prototype, is this only a warning ? What is more, the code executes well without any pop-up error windows.
A: In C, a function without any parameters can still take parameters.
That's why it compiles. The way to specify that it doesn't take any parameters is:
void printOut(void)
This is the proper way to do, but is less common especially for those from a C++ background.
A: Your program's behavior is undefined, because you define printOut() with no parameters, but you call it with one argument. You need to fix it. But you've written it in such a way that the compiler isn't required to diagnose the problem. (gcc, for example, doesn't warn about the parameter mismatch, even with -std=c99 -pedantic -Wall -Wextra -O3.)
The reasons for this are historical.
Pre-ANSI C (prior to 1989) didn't have prototypes; function declarations could not specify the expected type or number of arguments. Function definition, on the other hand, specified the function's parameters, but not in a way that the compiler could use to diagnose mismatched calls. For example, a function with one int parameter might be declared (say, in a header file) like this:
int plus_one();
and defined (say, in the corresponding .c file) like this:
int plus_one(n)
int n;
{
return n + 1;
}
The parameter information was buried inside the definition.
ANSI C added prototypes, so the above could written like this:
int plus_one(int n);
int plus_one(int n)
{
return n + 1;
}
But the language continued to support the old-style declarations and definitions, so as not to break existing code. Even the upcoming C201X standard still permits pre-ANSI function declarations and definitions, though they've been obsolescent for 22 years now.
In your definition:
void printOut()
{
...
}
you're using an old-style function definition. It says that printOut has no parameters -- but it doesn't let the compiler warn you if you call it incorrectly. Inside your function you call it with one argument. The behavior of this call is undefined. It could quietly ignore the extraneous argument -- or it could conceivably corrupt the stack and cause your program to die horribly. (The latter is unlikely; for historical reasons, most C calling conventions are tolerant of such errors.)
If you want your printOut() function to have no parameters and you want the compiler to complain if you call it incorrectly, define it as:
void printOut(void)
{
...
}
This is the one and only correct way to write it in C.
Of course if you simply make this change in your program and then add a call to printOut() in main(), you'll have an infinite recursive loop on your hands. You probably want printOUt() to take an int argument:
void printOut(int n)
{
...
}
As it happens, C++ has different rules. C++ was derived from C, but with less concern for backward compatibility. When Stroustrup added prototypes to C++, he dropped old-style declarations altogether. Since there was no need for a special-case void marker for parameterless functions, void printOut() in C++ says explicitly that printOut has no parameters, and a call with arguments is an error. C++ also permits void printOut(void) for compatibility with C, but that's probably not used very often (it's rarely useful to write code that's both valid C and valid C++.) C and C++ are two different languages; you should follow the rules for whichever language you're using.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7540341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.