text stringlengths 8 267k | meta dict |
|---|---|
Q: Change the wallpaper on all desktops in OS X 10.7 Lion? I would like to change the wallpaper of all desktops (formerly "spaces") on a screen. As of OS X 10.6 there is a category to NSWorkspace which allows the setting of the wallpaper, however, when I use this function only the wallpaper of the current desktop gets changed and all the other desktops remain unchanged.
I then looked at the desktop preferences plist and wrote a class that modifies it to reflect the changes I want (basically set a new image file path). After the new file was saved I sent the com.apple.desktop "BackgroundChanged" notification - Google if you don't know what I am talking about, this was how people changed wallpapers in pre 10.6 days. At first this didn't produce any result, so instead of "nil" as userInfo dictionary I sent the exact same userInfo dictionary along as Apple does when you change the wallpaper in your settings (subscribe to the notification in an app and change the wallpaper in the settings app and you will see what it looks like). Luck helped me here, when I sent the notification this way for some reason the Dock crashed and when it reloaded, it loaded the settings from the preferences file thus displaying my changes.
This works on 10.7.1, however, I would a) rather not have the bad user experience of the dock crashing and reloading, and b) use a path that is more or less guaranteed to work in future releases as well. Exploiting a bug doesn't seem like a stable path.
Any other ideas on how to change the wallpaper of all desktops? I am also unsure whether the current behaviour of the NSWorkspace wallpaper category is intended or a bug, however, judging from the behaviour of the wallpaper preferences pane it seems that the former is the case.
A: There is no api for setting the same wallpaper to all screens or all spaces, NSWorkspace setDesktopImageURL it is implemented as such that it only sets the wallpaper for the current space on the current screen, this is how System Preferences does it too.
Besides the volatile method of manually modifying the ~/Library/Preferences/com.apple.desktop.plist (format could change) and using notifications to reload it (crashes you experienced) what you can do is set the wallpaper to spaces as the user switches to it , e.g. look for NSWorkspaceActiveSpaceDidChangeNotification (if your application is not always running you could tell the user to switch to all spaces he wants the wallpaper to apply to) , arguably these methods are not ideal but at least they are not volatile.
-(void)setWallpaper
{
NSWorkspace *sws = [NSWorkspace sharedWorkspace];
NSURL *image = [NSURL fileURLWithPath:@"/Library/Desktop Pictures/Andromeda Galaxy.jpg"];
NSError *err = nil;
for (NSScreen *screen in [NSScreen screens]) {
NSDictionary *opt = [sws desktopImageOptionsForScreen:screen];
[sws setDesktopImageURL:image forScreen:screen options:opt error:&err];
if (err) {
NSLog(@"%@",[err localizedDescription]);
}else{
NSNumber *scr = [[screen deviceDescription] objectForKey:@"NSScreenNumber"];
NSLog(@"Set %@ for space %i on screen %@",[image path],[self spaceNumber],scr);
}
}
}
-(int)spaceNumber
{
CFArrayRef windowsInSpace = CGWindowListCopyWindowInfo(kCGWindowListOptionAll | kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
for (NSMutableDictionary *thisWindow in (NSArray *)windowsInSpace) {
if ([thisWindow objectForKey:(id)kCGWindowWorkspace]){
return [[thisWindow objectForKey:(id)kCGWindowWorkspace] intValue];
}
}
return -1;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Storing links in a session? I want to store links in a session or multiple sessions and I was wondering what would be the best way to do this..
I was thinking that I could use a for loop with sessions foreach session as $s .... But then I would need $session1, $session2, $session3, etc.
Thanks in advance,
--I'm a PHP noob.
A: You can store arrays in sessions:
$_SESSION['links'] = array('example.com', 'example2.com');
foreach ($_SESSION['links'] as $link) {
// Do something with $link
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: add a new line in svg, bug cannot see the line I want to add a new line into the svg
when, the add button is pressed, a new line should be added into the svg
I can sure the line is added in the elements, but why it is not displayed on the screen?
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#map
{
border:1px solid #000;
}
line
{
stroke:rgb(0,0,0);
stroke-width:3;
}
</style>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$("#add").click(function(){
var newLine=$('<line id="line2" x1="0" y1="0" x2="300" y2="300" />');
$("#map").append(newLine);
});
})
</script>
</head>
<body>
<h2 id="status">
0, 0
</h2>
<svg id="map" width="800" height="600" version="1.1" xmlns="http://www.w3.org/2000/svg">
<line id="line" x1="50" y1="0" x2="200" y2="300"/>
</svg>
<button id="add">add</button>
</body>
</html>
A: In order to add elements to an SVG object those elements have to be created in the SVG namespace. As jQuery doesn't allow you to do this at present (AFAIK) you can't use jQuery to create the element. This will work:
$("#add").click(function(){
var newLine = document.createElementNS('http://www.w3.org/2000/svg','line');
newLine.setAttribute('id','line2');
newLine.setAttribute('x1','0');
newLine.setAttribute('y1','0');
newLine.setAttribute('x2','300');
newLine.setAttribute('y2','300');
$("#map").append(newLine);
});
Here's a working example.
A: with little bit less code
$("#add").click(function(){
$(document.createElementNS('http://www.w3.org/2000/svg','line')).attr({
id:"line2",
x1:0,
y1:0,
x2:300,
y2:300
}).appendTo("#map");
});
A: I solved this by reading the svg elements innerHTML property
and then writing it back to the svg elements innerHTML property
This forces an element refresh.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Request for member variables is something not a structure Okay so I am creating a custom uitablviewcell in IB and the class I have created is called CustomCell
I have imported it in the header file and here is some code
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CustomCell";
CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (CustomCell *) currentObject;
break;
}
}
}
//errors start
cell.usernameText.text = [usernameArray objectAtIndex:[indexPath row]];
cell.regionText.text = [regionArray objectAtIndex:[indexPath row]];
cell.gamesText.text = [gamesArray objectAtIndex:[indexPath row]];
cell.infoText.text = [aboutArray objectAtIndex:[indexPath row]];
cell.concoleText.text = [concoleArray objectAtIndex:[indexPath row]];
cell.micText.text = [NSString stringWithFormat:@"Mic:%@",[MicArray objectAtIndex:[indexPath row]]];
cell.ageText.text = [ageArray objectAtIndex:[indexPath row]];
//till her
return cell;
}
why is there an error and what can i do to fix it.
A:
Do you have class for your CustomCell(UITableViewCell)
and have the member usernameText, regionText, gamesText, infoText, concoleText, micText, and ageText of your CustomCell ? If no then you will get a warning Request for member variables is something not a structure because these are not the member variable. If you have not created separate class file for that then you may call cell.textLabel.text = @"Welcome" textLabel is the member of UITableViewCell.
and you did not tell use what ERROR you were getting?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Mysql Server 5 vs 6 vs MariaDB Have a simple question here.
I've a database with around 1 billion records, a server with 200GB of ram to handle it.
What do you suggest for best performances? Mysql 5, Mysql 6 or MariaDB?
A: MariaDB 5.3 should give you the best performance:
*
*It uses the XtraDB (InnoDB improved) storage engine from Percona as
default.
*The optimizer is greatly improved to handle big data.
*Replication is a magnitude faster in MariaDB if you have lots of
concurrent updates to InnoDB.
See http://kb.askmonty.org/en/what-is-mariadb-53 for a list of features.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: IOS: statusbar problem In my app I have two file xib FirstViewController.xib, SecondViewCotroller.xib and classic MainWindow.xib; in all I set statusBar at "none"; but when I launch my app I ever see this statusbar, why? where is the problem?
A: I'm afraid you are setting the Status Bar to "None" under the "Simulated Metrics" section. The settings in this section are there to help you visually design your screens but they have no effect when the application runs.
You can set the status bar as hidden for real in your Info.plist:
<key>UIStatusBarHidden</key>
<true/>
In the XCode interface, this is done via Info.plist --> Add Row --> "Status bar is initially hidden" --> YES.
You can also change the visibility of the status bar in code via the statusBarHidden property and the setStatusBarHidden:withAnimation: method of the UIApplication class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Drupal 2-phase submission Using Drupal 6 I'm looking for a 2-phase submission:
*
*User fills form and push "Send"
*Form is visualized as read-only with button "Back" and "Confirm"
Is there a module for that ?
A: The CTools module is probably the closest, it has a helper API to create multistep forms. There's a tutorial here.
Other than that you would need to create you own multistep form
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Save function in tuple without executing I have a tuple like the following:
self.tagnames = (('string', self.do_anything()),)
It should execute a specific function if a string matches to another.
However, when I initialize self.tagnames, it seems to execute the function already.
How can I fix my issue without executing the function on startup?
A: self.tagnames = (('string', self.do_anything),)
The () is a function call. If you want to defer the call until later, and just include the function reference without the parens like so.
A: self.tagnames = (('string', self.do_anything),)
You invoke a function by using parens with an argument list:
len is a function, len(s) is invoking that function on the argument s. Simply using the function's name gets you the function. Leave off the parenthesized argument list, and you are no longer invoking the function.
A: You should just remove the parenthesis:
self.tagnames = (('string', self.do_anything),)
Clearly self.do_anything() calls the method immediately, instead self.do_anything returns what in Python is called a "bound method", i.e. it's a callable object to which you can pass just the parameters (if any) and that will result in calling the method on the specific instance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: MYSQL query issue with UPDATE I have this query:
UPDATE people
SET column1 = (
SELECT if(r.rand BETWEEN 103 AND 109, 110, r.rand)
FROM ( SELECT floor(8+rand()*113) rand ) r
)
However, it sets the SAME random number to every row. How can I change it in order to give a different value to every row?
A: It seems the problem comes from the subquery, if you could simplify your assignment like the following:
UPDATE people
SET column1 = floor(8+rand()*113)
It would work the way you expect: each row has assigned a different random number. However the subquery returns a single value that is assigned to all the rows.
I guess that if you can't simplify the logic to remove the scalar subquery, you may have to write a stored procedure or a short program to do what you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Parsing HTML and counting tags with C# Suppose I have a block of HTML in a string:
<div class="nav mainnavs">
<ul>
<li><a id="nav-questions" href="/questions">Questions</a></li>
<li><a id="nav-tags" href="/tags">Tags</a></li>
<li><a id="nav-users" href="/users">Users</a></li>
<li><a id="nav-badges" href="/badges">Badges</a></li>
<li><a id="nav-unanswered" href="/unanswered">Unanswered</a></li>
</ul>
</div>
How can I parse the HTML and count the number of instances of a specific type of tag, such as <div> or <li>?
A: You can use HtmlAgilityPack for this - the latest version supports Linq so this is straight-forward:
For a local html file:
HtmlDocument doc = new HtmlDocument();
doc.Load(@"test.html");
int liCount = doc.DocumentNode.Descendants("li").Count(); //returns 5
From the web:
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load("http://stackoverflow.com");
int liCount = doc.DocumentNode.Descendants("li").Count();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Wrap Extended Frame View in a Window I have an assignment from my university to continue a JAVA card project from the students from last semester, which happens to be sucked. Because we have to carry on with someones work instead ours..
So my first step is to make an window image icon and tray icon for the application`s window.
The thing is, this code below is based on extended FrameView instead of JWindow.
My idea is to wrap the extended FrameView up into a Window.
Can someone help me with that?
Thanks much I would appreciate that.
CODE:
public class DesktopApplication1View extends FrameView implements IProgressDialogObserver
{
//============================================================
// Fields
// ===========================================================
private Connection connection = new Connection();
private ProgressDialogUpdater pbu = ProgressDialogUpdater.getInstance();
private Vector<CourseFromCard> courseListFromCard = new Vector<CourseFromCard>();
private Vector<School> schoolList = new Vector<School>();
private Vector<CourseFromFile> courseList = new Vector<CourseFromFile>();
private int cardReaderRefreshHelper = 0;
private Student student = null;
JLabel jLabelBilkaImage = null;
final String ICON = new File("").getAbsolutePath() + System.getProperty("file.separator") + "src" + System.getProperty("file.separator") + "resources" + System.getProperty("file.separator") + "image" + System.getProperty("file.separator") + "BilKa_Icon_32.png";
final String PIC = new File("").getAbsolutePath() + System.getProperty("file.separator") + "src" + System.getProperty("file.separator") + "resources" + System.getProperty("file.separator") + "image" + System.getProperty("file.separator") + "BilKa_Icon_128.png";
private JLabel getJLabelBilkaImage() {
if (jLabelBilkaImage == null) {
Icon image = new ImageIcon(PIC);
jLabelBilkaImage = new JLabel(image);
jLabelBilkaImage.setName("jLabelBilkaImage");
}
return jLabelBilkaImage;
}
//============================================================
// Constructors
// ===========================================================
public DesktopApplication1View(SingleFrameApplication app)
{
super(app);
pbu.registriere(this);
app.getMainFrame().setIconImage(Toolkit.getDefaultToolkit().getImage("icon.png"));
initComponents();
refreshConnectionState();
readFilesFromLocalHDD();
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++)
{
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener()
{
public void propertyChange(java.beans.PropertyChangeEvent evt)
{
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName))
{
if (!busyIconTimer.isRunning())
{
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
}
else if ("done".equals(propertyName))
{
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
}
else if ("message".equals(propertyName))
{
String text = (String) (evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
}
else if ("progress".equals(propertyName))
{
int value = (Integer) (evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
}
.........
A: SingleFrameApplication provides the method getMainFrame(), which returns the JFrame used to display a particular view. The code you listed in your question is one such view. If you need to operate on the frame, it's probably better to do it in code subclassing SingleFrameApplication than the code you posted.
There's a tutorial on using the Swing Application Framework, which might provide more help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why is the complexity of computing the Fibonacci series 2^n and not n^2? I am trying to find complexity of Fibonacci series using a recursion tree and concluded height of tree = O(n) worst case, cost of each level = cn, hence complexity = n*n=n^2
How come it is O(2^n)?
A: Look at it like this. Assume the complexity of calculating F(k), the kth Fibonacci number, by recursion is at most 2^k for k <= n. This is our induction hypothesis. Then the complexity of calculating F(n + 1) by recursion is
F(n + 1) = F(n) + F(n - 1)
which has complexity 2^n + 2^(n - 1). Note that
2^n + 2^(n - 1) = 2 * 2^n / 2 + 2^n / 2 = 3 * 2^n / 2 <= 2 * 2^n = 2^(n + 1).
We have shown by induction that the claim that calculating F(k) by recursion is at most 2^k is correct.
A: You are correct that the depth of the tree is O(n), but you are not doing O(n) work at each level. At each level, you do O(1) work per recursive call, but each recursive call then contributes two new recursive calls, one at the level below it and one at the level two below it. This means that as you get further and further down the recursion tree, the number of calls per level grows exponentially.
Interestingly, you can actually establish the exact number of calls necessary to compute F(n) as 2F(n + 1) - 1, where F(n) is the nth Fibonacci number. We can prove this inductively. As a base case, to compute F(0) or F(1), we need to make exactly one call to the function, which terminates without making any new calls. Let's say that L(n) is the number of calls necessary to compute F(n). Then we have that
L(0) = 1 = 2*1 - 1 = 2F(1) - 1 = 2F(0 + 1) - 1
L(1) = 1 = 2*1 - 1 = 2F(2) - 1 = 2F(1 + 1) - 1
Now, for the inductive step, assume that for all n' < n, with n ≥ 2, that L(n') = 2F(n + 1) - 1. Then to compute F(n), we need to make 1 call to the initial function that computes F(n), which in turn fires off calls to F(n-2) and F(n-1). By the inductive hypothesis we know that F(n-1) and F(n-2) can be computed in L(n-1) and L(n-2) calls. Thus the total runtime is
1 + L(n - 1) + L(n - 2)
= 1 + 2F((n - 1) + 1) - 1 + 2F((n - 2) + 1) - 1
= 2F(n) + 2F(n - 1) - 1
= 2(F(n) + F(n - 1)) - 1
= 2(F(n + 1)) - 1
= 2F(n + 1) - 1
Which completes the induction.
At this point, you can use Binet's formula to show that
L(n) = 2(1/√5)(((1 + √5) / 2)n - ((1 - √5) / 2)n) - 1
And thus L(n) = O(((1 + √5) / 2)n). If we use the convention that
φ = (1 + √5) / 2 ≈ 1.6
We have that
L(n) = Θ(φn)
And since φ < 2, this is o(2n) (using little-o notation).
Interestingly, I've chosen the name L(n) for this series because this series is called the Leonardo numbers. In addition to its use here, it arises in the analysis of the smoothsort algorithm.
Hope this helps!
A: t(n)=t(n-1)+t(n-2)
which can be solved through tree method:
t(n-1) + t(n-2) 2^1=2
| |
t(n-2)+t(n-3) t(n-3)+t(n-4) 2^2=4
. . 2^3=8
. . .
. . .
similarly for the last level . . 2^n
it will make total time complexity=>2+4+8+.....2^n
after solving the above gp we will get time complexity as O(2^n)
A: The complexity of a naive recursive fibonacci is indeed 2ⁿ.
T(n) = T(n-1) + T(n-2) = T(n-2) + T(n-3) + T(n-3) + T(n-4) =
= T(n-3) + T(n-4) + T(n-4) + T(n-5) + T(n-4) + T(n-5) + T(n-5) + T(n-6) = ...
In each step you call T twice, thus will provide eventual asymptotic barrier of:
T(n) = 2⋅2⋅...⋅2 = 2ⁿ
bonus: The best theoretical implementation to fibonacci is actually a close formula, using the golden ratio:
Fib(n) = (φⁿ – (–φ)⁻ⁿ)/sqrt(5) [where φ is the golden ratio]
(However, it suffers from precision errors in real life due to floating point arithmetics, which are not exact)
A: The recursion tree for fib(n) would be something like :
n
/ \
n-1 n-2 --------- maximum 2^1 additions
/ \ / \
n-2 n-3 n-3 n-4 -------- maximum 2^2 additions
/ \
n-3 n-4 -------- maximum 2^3 additions
........
-------- maximum 2^(n-1) additions
*
*Using n-1 in 2^(n-1) since for fib(5) we will eventually go down to fib(1)
*Number of internal nodes = Number of leaves - 1 = 2^(n-1) - 1
*Number of additions = Number of internal nodes + Number of leaves = (2^1 + 2^2 + 2^3 + ...) + 2^(n-1)
*We can replace the number of internal nodes to 2^(n-1) - 1 because it will always be less than this value :
= 2^(n-1) - 1 + 2^(n-1)
~ 2^n
A: The complexity of Fibonacci series is O(F(k)), where F(k) is the kth Fibonacci number. This can be proved by induction. It is trivial for based case. And assume for all k<=n, the complexity of computing F(k) is c*F(k) + o(F(k)), then for k = n+1, the complexity of computing F(n+1) is c*F(n) + o(F(n)) + c*F(n-1) + o(F(n-1)) = c*(F(n) + F(n-1)) + o(F(n)) + o(F(n-1)) = O(F(n+1)).
A: The complexity of recursive Fibonacci series is 2^n:
This will be the Recurrence Relations for recursive Fibonacci
T(n)=T(n-1)+T(n-2) No of elements 2
Now on solving this relation using substitution method (substituting value of T(n-1) and T(n-2))
T(n)=T(n-2)+2*T(n-3)+T(n-4) No of elements 4=2^2
Again substituting values of above term we will get
T(n)=T(n-3)+3*T(n-4)+3*T(n-5)+T(n-6) No of elements 8=2^3
After solving it completely, we get
T(n)={T(n-k)+---------+---------}----------------------------->2^k eq(3)
This implies that maximum no of recursive calls at any level will be at most 2^n.
And for all the recursive calls in equation 3 is ϴ(1) so time complexity will be 2^n* ϴ(1)=2^n
A: The O(2^n) complexity of Fibonacci number calculation only applies to the recursion approach. With a few extra space, you can achieve a much better performance with O(n).
public static int fibonacci(int n) throws Exception {
if (n < 0)
throws new Exception("Can't be a negative integer")
if (n <= 1)
return n;
int s = 0, s1 = 0, s2 = 1;
for(int i= 2; i<=n; i++) {
s = s1 + s2;
s1 = s2;
s2 = s;
}
return s;
}
A: I cannot resist the temptation of connecting a linear time iterative algorithm for Fib to the exponential time recursive one: if one reads Jon Bentley's wonderful little book on "Writing Efficient Algorithms" I believe it is a simple case of "caching": whenever Fib(k) is calculated, store it in array FibCached[k]. Whenever Fib(j) is called, first check if it is cached in FibCached[j]; if yes, return the value; if not use recursion. (Look at the tree of calls now ...)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: Loading Xml file from Isolated Storage - Windows Phone 7 I'm trying to load xml data saved in the isolated storage, but I always get an error.
I use the following code to load xml data saved in the isolated storage
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
storage.CreateDirectory("Highscores");
using (var isoFileStream = new IsolatedStorageFileStream("Highscores\\scores.xml", FileMode.OpenOrCreate, storage))
{
using (XmlReader reader = XmlReader.Create(isoFileStream))
{
XDocument xml = XDocument.Load(reader);
int i = 0;
foreach (var score in xml.Root.Element("Highscores").Elements())
{
Count_to_10.Page2.Highscores.scores[i++] = score.Value.ToString();
}
}
}
But I get the following error
Root element is missing.
in this line
XDocument xml = XDocument.Load(reader);
The xml file is:
<HighscoreTable>
<Highscores length="25">
<score>00:00:09.000</score>
<score>00:00:07.000</score>
<score>00:00:02.000</score>
<score>00:00:04.000</score>
</Highscores>
</HighscoreTable>
I'd be glad if you'd help me find the source of the error.
A: What that error indicates to me is the XDocument.Load(reader); call is trying to read the file given and cannot find the file. Essentially your file was not ever saved to isolatedstorage in the first place or it was saved with a different path.
I was testing something for myself and I was able to duplicate your issue when I tried to read the wrong file path.
Try adding storage.FileExists("Highscores\\scores.xml") to make sure your file exists in isolatedstorage before you try to read it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: wp_nav_menu change sub-menu inline style? I am trying to modify sub-menus of a Wordpress site. Wordpress generates the following HTML code for the sub-menus
<ul class="sub-menu" style="top: 50px; visibility: visible; left: 0px; width: 202px; display: none;">
<li class="menuitem123 menu-item menu-item-type-post_type menu-item-object-page menu-item-123" id="menu-item-123"><a href="http://www.example.com" class="">Link Name</a></li>
<!-- other li elements follow -->
</ul>
Here's my invocation of the wp_nav_menu
<?php if(has_nav_menu('secondary')):?>
<?php wp_nav_menu( array( 'sort_column' => 'menu_order', 'menu_container' => 'div', 'container_id' => 'secondary-menu','menu_class' => '', 'theme_location' => 'secondary'));?>
<?php endif;?>
The problem is, I want to customize the inline style (or preferably move it out into a css file) that Wordpress is generating for the ul element, mainly the width. I have searched high and low but cannot find from where Wordpress is picking up the inline style and inserting it. I need to get rid of the inline style because I need to set different width for other sub-menus.
I could adapt the answer given on this wp_nav_menu change sub-menu class name? link which suggests sub classing the Wordpress Walker class.
Please can someone provide some pointers on what else should I be checking to see from where Wordpress is picking up the inline style?
Many thanks.
A: WordPress itself does not generate any inline styles, so most probably the deal is in your plugins or theme installed. According to your code, you do not use customized walkers, so the only deal may be in filters attached to standard Walker_Nav_Menu (see nav-menu-template.php file, at the beginning). Corresponding filters are most probably: nav_menu_css_class, nav_menu_item_id, walker_nav_menu_start_el.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Null pointer in C++ When in C++ I declare a null pointer to be int* p=0, does that mean the zero is some special constant of integer pointer type, or does it mean that p is pointing to address 0x0?
Of course for that 0x0 would have to be an special address to which C++ never touches during allocation of variables/arrays.
A: The C++ standard defines that the integer constant 0 converts to a null pointer. This does not mean that null pointers point to address 0x0. It just means that the text '0' turns into a null pointer when converted to a pointer.
Of course, making null pointers have a representation other than 0x0 is rather complicated, so most compilers just let 0x0 be the null pointer address and make sure nothing is ever allocated at zero.
Note that using this zero-conversion is considered bad style. Use NULL (which is a preprocessor macro defined as 0, 0L, or some other zero integral constant), or, if your compiler is new enough to support it, nullptr.
A: It means that an integral constant expression with value zero has a special meaning in C++; it is called a null pointer constant. when you use such an expression to initialize a pointer with, or to assign to a pointer, the implementation ensures that the pointer contains the appropriately typed null pointer value. This is guaranteed to be a different value to any pointer pointing at a genuine object. It may or may not have a representation that is "zero".
ISO/IEC 14882:2011 4.10 [conv.ptr] / 1:
A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type.
A: It's a special value, which by the standard is guaranteed to never be equal to a pointer that is pointing to an object or a function. The address-of operator & will never yield the null pointer, nor will any successful dynamic memory allocations. You should not think of it as address 0, but rather as special value that indicates that the pointer is pointing nowhere. There is a macro NULL for this purpose, and the new idiom is nullptr.
A: It means that it's not pointing to anything.
A: The value of the pointer is just 0. It doesn't necessarily mean it points to address 0x0. The NULL macro, is just a 0 constant.
A: the pointer points to address 0. On most platforms that is very special, but you should use NULL, because it is not always 0 (but very often).
A: Yes. Zero is a special constant. In fact, it's the only integral constant which can be used, without using explicit cast, in such statements:
int *pi = 0; //ok
char *pc = 0; //ok
void *pv = 0; //ok
A *pa = 0; //ok
All would compile fine.
However, if you use this instead:
int *pi = 1; //error
char *pc = 2; //error
void *pv = 3; //error
A *pa = 4; //error
All would give compilation error.
In C++11, you should use nullptr, instead of 0, when you mean null pointer.
A: In your example 'p' is the address of an int. By setting p to 0 you're saying there is an int at address 0. The convention is that 0 is the "not a valid address address", but its just a convention.
In pratice address 0 is generally "unmapped" (that is there is no memory backing that address), so you will get a fault at that address. That's not true in some embedded systems, though.
You could just as well pick any random address (e.g. 0xffff7777 or any other value) as the "null" address, but you would be bucking convention and confusing a lot of folks that read your code. Zero is generally used because most languages have support for testing is-zero is-not-zero efficiently.
See this related question: Why is address zero used for the null pointer?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to add manually a label with a text field inside a panel using Java I have a dialog and inside this dialog I have a list on the left and on the right I have a panel
I created these things using the gui builder of netbeans
now for the panel, I have 3 pairs of label - textfield
the problem is that depending on the user's input the pairs may become 4, or 5 etc
so I can't just draw these pairs using the gui builder, I need to create them by writing code
the question is, what kind of layout for this panel should I use in order to achieve this?
the panel is like that
label1 textfield
label2 textfield
label3 textfield
empty
empty
etc
here's a picture:
thanks
A: Personally I prefer a GroupLayout for such tasks.
GroupLayout layout = new GroupLayout(container);
container.setLayout(layout);
layout.setAutoCreateContainerGaps(true);
layout.setAutoCreateGaps(true);
Group groupLabels = layout.createParallelGroup();
Group groupFields = layout.createParallelGroup();
Group groupRows = layout.createSequentialGroup();
layout.setHorizontalGroup(layout.createSequentialGroup()
.addGroup(groupLabels)
.addGroup(groupFields));
layout.setVerticalGroup(groupRows);
for (int i = 0; i < 5; i++) {
JLabel label = new JLabel("ABCDEFGHIJ".substring(0, 2 + 2 * i));
JTextField field = new JTextField("ABCDEFGHIJ".substring(0, 2 + 2 * i));
groupLabels.addComponent(label);
groupFields.addComponent(field);
groupRows.addGroup(layout.createParallelGroup()
.addComponent(label)
.addComponent(field, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE));
}
If you want to dynamically add more rows the only thing you have to do is to add the corresponding components to the three groups and call validate on the container.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: vim xptemplate shortcut not working I have vim running on a remote server (connecting via the Terminal app on a Mac). It uses pathogen to manage plugins and has xptemplate installed.
Recently the that triggers xptemplate when you've inserted a keyword has stopped working. I can't think of anything I've changed.
If I do:
verbose imap <C-\>
it seems to be there:
i <C-\> * <C-R>=XPTemplateStart(0,{'k':'<C-\++'})<CR>
Last set from ~/.vim/bundle/xptemplate/plugin/xptemplate.conf.vim
Any suggestions how to further debug it?
Thanks.
A: have you tried following this "trouble shooting" to track the problem?:
https://github.com/drmingdrmer/xptemplate/wiki/FAQ
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Interact with webview from method outside OnCreate in android I have a question thta keeps occuring and i was wondering how to fix it. I want to be able to interact with views, in this case specifically the webview from outside the oncreate so that my methods can interact with the webview defined in the oncreate.
Here is an example of what im trying to do. In the search voice array im checked to see if the user said "go" and if they did i want either the go button to be pressed or to simply execute the code that the go button would do. I hope i explained this well enough, if you need clarification please let me know, thanks in advance!
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class web extends Activity {
static final int check = 111;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web);
final WebView webBrowser = (WebView) findViewById(R.id.webview);
webBrowser.setWebViewClient(new cpViewClient());
webBrowser.getSettings().setJavaScriptEnabled(true);
webBrowser.getSettings().setLoadWithOverviewMode(true);
webBrowser.getSettings().setUseWideViewPort(true);
webBrowser.loadUrl("http://www.google.com");
final InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
Button bGo = (Button) findViewById(R.id.go);
Button bBack = (Button) findViewById(R.id.back);
Button bForward = (Button) findViewById(R.id.forward);
Button bRefresh = (Button) findViewById(R.id.refresh);
Button bClearHistory = (Button) findViewById(R.id.clearhistory);
final EditText etUrl = (EditText) findViewById(R.id.url);
bGo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String enteredUrl = etUrl.getText().toString();
enteredUrl = enteredUrl.toLowerCase();
int len = enteredUrl.length();
/*
* if (enteredUrl.substring(0, 3).equals("www")) enteredUrl =
* "http://" + enteredUrl; else if (enteredUrl.substring(0,
* 11).equals("http://www.")) //Do nothing its perfect
* Log.d("URL", "The Url is fine"); else enteredUrl =
* "http://www." + enteredUrl;
*
* String dot1 = enteredUrl.substring(len-5, len-4); String dot2
* = enteredUrl.substring(len-4, len-3); if (!dot1.equals(".")
* || !dot2.equals(".")) enteredUrl = enteredUrl + ".com";
*/
if (enteredUrl.indexOf("http://") == -1
& enteredUrl.indexOf("www.") == -1) {
enteredUrl = "http://www." + enteredUrl;
} else if (enteredUrl.indexOf("http://") == -1) {
enteredUrl = "http://" + enteredUrl;
}
if (enteredUrl.indexOf(".com") == -1
& enteredUrl.indexOf(".org") == -1
& enteredUrl.indexOf(".net") == -1
& enteredUrl.indexOf(".mil") == -1
& enteredUrl.indexOf(".gov") == -1
& enteredUrl.indexOf(".edu") == -1
& enteredUrl.indexOf(".info") == -1) {
enteredUrl = enteredUrl + ".com";
}
webBrowser.loadUrl(enteredUrl);
etUrl.setText(enteredUrl);
imm.hideSoftInputFromWindow(etUrl.getWindowToken(), 0);
}
});
bBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (webBrowser.canGoBack())
webBrowser.goBack();
}
});
bForward.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (webBrowser.canGoForward())
webBrowser.goForward();
}
});
bRefresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
webBrowser.reload();
}
});
bClearHistory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
webBrowser.clearHistory();
}
});
Button VR = (Button) findViewById(R.id.webvoice);
VR.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getvoice();
}
});
}
public void getvoice() {
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
startActivityForResult(i, check);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == check && resultCode == RESULT_OK) {
result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
final TextView tvvoicearray = (TextView) findViewById(R.id.tvvoicearray);
tvvoicearray.setText(result.get(0));
searchvoicearray();
}
super.onActivityResult(requestCode, resultCode, data);
}
public void searchvoicearray() {
// Log.d("DEBUGGINGG",result.get(0));
// System.out.println(result);
int size = result.size();
int i = 0;
while (i < size) {
String s = result.get(i);
// next line removes all spaces in the string
// s= s.replaceAll(" ", "");
if (s.indexOf("go") != -1 ) {
i = size;
//i want the button go to be pressed or its action to be completed.
if (webBrowser.canGoBack())
webBrowser.goBack();
}
else if (s.indexOf("back") != -1) {
i = size;
if (webBrowser.canGoBack())
webBrowser.goBack();
}
else {
System.out.println(result.get(i) + " is not internet");
Log.d("DEBUGGINGG", result.get(i) + " is not internet");
// }
i++;
}
}
}
ArrayList<String> result = new ArrayList<String>();
}
A: Then, declare webview outside onCreate:
static final int check = 111;
private WebView webBrowser;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web);
webBrowser = (WebView) findViewById(R.id.webview);
A: You need to make the WebView a member of your web class and not variable that is local to the onCreate() method: To do this you simply move its declaration outside the method:
public class web extends Activity {
//Declare your member objects/variables here
static final int check = 111;
WebView webBrowser;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web);
webBrowser = (WebView) findViewById(R.id.webview);
...
}
...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to abort specific thread in task parallel library with C# I have this tricky task I've been trying to achieve for quiet sometime but till now I couldn't think of anything to make it work. anyway here is the scenario...
I have a winform application contains a listview and a button.
the listview contains 1 column which holds the data I need to pass to my functions later on. the column contains lets say 50 rows containing a list of links.
Now I have this function which I'm using to fetch and grab the contents of these links (5 links at a time) with parallel multithreaded mode using (Task Parallel Library):
//List<int> currentWorkingItem //contains the indices of the items in listview
//List<string> URLsList //contains the URLs of the items in listview
Parallel.ForEach(URLsList, new ParallelOptions() { MaxDegreeOfParallelism = 5 }, (url, i, j) =>
{
//show to user this link is currently being downloaded by highlighting the item to green...
this.BeginInvoke((Action)(delegate()
{
//current working item
mylistview.Items[currentWorkingItem[(int)j]].BackColor = green;
}));
//here I download the contents of every link in the list...
string HtmlResponse = GetPageResponse(url);
//do further processing....
});
Now the above code works perfectly... but sometimes I want the user to abort certain thread which is currently running and continue with the rest of the threads in the list... is that achievable in this? if so please help me out.. I'd really appreciate any solution or suggestions..
A: Try using Task library with cancellation tokens. I find it more elegant and safer approach to do your thing. Here is a quote good example of doing that:
using System;
using System.Threading.Tasks;
using System.Threading;
namespace CancelTask
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press 1 to cancel task");
var cTokenSource = new CancellationTokenSource();
// Create a cancellation token from CancellationTokenSource
var cToken = cTokenSource.Token;
// Create a task and pass the cancellation token
var t1 = Task<int>.Factory.StartNew(()
=> GenerateNumbers(cToken), cToken);
// to register a delegate for a callback when a
// cancellation request is made
cToken.Register(() => cancelNotification());
// If user presses 1, request cancellation.
if (Console.ReadKey().KeyChar == '1')
{
// cancelling task
cTokenSource.Cancel();
}
Console.ReadLine();
}
static int GenerateNumbers(CancellationToken ct)
{
int i;
for (i = 0; i < 10; i++)
{
Console.WriteLine("Method1 - Number: {0}", i);
Thread.Sleep(1000);
// poll the IsCancellationRequested property
// to check if cancellation was requested
if (ct.IsCancellationRequested)
{
break;
}
}
return i;
}
// Notify when task is cancelled
static void cancelNotification()
{
Console.WriteLine("Cancellation request made!!");
}
}
}
Original article could be found here: http://www.dotnetcurry.com/ShowArticle.aspx?ID=493
A: ok after struggling with this I finally found an efficient and an easy solution for this..
it required me only a hashtable which contains the indicies of the selected items in the listview and a simple bool value. the index is the key and the bool (true, false) is the value. the bool value is like an (on/off) switch indicates that the current loop is aborted or not.. so in order to abort specific thread simple I need to pass the key(the index) of the selected item on my listview to the foreach loop and check if the bool switch is on or off and that's basically it...
so my final code will be like this:
//I declared the hashtable outside the function so I can manage it from different source.
private Hashtable abortingItem;
Now when I click grab button it should fill the hashtable with the selected indicies...
abortingItem = new Hashtable();
for (int i = 0; i < myURLslist.SelectedItems.Count(); i++)
{
//false means don't abort this.. let it run
abortingItem.Add(myURLslist.SelectedItems[i].index, false);
}
//here should be the code of my thread to run the process of grabbing the URLs (the foreach loop)
//..........................
now if I need to abort specific item all I need is to select the item in the listview and click abort button
private void abort_Click(object sender, EventArgs e)
{
if (abortingItem != null)
{
for (int u = 0; u < myURLslist.SelectedIndices.Count; u++)
{
//true means abort this item
abortingItem[myURLslist.SelectedIndices[u]] = true;
}
}
}
In my foreach loop all I need is a simple if else statement to check if the bool is on or off:
//List<int> currentWorkingItem //contains the indices of the items in listview
//List<string> URLsList //contains the URLs of the items in listview
Parallel.ForEach(URLsList, new ParallelOptions() { MaxDegreeOfParallelism = 5 }, (url, i, j) =>
{
//aborting
if (!(bool)abortingItem[currentWorkingItem[(int)j]])
{
//show to user this link is currently being downloaded by highlighting the item to green...
this.BeginInvoke((Action)(delegate()
{
//current working item
mylistview.Items[currentWorkingItem[(int)j]].BackColor = green;
}));
//here I download the contents of every link in the list...
string HtmlResponse = GetPageResponse(url);
//do further processing....
}
else
{
//aborted
}
});
that's simply it..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: C++ header-implementation-header-implementation dependency chain I'm trying to create simple C++ incremental-build tool with dependency resolver.
I've been confused about one problem with cpp build process.
Imagine we have a library consists several files:
// h1.h
void H1();
// s1.cpp
#include "h1.h"
#include "h2.h"
void H1(){ H2(); }
// h2.h
void H2();
// s2.cpp
#include "h2.h"
#include "h3.h"
void H2(){ /*some implementation*/ }
void H3(){ /*some implementation*/ }
// h3.h
void H3();
When in client code including h1.h
// app1.cpp
#include "h1.h"
int main()
{
H1();
return 0;
}
there is implicit dependency of s2.cpp implementation:
our_src -> h3 -> s1 -> h2 -> s2. So we need to link with two obj files:
g++ -o app1 app1.o s1.o s2.o
In contrast when h3.h included
// app2.cpp
#include "h3.h"
int main()
{
H3();
return 0;
}
there is only one source dependency:
our_src -> h3 -> s2
So when we include h3.h we need only s2.cpp compiled (in spite of s1.cpp -> h2.h inclusion):
g++ -o app2 app2.o s2.o
This is very simple example of the problem, in real projects surely we may have several hundreds files and chains of inefficient includes may contain much more files.
So my question is: Is there a way or instruments to find out which header inclusion could be omitted when we check dependencies (without CPP parsing)?
I would appreciate for any responce.
A: In the case you stated to see the implicit dependence on s2.cpp you need to parse the implementation module s1.cpp because only there you will find that the s1 module is using s2. So to the question "can I solve this problem without parsing .cpp files" the answer is clearly a no.
By the way as far as the language is concerned there is no difference between what you can put in an header file or in an implementation file. The #include directive doesn't work at the C++ level, it's just a textual macro function without any understanding of the language.
Moreover even parsing "just" C++ declarations is a true nightmare (the difficult part of C++ syntax are the declarations, not the statements/expressions).
May be you can use the result of gccxml that parses C++ files and returns an XML data structure that can be inspected.
A: This is not an easy problem. Just a couple of many things that make this difficult:
*
*What if one header file is implemented in N>1 source files? For example, suppose class Foo is defined in foo.h but implemented in foo_cotr_dotr.cpp, foo_this_function.cpp, and foo_that_function.cpp.
*What if the same capability is implemented in multiple source files? For example, suppose Foo::bar() has implementations in foo_bar_linux.cpp, foo_bar_osx.cpp, foo_bar_sunos.cpp. The implemention to be used depends on the target platform.
One easy solution is to build a shared or dynamic library and link against that library. Let the toolchain resolve those dependencies. Problem #1 disappears entirely, and problem #2 does too if you have a smart enough makefile.
If you insist on bucking this easy solution you are going to need to do something to resolve those dependencies yourself. You can eliminate the above problems (not an exhaustive list) by a project rule one header file == one source file. I have seen such a rule, but not nearly as often as I've seen a project rule that says one function == one source file.
A: You may have a look at how I implemented Wand. It uses a directive to add dependencies for individual source files. The documentation is not fully completed yet, but there are examples of Wand directives in the source code of Gabi.
Examples
Thread class include file
Thread.h needs thread.o at link time
#ifdef __WAND__
dependency[thread.o]
target[name[thread.h] type[include]]
#endif
Thread class implementation on windows (thread-win32.cpp)
This file should only be compiled when Windows is the target platform
#ifdef __WAND__
target[name[thread.o] type[object] platform[;Windows]]
#endif
Thread class implementation on GNU/Linux (thread-linux.cpp)
This file should only be compiled when GNU/Linux is the target platform. On GNU/Linux, the external library pthread is needed when linking.
#ifdef __WAND__
target
[
name[thread.o] type[object] platform[;GNU/Linux]
dependency[pthread;external]
]
#endif
Pros and cons
Pros
*
*Wand can be extended to work for other programming languages
*Wand will save all necessary data needed to successfully link a new program by just giving the command wand
*The project file does not need to mention any dependencies since these are stored in the source files
Cons
*
*Wand requires extra directives in each source file
*The tool is not yet widely used by library writers
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Second jquery "chunk" not running I have the following jquery below. When the user clicks .commentCount, I want this div called #commentSec to open up, and then some other elements on the site change. This jquery chunk runs fine. However, the second chunk, onclick of a close button called .closeComments, doesn't run at all. What am I doing wrong? Do I have to return true or something in the first jquery section? Thanks--
$('.commentCount').click( function() {
$('#commentSec').css({ 'display' : 'inline', 'height' : 'auto', 'padding' : '10px', 'padding-bottom' : '0px', 'margin-bottom' : '10px', 'margin-left' : '10px', 'z-index' : '10'});
$('#commentSec h3').css({ 'display' : 'block'});
$('#rightcolumn').css({ 'opacity' : '.3'}); //Transparent rightcolumn
});
Second Chunk:
$('.closeComments').click( function() {
$('#commentSec').css({ 'display' : 'none'});
$(this).css({'opacity' : '.9'});
$('#rightcolumn').css({ 'opacity' : '1'}); //Undo transparent rightcolumn
});
HTML/PHP:
<h3><b>' . $useranswering . '\'s</b> ANSWER</h3><img class="closeComments" src="../Images/bigclose.png" alt="close"/>
<span><a class="prev" >← previous answer</a><a class="next" href="">next answer →</a></span>
<div>
<p>' . $answer . '</p>
<form method=post>
<input type="hidden" value="'. $ansid .'" name="answerid">
<textarea rows="2" cols="33" name="answercomment">Comment on this answer</textarea>
<input type="image" src="../Images/commentSubmit.png"/>
A: The third line of your Second Chunk:
$(this).css({'opacity' : '9'});
Should that not be:
$(this).css({'opacity' : '0'});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iPhone - Won’t save array to plist on iPhone I’m trying to save an array to a .plist file on my iphone but it won’t save to it. When i try it on the simulator it works. But when i run it on the iphone it doesn’t work. I check if the file exists on the device and it does and i can read the data from the file, but it won’t write to it. Here is the code when i add the data to the .plist file.
//Sorts the arrays
[self sortArrays];
NSString *sString = [[NSString alloc] initWithFormat:@"Schema%i", currentIndex];
NSString *daPath = [[NSBundle mainBundle] pathForResource:sString ofType:@"plist"];
NSLog(@"Path: %@", daPath);
//Checks if the file exists
BOOL exists;
NSFileManager *fileManager = [NSFileManager defaultManager];
exists = [fileManager fileExistsAtPath:daPath];
if(!exists)
NSLog(@"PATH %@ DOES NOT EXIST", daPath);
else
NSLog(@"PATH %@ DO EXIST!!", daPath);
//Writes out the array to check if it gots any elements
for (int i = 0; i < [itemsArray count]; i++)
NSLog(@"%i: %@", i, [(NSMutableArray*)[itemsArray objectAtIndex:i] objectAtIndex:0]);
//Writes the array to the .plist
[itemsArray writeToFile:daPath atomically:YES];
//Gets the .plist file
NSMutableArray *tmpA2 = [[NSMutableArray alloc] initWithContentsOfFile:daPath];
//Checks if the new elements that got added is there.
for (int i = 0; i < [tmpA2 count]; i++)
NSLog(@"FILE: %i: %@", i, [(NSMutableArray*)[tmpA2 objectAtIndex:i] objectAtIndex:0]);
[sString release];
[itemsArray release];
sString = nil;
itemsArray = nil;
Does anyone know why it doesn’t work?
A: You can not write into the app bundle, you need to write to the app's document directory.
NSString *fileName = @"fileName";
NSArray *searchPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectoryPath = [searchPath objectAtIndex:0];
NSString *filePath = [documentDirectoryPath stringByAppendingPathComponent:fileName];
If there is initial data in a file in the app bundle on startup copy it to the document directory if it does not exist and then it can be read, modified and written..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use CodeDOM's CodeMemberProperty to generate DebuggerStepThrough attribute for a property getter or setter How can I generate a DebuggerStepThroughAttribute over a getter/setter with CodeDOM?
This question follows from MSDN documentation and a question on StackOverflow.
A: CodeMemberProperty's CustomAttributes is of type CodeAttributeDeclarationCollection. If an Attribute is specified here, then it's added above the property declaration line: generated code won't compile.
CodeMemberProperty's GetStatements and SetStatements are collections: i cannot specify custom attributes on them.
Here's what I can see in Microsoft CSharpCodeGenerator with help from Reflector:
private void GenerateProperty(CodeMemberProperty e, CodeTypeDeclaration c)
{
if ((this.IsCurrentClass || this.IsCurrentStruct) || this.IsCurrentInterface)
{
if (e.CustomAttributes.Count > 0)
{
this.GenerateAttributes(e.CustomAttributes);
}
if (!this.IsCurrentInterface)
{
if (e.PrivateImplementationType == null)
{
this.OutputMemberAccessModifier(e.Attributes);
this.OutputVTableModifier(e.Attributes);
this.OutputMemberScopeModifier(e.Attributes);
}
}
else
{
this.OutputVTableModifier(e.Attributes);
}
this.OutputType(e.Type);
this.Output.Write(" ");
if ((e.PrivateImplementationType != null) && !this.IsCurrentInterface)
{
this.Output.Write(this.GetBaseTypeOutput(e.PrivateImplementationType));
this.Output.Write(".");
}
if ((e.Parameters.Count > 0) && (string.Compare(e.Name, "Item", StringComparison.OrdinalIgnoreCase) == 0))
{
this.Output.Write("this[");
this.OutputParameters(e.Parameters);
this.Output.Write("]");
}
else
{
this.OutputIdentifier(e.Name);
}
this.OutputStartingBrace();
this.Indent++;
if (e.HasGet)
{
if (this.IsCurrentInterface || ((e.Attributes & MemberAttributes.ScopeMask) == MemberAttributes.Abstract))
{
this.Output.WriteLine("get;");
}
else
{
this.Output.Write("get");
this.OutputStartingBrace();
this.Indent++;
this.GenerateStatements(e.GetStatements);
this.Indent--;
this.Output.WriteLine("}");
}
}
if (e.HasSet)
{
if (this.IsCurrentInterface || ((e.Attributes & MemberAttributes.ScopeMask) == MemberAttributes.Abstract))
{
this.Output.WriteLine("set;");
}
else
{
this.Output.Write("set");
this.OutputStartingBrace();
this.Indent++;
this.GenerateStatements(e.SetStatements);
this.Indent--;
this.Output.WriteLine("}");
}
}
this.Indent--;
this.Output.WriteLine("}");
}
}
Carefully examining lines around if (e.HasGet), it seems impossible.
A: I don't think you can. The CodeDom namespace has been abandoned by Microsoft in favor of T4 code generation technology.
It has been a few years since anything new has been added there. I'm quite sure that the last addition was in .NET 2.0. And after that, not a thing.
So, if you're creating anything new that generates code, move to the T4.
A: Here is a LinqPad snippet that demonstrates how to do this. It is a major hack, since, as GregC's answer shows, it isn't possible using the structured Dom Classes. It basically generates the property, then edits the string to insert the attributes.
void Main()
{
Sample sample = new Sample();
sample.AddFields();
sample.AddProperties();
sample.AddMethod();
sample.AddConstructor();
sample.AddEntryPoint();
sample.GenerateCSharpCode();
}
public class Sample{
/// <summary>
/// Define the compile unit to use for code generation.
/// </summary>
CodeCompileUnit targetUnit;
/// <summary>
/// The only class in the compile unit. This class contains 2 fields,
/// 3 properties, a constructor, an entry point, and 1 simple method.
/// </summary>
CodeTypeDeclaration targetClass;
/// <summary>
/// The name of the file to contain the source code.
/// </summary>
private const string outputFileName = "SampleCode.cs";
/// <summary>
/// Define the class.
/// </summary>
public Sample()
{
targetUnit = new CodeCompileUnit();
CodeNamespace samples = new CodeNamespace("CodeDOMSample");
samples.Imports.Add(new CodeNamespaceImport("System"));
targetClass = new CodeTypeDeclaration("CodeDOMCreatedClass");
targetClass.IsClass = true;
targetClass.TypeAttributes =
TypeAttributes.Public | TypeAttributes.Sealed;
samples.Types.Add(targetClass);
targetUnit.Namespaces.Add(samples);
}
/// <summary>
/// Adds two fields to the class.
/// </summary>
public void AddFields()
{
// Declare the widthValue field.
CodeMemberField widthValueField = new CodeMemberField();
widthValueField.Attributes = MemberAttributes.Private;
widthValueField.Name = "widthValue";
widthValueField.Type = new CodeTypeReference(typeof(System.Double));
widthValueField.Comments.Add(new CodeCommentStatement(
"The width of the object."));
targetClass.Members.Add(widthValueField);
// Declare the heightValue field
CodeMemberField heightValueField = new CodeMemberField();
heightValueField.Attributes = MemberAttributes.Private;
heightValueField.Name = "heightValue";
heightValueField.Type =
new CodeTypeReference(typeof(System.Double));
heightValueField.Comments.Add(new CodeCommentStatement(
"The height of the object."));
targetClass.Members.Add(heightValueField);
}
/// <summary>
/// Add three properties to the class.
/// </summary>
public void AddProperties()
{
// Declare the read-only Width property.
CodeMemberProperty widthProperty = new CodeMemberProperty();
widthProperty.Attributes =
MemberAttributes.Public | MemberAttributes.Final;
widthProperty.Name = "Width";
widthProperty.HasGet = true;
widthProperty.HasSet = true;
widthProperty.Type = new CodeTypeReference(typeof(System.Double));
widthProperty.Comments.Add(new CodeCommentStatement(
"The Width property for the object."));
widthProperty.GetStatements.Add(new CodeMethodReturnStatement(
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), "widthValue")));
widthProperty.SetStatements.Add(new CodeMethodReturnStatement(
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), "widthValue")));
targetClass.Members.Add(widthProperty);
// Declare the read-only Height property.
CodeMemberProperty heightProperty = new CodeMemberProperty();
heightProperty.Attributes =
MemberAttributes.Public | MemberAttributes.Final;
heightProperty.Name = "Height";
heightProperty.HasGet = true;
heightProperty.Type = new CodeTypeReference(typeof(System.Double));
heightProperty.Comments.Add(new CodeCommentStatement(
"The Height property for the object."));
heightProperty.GetStatements.Add(new CodeMethodReturnStatement(
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), "heightValue")));
targetClass.Members.Add(heightProperty);
// Declare the read only Area property.
CodeMemberProperty areaProperty = new CodeMemberProperty();
areaProperty.Attributes =
MemberAttributes.Public | MemberAttributes.Final;
areaProperty.Name = "Area";
areaProperty.HasGet = true;
areaProperty.Type = new CodeTypeReference(typeof(System.Double));
areaProperty.Comments.Add(new CodeCommentStatement(
"The Area property for the object."));
// Create an expression to calculate the area for the get accessor
// of the Area property.
CodeBinaryOperatorExpression areaExpression =
new CodeBinaryOperatorExpression(
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), "widthValue"),
CodeBinaryOperatorType.Multiply,
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), "heightValue"));
areaProperty.GetStatements.Add(
new CodeMethodReturnStatement(areaExpression));
targetClass.Members.Add(areaProperty);
}
/// <summary>
/// Adds a method to the class. This method multiplies values stored
/// in both fields.
/// </summary>
public void AddMethod()
{
// Declaring a ToString method
CodeMemberMethod toStringMethod = new CodeMemberMethod();
toStringMethod.Attributes =
MemberAttributes.Public | MemberAttributes.Override;
toStringMethod.Name = "ToString";
toStringMethod.ReturnType =
new CodeTypeReference(typeof(System.String));
CodeFieldReferenceExpression widthReference =
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), "Width");
CodeFieldReferenceExpression heightReference =
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), "Height");
CodeFieldReferenceExpression areaReference =
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), "Area");
// Declaring a return statement for method ToString.
CodeMethodReturnStatement returnStatement =
new CodeMethodReturnStatement();
// This statement returns a string representation of the width,
// height, and area.
string formattedOutput = "The object:" + Environment.NewLine +
" width = {0}," + Environment.NewLine +
" height = {1}," + Environment.NewLine +
" area = {2}";
returnStatement.Expression =
new CodeMethodInvokeExpression(
new CodeTypeReferenceExpression("System.String"), "Format",
new CodePrimitiveExpression(formattedOutput),
widthReference, heightReference, areaReference);
toStringMethod.Statements.Add(returnStatement);
targetClass.Members.Add(toStringMethod);
}
/// <summary>
/// Add a constructor to the class.
/// </summary>
public void AddConstructor()
{
// Declare the constructor
CodeConstructor constructor = new CodeConstructor();
constructor.Attributes =
MemberAttributes.Public | MemberAttributes.Final;
// Add parameters.
constructor.Parameters.Add(new CodeParameterDeclarationExpression(
typeof(System.Double), "width"));
constructor.Parameters.Add(new CodeParameterDeclarationExpression(
typeof(System.Double), "height"));
// Add field initialization logic
CodeFieldReferenceExpression widthReference =
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), "widthValue");
constructor.Statements.Add(new CodeAssignStatement(widthReference,
new CodeArgumentReferenceExpression("width")));
CodeFieldReferenceExpression heightReference =
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), "heightValue");
constructor.Statements.Add(new CodeAssignStatement(heightReference,
new CodeArgumentReferenceExpression("height")));
targetClass.Members.Add(constructor);
}
/// <summary>
/// Add an entry point to the class.
/// </summary>
public void AddEntryPoint()
{
CodeEntryPointMethod start = new CodeEntryPointMethod();
CodeObjectCreateExpression objectCreate =
new CodeObjectCreateExpression(
new CodeTypeReference("CodeDOMCreatedClass"),
new CodePrimitiveExpression(5.3),
new CodePrimitiveExpression(6.9));
// Add the statement:
// "CodeDOMCreatedClass testClass =
// new CodeDOMCreatedClass(5.3, 6.9);"
start.Statements.Add(new CodeVariableDeclarationStatement(
new CodeTypeReference("CodeDOMCreatedClass"), "testClass",
objectCreate));
// Creat the expression:
// "testClass.ToString()"
CodeMethodInvokeExpression toStringInvoke =
new CodeMethodInvokeExpression(
new CodeVariableReferenceExpression("testClass"), "ToString");
// Add a System.Console.WriteLine statement with the previous
// expression as a parameter.
start.Statements.Add(new CodeMethodInvokeExpression(
new CodeTypeReferenceExpression("System.Console"),
"WriteLine", toStringInvoke));
targetClass.Members.Add(start);
}
/// <summary>
/// Generate CSharp source code from the compile unit.
/// </summary>
/// <param name="filename">Output file name</param>
public void GenerateCSharpCode()
{
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
var options = new CodeGeneratorOptions(){
BracingStyle = "C",
IndentString = "\t", BlankLinesBetweenMembers = true};
using (var sourceWriter = new StringWriter())
{
foreach(CodeNamespace @namespace in targetUnit.Namespaces){
foreach(CodeTypeDeclaration type in @namespace.Types){
var items = new List<CodeTypeMember>();
foreach(CodeTypeMember codeMember in type.Members){
var property = codeMember as CodeMemberProperty;
if(property == null){
items.Add(codeMember);
continue;}
items.Add(new CodeSnippetTypeMember(GetPropertyTextWithGetSetLevelDebuggerNonUserCodeAttribute(provider, options, sourceWriter, property)));
}
type.Members.Clear();
type.Members.AddRange(items.ToArray());
}
}
}
using (StringWriter sourceWriter = new StringWriter())
{
provider.GenerateCodeFromCompileUnit(
targetUnit, sourceWriter, options);
sourceWriter.ToString().Dump();
}
}
private static string GetPropertyTextWithGetSetLevelDebuggerNonUserCodeAttribute(CodeDomProvider provider, CodeGeneratorOptions options, StringWriter sourceWriter, CodeMemberProperty property)
{
provider.GenerateCodeFromMember(property, sourceWriter, options);
var code = sourceWriter.ToString();
sourceWriter.GetStringBuilder().Clear();
var lines = code.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
lines.RemoveAt(0);
lines.RemoveAt(lines.Count -1);
for (var i = lines.Count() - 1; i >= 0; i--)
{
var line = lines[i];
lines[i] = "\t\t\t" + line;
if (line.TrimStart() == "get" || line.TrimStart() == "set")
{
//Insert attribute above
lines.Insert(i, "\t\t\t[System.Diagnostics.DebuggerNonUserCode()]");
}
}
return String.Join(Environment.NewLine, lines.ToArray());
}
// Define other methods and classes here
}
It generates this class:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CodeDOMSample
{
using System;
public sealed class CodeDOMCreatedClass
{
// The width of the object.
private double widthValue;
// The height of the object.
private double heightValue;
// The Width property for the object.
public double Width
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.widthValue;
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
return this.widthValue;
}
}
// The Height property for the object.
public double Height
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.heightValue;
}
}
// The Area property for the object.
public double Area
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return (this.widthValue * this.heightValue);
}
}
public CodeDOMCreatedClass(double width, double height)
{
this.widthValue = width;
this.heightValue = height;
}
public override string ToString()
{
return string.Format("The object:\r\n width = {0},\r\n height = {1},\r\n area = {2}", this.Width, this.Height, this.Area);
}
public static void Main()
{
CodeDOMCreatedClass testClass = new CodeDOMCreatedClass(5.3D, 6.9D);
System.Console.WriteLine(testClass.ToString());
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Changing MainWindow background color WPF I am trying to change the background color of the MainWindow using a dialogbox called EditColorDialog. The dialogbox can read the current background color of the main window just fine but I can't seem to get it to change that color.
public partial class EditColorDialog : Window
{
ColorDialog colorPicker = new ColorDialog(); //this is a colorpicker
MainWindow mw = new MainWindow();
public ColorDialog()
{
InitializeComponent();
rect.Fill = mw.background; //reads the color off the main window
}
private void rect_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
colorPicker.Owner = this;
if ((bool)colorPicker.ShowDialog())
{
//selects new color from colorpicker
rect.Fill = new SolidColorBrush(colorPicker.SelectedColor);
}
}
private void OkButton_Click(object sender, RoutedEventArgs e)
{
mw.background = rect.Fill;
this.Close();
}
}
I am using this property in the main window code
public Brush background
{
get { return main_window.Background; }
set { main_window.Background = value; }
}
A: You create a new MainWindow every time you create such a dialog. Not a good idea.
If anything you should set the Application.MainWindow on application startup. Then set the reference like this:
MainWindow mw = (MainWindow)Application.Current.MainWindow;
and just use nw.Background, that property of yours seems like a non-static wrapper for a static call. Doing it this way you already have the main window.
A: Why does you EditColorDialog contains another new MainWindow? I guess you want a reference to the existing MainWindow which opens the EditColorDialog not a new one.Also i guess thats what H.B. meant, is you have a property *b*ackground, but your MainWindow already contains a Property called *B*ackground notice the uppercase 'B'. When closing the Dialog you can now set the Background property in your passed MainWindow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: http.request listener I need my Play! application to accept http POST from other server.
Is there some simple way how to manage external http post, get data and sent response?
Some easy http request listener?
Thanks
A: You could say nearly ALL http requests come from a remote source, so this is how Play and all HTTP based containers works by default!
However, to offer some advice, as you are sharing data between servers, and not a client-browser, I would check out renderXml and renderJSON in your controllers to return data in a way that your server will expect (as it is unlikely to be expecting HTML content??).
A: I agree with Codemwnci - besides those tips you can take a look in the 'routes' file and mark your method to accept only POST:
POST /edit controllerName.methodName
A: Thanks for the Answers, once I have the routes, it is really easy to write controller:
public static void accept(){
InputStream inputStream = request.body;
...
String response = "cmd=asynch-no-trace";
renderText(response);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pascal insert user input to an array I am trying to get better at functional programming. As a start I am planning on trying out with couple of languages like Pascal, Scheme, ML etc. First I started with Pascal. I am trying to insert user input into a integer array in pascal and then get them reverse.
1 program ReverseList;
2
3 var
4 i: Integer;
5 k: Integer;
6 a: array[1..100] of Integer;
7 begin
8 i := 0;
9 repeat
10 writeln('Enter a number');
11 readln(k);
12 if k > -1 then
13 i := i + 1;
14 a[i] := k;
15 until(k < 0);
16 for i := 1 to i do
17 writeln(a[i]);
18 end.
In past I have mostly been a java developer so I was so custom to using all the lists thats available. Also ideally I was wondering if I can build a list where I can iterate over the list based on the number of elements in that list.
It would be great if anyone could point me on the direction of good tutorials in functional programming as well as syntax on above mentioned programming languages.
A: There are several problems with your program:
*
*The array is not initialized.
*There is no input checking, both i=0 and i>100 result in an illegal array index.
*The array index and the value are the same, is that correct?
*You only write the first 10 numbers (but you use a different index, which is certain to be out of range).
*The output is not in reverse.
There are also several pascal tutorials.
By the way, Pascal isn't a functional language. So if you really want to learn a functional language, you better try another one (like Lisp, Ml or probably F#).
A: It was a good practice and I managed to figure a solution for this. I am sure there are better ways to do, and also this doesn't look like I am using the functionalities of functional programming. But if anyone wants to provide a better solution please do so,
{author: Null-Hypothesis}
program ReverseList;
var
i: Integer; {integer to keep the array length}
k: Integer; {user input value}
a: array[1..100] of Integer; {array to store the user inputs}
begin
i := 0;
repeat {iterate until user input is negative or number of inputs exceed array size}
writeln('Enter a number or enter negative value to exit the program.');
readln(k);
if(k > -1) and (i < 100) then {check for negative value and size of the array}
begin
i := i + 1; {increase array index}
a[i] := k {assign value to array}
end
else
break; {exit if array size exceed the limit of array}
until(k < 0);
writeln;
{Printing the user input before the reversing the list}
writeln('Original order of the list');
for i := 1 to i do
writeln(a[i]);
writeln;
{Printing the reverse list}
writeln('Reversed List');
for i := i downto 1 do {decrement array index}
writeln(a[i]);
writeln('Bye!!!');
end.
Happy Coding, off to the next language...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: why does my application work differently when running as administrator? I have a small Delphi application that writes a key to the LOCAL_MACHINE registry.
When I run it on Windows 7 professional with user that has administrator privileges it fails to write the value, but when I right click and choose "Run as administrator" it does work.
The code is:
var
reg : TRegistry;
begin
Result := false;
reg := TRegistry.Create;
reg.RootKey := HKEY_LOCAL_MACHINE;
if (reg.OpenKey('Software\YepYep', TRUE)) then
Begin
try
reg.WriteString('ProductKey', Trim(ProductKey));
Result := true;
finally
reg.CloseKey();
end;
End;
reg.Free;
end;
The computer UAC settings are set to "Notify only when programs try to make changes to my computer" (second lowest level). When I take it down to "Never notify" it also works (with no need to use "Run as administrator").
If you have any ideas/thoughts about what could be the issue, I would appreciate hearing them.
Thanks.
A: Simply put, a user needs administrator rights to write to HKLM. Likewise for writing to system directories (system32, program files). This has always been true for Windows versions that implemented security (NT, 2k, XP, Vista, 7).
Under UAC, users in the administrators group run processes, by default, with a standard user token. So they do not get write access to HKLM etc.
You really need to read up on UAC before going much further. Start here.
Once you are familiar with the issues you have two principal options:
*
*Add a requireAdministrator manifest to your application so that it always runs with elevated privileges. This means that the user will have to negotiate the UAC dialog every time they start your application.
*Rework your application so that it does not write to HKLM. A common approach is to do everything that needs admin rights during installation which typically happens elevated. Another variant is to hive off the small part of your app that needs admin rights to a separate process so that you only present UAC dialogs when necessary.
Of these two options, number 2 is most definitely to be preferred. Bear in mind that your application already did not work on 2000/XP for non-administrator users.
A: Administrator accounts have limited access because of UAC - that is the design of Windows Vista and Windows 7. HKEY_LOCAL_MACHINE is a very protected space.
You can include a manifest to prompt when starting your application.
A: Starting from Vista, applications can no longer write to this part of the registry.
When writing to HKEY_LOCAL_MACHINE\Software your application needs elevated privileges.
To provide backwards XP compatibility they invented registry virtualization:
http://msdn.microsoft.com/en-us/library/aa965884
please read the ms page and you will understand why your application does not work when not running as administrator...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Rackspace CloudFiles C# API: How to list files on root 'folder', and how to list (sub)folders within a 'folder'? (1)
I can list the files on a folder this way:
var parameters = new Dictionary<GetListParameters, string>();
parameters.Add(GetListParameters.Path, "folder1/"); // get items from this specific path
var containerItemList = connection.GetContainerItemList(Settings.ContainerName, parameters);
However, this:
parameters.Add(GetListParameters.Path, "/");
or this:
parameters.Add(GetListParameters.Path, "");
does not work.
How can I query the files on the root folder?
(2)
The code above returns the list of files in a folder.
How can I get the list of folders within a folder? I there any parameter I can set to get this list?
Note: I know that this is a 'flat' file system, similar to Amazon S3. However, both (cloudfiles and S3) provides a way to work with 'folder'. In S3 is easy. In cloudfiles (with the .net API) I could not find how to do this.
Any hint will be highly appreciated.
A: This has just been fixed with the latest push and closes issue #51 on github
Link to downloadable package
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Restarting a job (upstart) in a php script I am currently writing the admin portal for my most recent project. I have been fighting with my computer to get upstart working, and now that it is, I wanted to be able to operate upstart from the web. I need to execute the following in my php script
sudo restart job
sudo start job
sudo stop job
as you can see sudo is the theme of those commands, so I need to somehow run sudo from this php script. How can I attack this problem, or is there a work around for this.
in case it matters:
# which start
/sbin/start
# which stop
/sbin/stop
# which restart
/sbin/restart
A: I see several approaches. You could certainly add www-data to the sudoers list, and then either hard-code www-data's password into your script (not so good) or read it from a file (a little better) to make sudo work. If you go this route, you'll probably need to manually override www-data's password, since it doesn't really have a usable password. Either of these approaches should be discouraged because www-data is deliberately stripped of most privileges as a security measure. Granting it a big one (like sudo) and putting its password in a file or script creates a significant security vulnerability.
You might be able to grant www-data very limited sudo privileges that enable the functionality you need without opening up too many security holes. Read up on sudo and the sudoers file for more information.
A better approach might be to write a script that takes a start/stop/restart argument and invokes the appropriate upstart command. The trick is to make this script setuid root (chown root:root script.sh; chmod +s script.sh), so that it runs as root instead of www-data. Give this script 755 permissions so only root can change it. This limits the security risk and still gives you the powers you need, but no more.
The setuid approach probably won't work directly on your system (try it first), since most Unix systems these days deliberately disable setuid for working as advertised on shell scripts since the security risk is too high. Here is an article that explains a workaround that uses a C program (on which setuid still works) to invoke your script. It is a little convoluted, but it should work.
Possibly the best approach would be to leverage upstart's event mechanism and have your web code fire events that upstart would catch and forward to your .conf file. I am just learning upstart myself, so I can't give you more specifics, but I get the sense it is meant to be used this way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: My locale is set, I can see € instead of $, but time still displays English months I am doing a Rails app in French. I downloaded a fr.yml stored in config/locales and added config.i18n.default_locale = :fr to my application.rb. The .yml contains days and months.
Messages in pages generated by scaffold are in French, € is displayed instead of $, but it keep using English names for months with strftime (a Time function).
Why?
A: <%= I18n.localize(Time.zone.now, :format => :short) %>
You can add more formats to your fr.yml
date:
formats:
default: "%d.%m.%Y"
numeric: "%d.%m.%Y"
short: "%e %b"
long: "%e %B %Y, %A"
only_day: "%e"
A: The strftime function isn't hooked into Rails - it's just a member of the Ruby Time class. Try using Rails localization instead - that should do what you're expecting.
Hope that helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Check Browser PHP and put results in .txt
Possible Duplicate:
How can I detect the browser with PHP or JavaScript?
I want to check what browser visitors to my site are using, and then save the results to a file named browser.txt on my server. Any ideas?
Thanks
A: Why not just install Google Analytics which does that (and an awful lot more) for you (albeit it doesn't store the data on your server)? Alternatively you could just check your server logs, the data should also be in there.
A: file_put_contents(
__DIR__ . '/browser.txt',
$_SERVER['HTTP_USER_AGENT'],
FILE_APPEND
);
A: In php you can do this:
get_browser( $_SERVER['HTTP_USER_AGENT']);
it will return an object/array containing all the information you need.
thake a look at PHP get_browser
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: How search engines find websites over internet I'm going to write a Web parser (an application that crawles on the web from one site to another).
How Can I find list of available domains/IPs in the internet (as complete as possible)?
How search engines find websites (What they use as a reliable list of registred IP/Domains for starting point)?
Thanks
A: As Michael P's comment indicates, depends on what your objective is.
My company recently wanted to answer a question about third-party tools used on leading websites. I used Alexa as a starting point to find the top (by traffic) websites, and created a parser that can answer the specific question my company asked. If you start from such a list, you can program your web crawler to follow the links it encounters to broaden your knowledge of sites on the web.
Hopefully that helps you think about the problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Undefined Reference Trying to invoke Java from C++ I am trying to create a Java virtual machine from C++ and invoke the main method passing a String argument to the main method of the Java program. I am following this example found on Sun's website: http://java.sun.com/docs/books/jni/html/invoke.html#11202
Here is the simple Java Program:
public class TestJNIInvoke
{
public static void main(String[] args)
{
System.out.println(args[0]);
}
}
Here is the C++ program I am using to (try to) invoke the JVM:
#include <jni.h>
#include <cstdlib>
using namespace std;
int main()
{
JNIEnv *env;
JavaVM *jvm;
jint res;
jclass cls;
jmethodID mid;
jstring jstr;
jclass stringClass;
jobjectArray args;
JavaVMInitArgs vm_args;
JavaVMOption* options = new JavaVMOption[1]; //LINE 18 ERROR
options[0].optionString =
(char*)&"-Djava.class.path=C:\\Program Files\\Java\\jdk1.7.0\\bin";
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 1;
vm_args.options = options;
vm_args.ignoreUnrecognized = false;
/* load and initialize a Java VM, return a JNI interface
* pointer in env */
res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); //LINE 26 ERROR
if (res < 0)
{
fprintf(stderr, "Can't create Java VM\n");
exit(1);
}
cls = env->FindClass("TestJNIInvoke");
if (cls == NULL)
{
goto destroy;
}
mid = env->GetStaticMethodID(cls, "main",
"([Ljava/lang/String;)V");
if (mid == NULL)
{
goto destroy;
}
jstr = env->NewStringUTF(" from CPP!");
if (jstr == NULL)
{
goto destroy;
}
stringClass = env->FindClass("java/lang/String");
args = env->NewObjectArray(1, stringClass, jstr);
if (args == NULL)
{
goto destroy;
}
env->CallStaticVoidMethod(cls, mid, args);
destroy:
if (env->ExceptionOccurred())
{
env->ExceptionDescribe();
}
jvm->DestroyJavaVM();
}
Anyway If I just compile the file with:
gcc -I"c:\Program Files\Java\jdk1.7.0\include"
-I"c:\Program Files\Java\jdk1.7.0\include\win32" -c TestJNIInvoke.cpp
It compiles fine, but when I try to compile and link:
gcc -I"c:\Program Files\Java\jdk1.7.0\include"
-I"c:\Program Files\Java\jdk1.7.0\include\win32" -g TestJNIInvoke.cpp
I get two weird errors that I don't understand:
TestJNIInvoke.cpp:18: undefined reference to `operator new[](unsigned int)'
TestJNIInvoke.cpp:26: undefined reference to `_imp__JNI_CreateJavaVM@12'
collect2: ld returned 1 exit status
I marked the lines in the above code where the error is occuring, has anyone encountered this problem before?
Any ideas/links would be great
Thanks
A: First, don't use gcc. By default, it assumes the code it's handling is written in C. When you want it to compile or link C++ code, you should run g++. This will bring in the C++ standard headers and libraries.
Second, you need to include the java libraries. Section 7.2.1 in the page you linked discusses this.
Your command line should look more like this:
g++ -I"C:\Program Files\Java\jdk1.7.0\include" -L"C:\Program Files\Java\jdk1.7.0\lib" -lthread -ljava TestJNIInvoke.cpp
Note that you might have to add additional include (-I) or linker (-L) directories.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Should I use EventArgs or a simple data type? I'm currently creating a library for fun and practice and I was wondering, when raising an event, how to choose between passing your own EventArgs derivative or just the data type.
For example, in my library I have something like this:
public delegate void LostConnectionEventHandler(string address);
public delegate void MessageReceieved(byte[] bytes);
What is the standard practice for this? Should I replace string address with ConnectionEventArgs and byte[] bytes with MessageEventArgs?
I know either one works just fine and this question may be subjective but I am still curious on the thought process higher-level programmers go through when deciding whether or not to include their own EventArgs or just to pass the data in directly.
Thanks!
A:
The .NET Framework guidelines indicate that the delegate type used for
an event should take two parameters, an "object source" parameter
indicating the source of the event, and an "e" parameter that
encapsulates any additional information about the event. The type of
the "e" parameter should derive from the EventArgs class. For events
that do not use any additional information, the .NET Framework has
already defined an appropriate delegate type: EventHandler.
Reference: http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx
Another useful information: http://msdn.microsoft.com/en-us/library/ms229011.aspx
A: Personally I like the idea of deriving from EventArgs,
if you have to pass status information and aggregate objects you could easily do it, see the
MouseEventArgs type for example.
using OOP approach, if you have an event/construct which accepts an object of type EventArgs you can rely on the fact that every object derived from it will work in the same way while if you have another kind of object which does not share the same base class, you could eventually break something.
hard to prove and reproduce but possible depending on the design, because events are special delegates designed to work with EventArgs and its descendants
A: In a larger project, having an EventArgs class, helps with minimizing the code you have to modify, when your event needs additional data in some cases. I usually prefere the EventArgs way instead of a direct value.
A: Within my projects I use EventArgs when the number of parameters is larger than one! Look at the NotifyPropertyChanged Event, it has one argument, which isn't an EventArgs type.
A: There's no need to derive from EventArgs however the convention follows the common (Introduce Parameter Object) refactoring rule. And the rationale for this rule is well documented.
A: I generally disagree with the "hide your args" guideline. Hiding arguments in a contrived object removes a lot of meaning and context from the event signature, making developers hunt for it. And why? Just to avoid something we do all the time with methods: update call sites when an argument is added. That's just not a big deal. If it were, we'd also hide method arguments in a "MethodArgs" parameter. The readability loss isn't worth it in most cases.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Define a computed column in view as not null I have a view with computed columns now I need to enforce the computed columns to be "not null" for lightswitch.
I tried to cast() but I still cant get the computed columns to be "not null"
Is it possible?
This is my SQL:
SELECT dbo.Nop_Manufacturer.Name,
CAST(SUM(dbo.Nop_OrderProductVariant.PriceExclTax) AS INT) AS
SALES,
CAST(MONTH(dbo.Nop_Order.PaidDate) AS INT) AS
paid_month,
CAST(YEAR(dbo.Nop_Order.PaidDate) AS INT) AS
paid_year,
CAST(COUNT(dbo.Nop_OrderProductVariant.OrderProductVariantID) AS INT)AS
num_prod_sold
FROM dbo.Nop_ProductVariant
INNER JOIN dbo.Nop_OrderProductVariant
ON dbo.Nop_ProductVariant.ProductVariantId =
dbo.Nop_OrderProductVariant.ProductVariantID
INNER JOIN dbo.Nop_Product
ON dbo.Nop_ProductVariant.ProductID = dbo.Nop_Product.ProductId
INNER JOIN dbo.Nop_Product_Manufacturer_Mapping
INNER JOIN dbo.Nop_Manufacturer
ON dbo.Nop_Product_Manufacturer_Mapping.ManufacturerID =
dbo.Nop_Manufacturer.ManufacturerID
ON dbo.Nop_Product.ProductId =
dbo.Nop_Product_Manufacturer_Mapping.ProductID
INNER JOIN dbo.Nop_Order
ON dbo.Nop_OrderProductVariant.OrderID = dbo.Nop_Order.OrderID
WHERE ( NOT ( dbo.Nop_Order.PaidDate IS NULL ) )
GROUP BY dbo.Nop_Manufacturer.Name,
MONTH(dbo.Nop_Order.PaidDate),
YEAR(dbo.Nop_Order.PaidDate)
A: CAST-ing as INT won't do anything to affect the perceived nullability of computed columns. You need to wrap them in ISNULL instead.
e.g. ISNULL(YEAR(dbo.Nop_Order.PaidDate),0)
This is documented in the last paragraph here
The Database Engine automatically determines the nullability of
computed columns based on the expressions used. The result of most
expressions is considered nullable even if only nonnullable columns
are present, because possible underflows or overflows will produce
null results as well. Use the COLUMNPROPERTY function with the
AllowsNull property to investigate the nullability of any computed
column in a table. An expression that is nullable can be turned into a
nonnullable one by specifying ISNULL(check_expression, constant),
where the constant is a nonnull value substituted for any null result.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android: Clickable imageview widget I want to make a very simple widget:
It must consist from just one image view
1) on incoming sms it should change the image
2) on click it also should change the image
I tried to make it using ImageButton but failed: there were problems with changing the image on sms received event: new image had wrong scale.
Anyway now I want to make an ImageView without anything else.
The problem is that I can't handle onClick event:
I've got a running service which should handle all events: sms received and click:
widget provider:
public class MyWidgetProvider extends AppWidgetProvider {
@Override
public void onDisabled(Context context) {
context.stopService(new Intent(context, UpdateService.class));
super.onDisabled(context);
}
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
Intent intent = new Intent(context, UpdateService.class);
context.startService(intent);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
for (int i = 0; i < appWidgetIds.length; i++) {
int appWidgetId = appWidgetIds[i];
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
Intent widgetClickIntent = new Intent(context, UpdateService.class);
widgetClickIntent.setAction(UpdateService.ACTION_ON_CLICK);
PendingIntent pendingIntentViewClick = PendingIntent.getService(context, 0, widgetClickIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.widget_imageview, pendingIntentViewClick);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
}
}
service:
public class UpdateService extends Service {
static final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
static final String ACTION_ON_CLICK = "android.MyWidget.ACTION_ON_CLICK";
private final static IntentFilter intentFilter;
static {
intentFilter = new IntentFilter();
intentFilter.addAction(ACTION_SMS_RECEIVED);
intentFilter.addAction(ACTION_ON_CLICK);
}
public final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(ACTION_SMS_RECEIVED)) {
reactOnSms(context);
}
if (action.equals(ACTION_ON_CLICK)) {
onCLick(context);
}
}
};
@Override
public void onCreate() {
super.onCreate();
registerReceiver(broadcastReceiver, intentFilter);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void reactOnSms(Context context) {
// doSomething
}
public void onCLick(Context context) {
// doSomething
}
Manifest:
<receiver a:name="..."...>
<intent-filter>
<action a:name="android.provider.Telephony.SMS_RECEIVED"/>
<action a:name="android.MyWidget.ACTION_ON_CLICK"/>
</intent-filter>
<meta-data a:name="android.appwidget.provider"
a:resource="@xml/my_widget_provider_info"/>
</receiver>
<service a:name=".UpdateService"
a:label="UpdateService">
<intent-filter>
<action a:name="android.provider.Telephony.SMS_RECEIVED"/>
<action a:name="android.MyWidget.ACTION_ON_CLICK"/>
</intent-filter>
</service>
I tried this Clickable widgets in android
A: I found the solution.
Sorry for those of you who read the question. Too much code inside, I understand.
The problem was that UpdateService was not the real handler of the broadcast intent. Anonymous implementation of BroadcastReceiver made all the work.
So the problem was in this code (widgetProvider):
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
for (int i = 0; i < appWidgetIds.length; i++) {
int appWidgetId = appWidgetIds[i];
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
// wrong:
// Intent widgetClickIntent = new Intent(context, UpdateService.class);
// widgetClickIntent.setAction(UpdateService.ACTION_ON_CLICK);
// PendingIntent pendingIntentViewClick = PendingIntent.getService(context, 0, widgetClickIntent, 0);
// correct:
Intent widgetClickIntent = new Intent(UpdateService.ACTION_ON_CLICK);
PendingIntent pendingIntentViewClick = PendingIntent.getBroadcast(context, 0, widgetClickIntent, 0);
///////
remoteViews.setOnClickPendingIntent(R.id.widget_imageview, pendingIntentViewClick);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is there a way to draw a set of lines in mathematica all with the same origin point? I have a set of points given by this list:
list1 = {{3, 1}, {1, 3}, {-1, 2}, {-1, -1}, {1, -2}};
I would like Mathematica to draw a line from the origin to all the points above. In other words draw vectors from the origin (0,0) to all the individual points in the above set. Is there a way to do this? So far I've tried the Filling option, PlotPoints and VectorPlot but they don't seem to be able to do what I want.
A: Graphics[
{
Line[{{0, 0}, #}] & /@ list1
}
]
where /@ is the shorthand infix notation for the function Map.
I wonder why you tried Filling, Plotpoints and VectorPlot. I must assume you haven't read the documentation at all, because even a superficial reading would tell you that those commands and options have nothing to do with the functionality you're looking for.
A: Starting easy, and then increasing difficulty:
Graphics[{Arrow[{{0, 0}, #}] & /@ list1}]
Graphics[{Arrow[{{0, 0}, #}] & /@ list1}, Axes -> True]
Needs["PlotLegends`"];
list1 = {{3, 1}, {1, 3}, {-1, 2}, {-1, -1}, {1, -2}};
k = ColorData[22, "ColorList"][[;; Length@list1]];
GraphicsRow[{
Graphics[Riffle[k, Arrow[{{0, 0}, #}] & /@ #], Axes -> True],
Graphics@Legend[Table[{k[[i]], #[[i]]}, {i, Length@#}]]}] &@list1
Needs["PlotLegends`"];
list1 = {{3, 1}, {1, 3}, {-1, 2}, {-1, -1}, {1, -2}};
k = ColorData[22, "ColorList"][[;; Length@list1]];
ls = Sequence[Thick, Line[{{0, 0}, {1, 0}}]];
GraphicsRow[{
Graphics[Riffle[k, Arrow[{{0, 0}, #}] & /@ #], Axes -> True],
Graphics@Legend[MapThread[{Graphics[{#1, ls}], #2} &, {k, #}]]}] &@list1
Needs["PlotLegends`"];
list1 = {{3, 1}, {1, 3}, {-1, 2}, {-1, -1}, {1, -2}};
pr = {Min@#, Max@#} & /@ Transpose@list1;
k = ColorData[22, "ColorList"][[;; Length@list1]];
GraphicsRow[{
Graphics[r = Riffle[k, {Thick,Arrow[{{0, 0}, #}]} & /@ #], Axes -> True],
Graphics@
Legend[MapThread[
{Graphics[#1, Axes -> True, Ticks -> None, PlotRange -> pr],
Text@Style[#2, 20]} &,
{Partition[r, 2], #}]]}] &@list1
You could also tweak ListVectorPlot, although I don't see why you should do it, as it is not intended to use like this:
list1 = {{3, 1}, {1, 3}, {-1, 2}, {-1, -1}, {1, -2}};
data = Table[{i/2, -i/Norm[i]}, {i, list1}];
ListVectorPlot[data, VectorPoints -> All,
VectorScale -> {1, 1, Norm[{#1, #2}] &},
VectorStyle -> {Arrowheads[{-.05, 0}]}]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Android Styling/Theming of just Search Dialog tl;dr: White text style in app theme being picked up by search dialog, making search text invisible.
I'm struggling mightily with what seems like a trivial issue.
My app is using a dark background, and I've tweaked the text color to be brighter than the standard gray using #EEEEEE.
I've implemented a Search Dialog (pre-Honeycomb) and it works well, but the text in the search dialog picks up the same #EEEEEE so it is essentially invisible. Even the context menu displayed when I long press the search text picks up #EEEEEE, so the text there is invisible as well.
I'm tearing my hair out, and I'm running out of hair.
Style:
<style name="master" paret="@android:style/Theme.NoTitleBar">
<item name="android:textColor">#EEEEEE</item>
<item name="android:windowNoTitle">true</item>
</style>
Manifest:
<application android:icon="@drawable/icon"
android:label="@string/app_label"
android:theme="@style/master"
android:hardwareAccelerated="true"
android:debuggable="true">
A: The attribute android:textColor is not meant to be used inside theme styles, it is primarily useful in widget and text appearance styles.
If you want to change the general text colors through a theme, use instead the android:textColor* family of attributes. There are quite a few of them, and different Views use them differently, so it takes a bit of experimentation (or careful studying of the Android source code) to to get it all right. The android.R.attr documentation lists them all. Look for the attributes that begin with textColor....
To get you started, try this theme, it will behave better by not affecting the Search Dialog colors at all, which seems to be what you want. By the way, you don't need to set android:windowNoTitle to true in your theme as your parent theme does that already:
<style name="master" parent="@android:style/Theme.NoTitleBar">
<item name="android:textColorPrimary">#EEEEEE</item>
<item name="android:textColorSecondary">#EEEEEE</item>
<item name="android:textColorTertiary">#EEEEEE</item>
</style>
A: I got into the same problem as you. I've looked around for a solution but it seems that you just can't change the textColor of a dialog. My solution was creating a custom dialog based on this tutorial: http://blog.androgames.net/10/custom-android-dialog/
I extended this a lot based on the Android source code, always using the same method names etc to make it a bit easier.
It is not ideal, but as far as I know it's the best option...
EDIT: for your problem there might be a simpler solution: don't put the textColor into the theme, but put it in a style. I don't know how you're styling your app but I'm usually creating a "master-style" which all the others inherit from (direct or indirect). You could then put the textColor in there so all your standard dialogs will still have the standard textColor.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Problems after server uses accept() to accept connections This is my first time ever using sockets, and I am having trouble accepting connections on the server side. My server is only designed to accept one connection at a time. Once a connection is received, the current date and time are written to the socket, and then the client prints out the date and time it received from the server. My server has the following code:
cout << "Server: Waiting for connections." << endl;
client_length = sizeof(client_address);
connection_fd = accept(listen_fd, (struct sockaddr*)&client_address, (socklen_t*)&client_length);
cout << "Server: Client connected" << endl;
When I run my server, I get the following output:
./server&
Server: Waiting for connections.
Then when I run my client, I get the following output:
./client 127.0.0.1
Client: Connecting to: 127.0.0.1
Client: Connected to server.
Sun Sep 25 13:20:07 2011
The client seems to print out the correct data, but the server never prints out that a client connected. Something is wrong here. Another symptom is when I try to write to the pipe (client writes, server reads), the client gets a broken pipe error. Is there something I am missing? If there is any code you would like to see, please ask.
Edit: Here is the server running under strace. Nothing seems to happen after accept is printed out. Weird?
write(2, "Server: Socket created.", 23Server: Socket created.) = 23
write(2, "\n", 1
) = 1
bind(3, {sa_family=AF_INET, sin_port=htons(4007), sin_addr=inet_addr("0.0.0.0")}, 16) = -1 EADDRINUSE (Address already in use)
write(2, "Server: Address and port bound t"..., 41Server: Address and port bound to socket.) = 41
write(2, "\n", 1
) = 1
listen(3, 100) = 0
write(2, "Server: Socket is now a listenin"..., 41Server: Socket is now a listening socket.) = 41
write(2, "\n", 1
) = 1
write(2, "Server: Waiting for connections.", 32Server: Waiting for connections.) = 32
write(2, "\n", 1
) = 1
accept(3,
Thanks.
A: This shouldn't happen.
It's even hard to imagine a broken scenario, like you have two instances of the server running, and the other one is accepting the connections, but then the new instance shouldn't be able to use the same port number again, so you probably doesn't verify return values of system calls, but then accept should fail, and you should see a false client connected message.. so, what the heck are you doing?
Update: yepp... -1 EADDRINUSE (Address already in use)
Another instance is running, or something else that uses that port number. Check with netstat. And for god's sake check the return values of those calls.
A: Your bind is failing with EADDRINUSE, yet your server plods on.
Add error handling to your code, and possibly change the port your are using.
Also, I suggest you make sure that you are not binding the same port in the client by accident
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dates from a text file I just wanted to ask whether it is possible to find Dates in all possible formats in a text file and print the results. I was able to open the file and format the dates but I couldn't combine the two elements. Here are the codes so far.
I appreciate any help.Thanks
here are the requirements and my approach :
Code needs to search all headings, headers, text and footnotes.
Code searches for a date, such as day of week, month, numeral 1 to 31 followed by a month, year between 1950 & 2050.
Code needs to get date as well as the nearest heading above and get the applicable main section
Code needs to get page number.
For Date :
import java.text.*;
import java.util.*;
public class Dates
{
public static void main(String[] args)
{
Date d1 = new Date();
DateFormat[] dfa = new DateFormat[6];
dfa[0] = DateFormat.getInstance();
dfa[1] = DateFormat.getDateInstance();
dfa[2] = DateFormat.getDateInstance(DateFormat.SHORT);
dfa[3] = DateFormat.getDateInstance(DateFormat.MEDIUM);
dfa[4] = DateFormat.getDateInstance(DateFormat.LONG);
dfa[5] = DateFormat.getDateInstance(DateFormat.FULL);
for(DateFormat df : dfa)
{
System.out.println(df.format(d1));
}
DateFormat df2 = DateFormat.getDateInstance(DateFormat.FULL);
String s = df2.format(d1);
System.out.println(s);
try
{
Date d2 = df2.parse(s);
System.out.println("parsed = " +d2.toString());
}
catch(ParseException pe)
{
System.out.println("Parse Exception");
}
}
}
for opening files :
import javax.swing.*;
import java.io.*;
import java.util.*;
public class FileOpener {
/**
* use a dialog box to select a text file (.txt)
* @return a Scanner for the selected file, or null if cancel selected
*/
public static Scanner selectTextFile() {
do {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Text/Java files","doc", "txt", "java");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
try {
if(returnVal == JFileChooser.APPROVE_OPTION) {
return new Scanner(chooser.getSelectedFile());
}
else {
return null;
}
}
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "Invalid file!",
"error", JOptionPane.ERROR_MESSAGE);
}
} while (true);
}
/**
* given a String, uses a Scanner to count the number of words
* @return number of words in the String
*/
public static int countWordsOnLine(String line) {
Scanner s = new Scanner(line);
//int count = 0;
while (s.hasNext()) {
s.next();
//count++;
}
//return count;
}
public static void main(String[] args) {
// make Java look like your normal OS
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) { // ignore exceptions and continue
}
Scanner lineScanner = FileOpener.selectTextFile();
int numberOfWords = 0;
if (lineScanner!=null) {
while (lineScanner.hasNextLine()) {
numberOfWords += FileOpener.countWordsOnLine(
lineScanner.nextLine());
}
System.out.println("The number of words is: " + numberOfWords);
//System.out.println(getPageNumber());
}
}
}
Table that will contain the end result:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class SimpleTableDemo extends JPanel {
private boolean DEBUG = false;
public SimpleTableDemo() {
super(new GridLayout(1,0));
String[] columnNames = {"HEADER",
"SENTENCE",
"PAGE",
"DATE"};
Object[][] data = {
{" ", " ",
" ", new Integer(5)},
{" ", " ",
" ", new Integer(3)},
{" ", " ",
" ", new Integer(2)},
{" ", " ",
" ", new Integer(20)},
{" ", " ",
" ", new Integer(10)}
};
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
if (DEBUG) {
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
printDebugData(table);
}
});
}
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this panel.
add(scrollPane);
}
private void printDebugData(JTable table) {
int numRows = table.getRowCount();
int numCols = table.getColumnCount();
javax.swing.table.TableModel model = table.getModel();
System.out.println("Value of data: ");
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + model.getValueAt(i, j));
}
System.out.println();
}
System.out.println("--------------------------");
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SimpleTableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
SimpleTableDemo newContentPane = new SimpleTableDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
A: All dates is almost certainly impossible. How are you going to parse these?
*
*Second monday of March 2012
*Donderdag 14 oktober aanstaande.
*First sunday after the first full moon after the equinox of 2012
These are all dates, and many more possibilities are possible. You can write a script that will find most dates, but not all of them.
But your best strategy is probably to define a number of common patterns, and scan the text file line by line for them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Size of button in alertdialog how can i change the size of button in alertdailog in code without using xml ?
I'm not using view ..
Thank you
The code :
alertbox3.setNeutralButton("Cancel",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } });
A: you may try this code:
AlertDialog.Builder adb = new AlertDialog.Builder(this);
Dialog d = adb.setView(new View(this)).create();
// (That new View is just there to have something inside the dialog that can grow big enough to cover the whole screen.)
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(d.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.FILL_PARENT;
lp.height = WindowManager.LayoutParams.FILL_PARENT;
d.show();
d.getWindow().setAttributes(lp);
and
http://developer.android.com/reference/android/widget/Button.html
look at this link aslo . Link1 and LInk2
A: you should use a customView for your case to change the button layout. see the following link on how to make your own view for alertDialog.
How to implement a custom AlertDialog View
A: Why do you want to? The system will construct a standard dialog layout on your behalf that follows conventions that the user expects and is familiar with. In general you should not go out of your way to circumvent this.
A: Try this :
https://stackoverflow.com/a/15910202/305135
final AlertDialog alert = builder.create();
alert.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button btnPositive = alert.getButton(Dialog.BUTTON_POSITIVE);
btnPositive.setTextSize(TEXT_SIZE);
Button btnNegative = alert.getButton(Dialog.BUTTON_NEGATIVE);
btnNegative.setTextSize(TEXT_SIZE);
}
});
return alert;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to draw gradient into a layer CGLayerRef I am new to Xcode and iOS development. I am trying to draw a gradient into a layer so that I can draw this layer repeatedly in my view. This gradient forms the background of the view and I do some drawing over this gradient. But when I draw a gradient into my layer, and then draw it in my view's context, it does not draw the gradient. I have tried debugging the code but everything seems to be just fine. Pasting the relevant code below:
I create the gradientLayer at the start.
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect myRect = self.bounds;
CGGradientRef myGradient;
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
CGFloat colors[] =
{
204.0 / 255.0, 224.0 / 255.0, 244.0 / 255.0, 1.00,
100 / 255.0, 200 / 255.0, 50 / 255.0, 1.00,
0, 0, 0, 1.00,
};
myGradient = CGGradientCreateWithColorComponents(rgb, colors, NULL, sizeof(colors)/(sizeof(colors[0])*4));
CGColorSpaceRelease(rgb);
CGContextRef layerContext = CGLayerGetContext(gradientLayer);
CGPoint start, end;
CGRect clip = CGContextGetClipBoundingBox(layerContext);
start = getStartPoint(clip);
end = getEndPoint(clip);
CGContextDrawLinearGradient(layerContext, myGradient, start, end, 0);
//CGContextSetRGBFillColor (layerContext, red / 255.0, green / 255.0, blue / 255.0, 1);
//CGContextFillRect (layerContext, clip);
I call this function when my class is instantiated. And then draw this layer repeatedly in my drawRect method.
CGRect rect = self.bounds;
CGContextSaveGState(context);
CGContextDrawLayerInRect(context, rect, gradientLayer);
CGContextSaveGState(context);
I can draw the same gradient directly in the drawRect but am unable to do so when drawing into a layer and then in the drawRect(trying to optimize the drawing).
A: The RGBA values for your gradient should be between 0.0f and 1.0f not between 0.0f and 255.0f.
A: YOU need to convert CGLayerRef into CGContextRef
Like this:
CGContextRef context = UIGraphicsGetCurrentContext();
CGLayerRef layer = CGLayerCreateWithContext(context, myRect.size, NULL);
CGContextRef gradientContext = CGLayerGetContext(layer);
// from here we care only on this gradientContext
// somewhere call
CGContextDrawLinearGradient(gradientContext, /*other args*/
// don't forget to clean memory
CGLayerRelease(layer);
and you can draw the gradient onto CGContextRef context
Or if you want to escape those conversions, you can use the normal CGContextRef
Here is how I achieved the gradient
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
// CGLayerRef gradientLayer = CGLayerCreateWithContext(ctx, myRect.size, NULL);
CGFloat colors[] =
{
204.0 / 255.0, 224.0 / 255.0, 244.0 / 255.0, 1.00, //color 1
100 / 255.0, 200 / 255.0, 50 / 255.0, 1.00, // color 2
0.0, 0.0, 0.0, 1.00, // color3
};
CGFloat locations[3] = { 0.0, 0.5, 1.0 }; // 3 locations
CGGradientRef myGradient = CGGradientCreateWithColorComponents(rgb, colors, locations, 3);
CGColorSpaceRelease(rgb);
// CGContextRef layerContext = CGLayerGetContext(gradientLayer);
CGFloat minX = CGRectGetMinX(self.bounds);
CGFloat minY = CGRectGetMinY(self.bounds);
CGFloat maxY = CGRectGetMaxY(self.bounds);
CGContextBeginPath(ctx);
CGRect clip = self.bounds;
CGContextAddRect(ctx, clip);
//release memory
CGContextClip(ctx);
CGContextDrawLinearGradient(ctx, myGradient, CGPointMake(minX,minY), CGPointMake(minX,maxY), kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
CGGradientRelease(myGradient);
Use the above code to get the gradient,
Ofcourse you can tweak both locations and colors to get the effect you want, but
remember the locations always is between 0.0 and 1.0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Capistrano error on bundling compass from git When I try to deploy to my newly set up server, capistrano throws this at me.
*** [err :: fupifarvandet.dk] fatal: Could not parse object '22e2458b77519e8eb8463170c1a1fe4bab105f3e'.
** [out :: fupifarvandet.dk] Git error: command `git reset --hard 22e2458b77519e8eb8463170c1a1fe4bab105f3e` in directory /var/www/apps/fupifarvandet.dk/shared/bundle/ruby/1.9.1/bundler/gems/compass-22e2458b7751 has failed.
** [out :: fupifarvandet.dk] If this error persists you could try removing the cache directory '/var/www/apps/fupifarvandet.dk/shared/bundle/ruby/1.9.1/cache/bundler/git/compass-dcbe0c41f22c777e90babfa80d61f78dfdea41b2'
This is from my Gemfile:
gem 'compass', git: 'git://github.com/chriseppstein/compass.git', branch: 'rails31'
What do?
A: It's because there is no rails3.1 branch on github. Try gem 'compass', '~> 0.12.alpha'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Class name conflict importing new package (java) First of all, I am a new to java, so my question might be stupid but i still need an answer :)
I have a class that handle display matters. I have named it "Display", but the problem is : I need to import a class called org.lwjgl.opengl.Display.
Of course, I have this error at my Display class statement :
"Display" is already defined in this compilation unit
And of course, I can rename my class, but i'd like to be sure there is no way to easily circumvent this issue.
In a general way (because using a game library such as LWJGL, I guess i will have plenty of this), is it a better idea to prefix all my class to avoid similar label ?
Update : The class is already in a package.
package Graphics;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
public class Display { ... }
Thanx.
A: If you can't rename your own class, which would be the easiest, then you can circumvent this by not importing the offending class and instead using the fully qualified package name, e.g
org.lwjgl.opengl.Display display = new org.lwjgl.opengl.Display().
Conversely, you should put your own class in packages and never use the default package, so that it's possible to apply the same method to disambiguate your own classes.
A: This happens when your java class name and importing library name is same. In your case Scanner is refer to the class name not for the library. Changing the class name to something else will be the simplest way to solve the error.
public class Foo {
private static class Display {...}
}
will also help to solve the issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: mysql - 2 select functions in 1 I want to combine 2 selects into 1 the first one is:
("SELECT * FROM `help_and_advice_forum` LIMIT 10, 10");
The second is:
("SELECT * FROM WHERE `sticky` = '1' LIMIT 0, 5");
Is their any way to select the first five sticky's then select 10 rows after 10 rows?
Thanks
A: UNION them together. (assuming help_and_advice_forum is the table name you omitted from the second one)
(SELECT * FROM `help_and_advice_forum` WHERE `sticky` = '1' ORDER BY id LIMIT 0, 5)
UNION
(SELECT * FROM `help_and_advice_forum` ORDER BY id LIMIT 10, 10)
If you have some unique id column like id, set an ORDER BY on it.
If you need to exclude the first five sticky results from your additional 10 rows where they might otherwise overlap and there is some unique id column in the table, try something like the following. I'm not positive it will work as intended though.
(SELECT * FROM `help_and_advice_forum` WHERE `sticky` = '1' ORDER BY id LIMIT 0, 5)
UNION
(SELECT * FROM `help_and_advice_forum` WHERE id NOT IN (SELECT id FROM help_and_advice_forum WHERE sticky=1 ORDER BY id LIMIT 0, 5) LIMIT 10, 10)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java: Getting time with currentTimeMillis() as a long, how do I output it with X decimal place accuracy? I have a long that represents System.currentTimeMillis(). I then took another measurement of the time into a long var later in my code. I subtracted the two but now want to see that time to 3 decimal places.
Currently I use %d to format my output when printing the long var and get only non-decimal values.
A: long is a whole number. It doesn't have decimal places. Do you mean you want to see seconds to three decimal places?
long start = System.currentTimeMillis();
long time = System.currentTimeMillis() - start;
System.out.printf("Took %.3f%n", time/1e3);
You can do the same with nanoTime, but it is still a whole number. If you want to see decimal places you need to divide by 1e3 (micro-seconds) or 1e6 (milli-seconds) or 1e9 (seconds)
A: You need to divide the number by 1000.0 and then display it using "%.3f". So something like
String.format("%.3f", number / 1000.0)
You need to divide by a double because you want a double. If you did divide by an int then it would round to the nearest int. You can't use %d because it is only used for displaying integers. You have to use %f for floats and doubles.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Does a collection of selenium 2.0 extensions exist? I have recently started a automated testing project using selenium 2.0. The api feels very low level and I'm looking to refactor some of the common stuff like form handling before writing too much repeating code.
I have searched a bit trying to find some conributed classes collection as I assume I'm not the first wanting to abstract some of the details of the driver away when writing the tests. I can't find any, however.
Where can I find reusable code for working with selenium 2.0?
I'm using Java but anything goes for inspiration.
Or would you recommend writing the utility classes from scratch or using the raw api?
A: I wrote an article about Selenium extensions in C#. It's only a few functions but you might find something interesting.
I agree that Selenium can lend itself to a lot of repetition and it would be interesting of the developers would include some higher level classes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Choosing Rails vs. Django based on performance and scalability I'm currently working on a side project (that hopefully will grow into something more), and right now its strictly static front-end stuff; HTML, CSS and jQuery. So in the meantime, I have time to do heavy research on choosing Ruby on Rails vs. Python/Django.
I've read countless articles comparing the two, which usually come down to "what language do you prefer?" and considerations of the development community.
My question here is strictly of a technical nature, comparing the frameworks (and their respective languages) as such:
Between Ruby/Rails vs. Python/Django:
*
*Which run-time performs better (any statistics or real-world examples would be great)?
*What are the known scalability problems, and which scales better in the long run (again, any technical documentation or data to represent this would be great)?
I understand that scalability comes down to architecture, so the question is what framework and its respective tools, APIs, plug-ins, community, documentation, etc. "guides" you towards the best scalable web architecture from the "get-go"?
Thanks!
A: https://stackoverflow.com/questions/91846/rails-or-django-or-something-else
Does Django scale?
Using Rails as a framework for a large website
https://stackoverflow.com/questions/3042259/django-or-rails
Rails or Django?
...
There are plenty of questions regarding this subject, and none of them answer the question - there's no right answer.
I don't think you should choose a framework on those two metrics. Unless you are building the next Facebook, both will scale to your needs. Similarly both should perform to your needs. Instead have a look at what features of the languages and frameworks appeal to your application etc.
A: That's the wrong approach to thinking about the problem.
Scalability on the web comes from expanding the number of application servers rather than speeding up an individual application server.
Ruby and Python are both slow languages with problematic multithreading and problematic garbage collectors. We use them anyway because they are very good at permitting the developer to write simpler programs that do the job better. It's not worth bothering about the question, which of these two runtimes performs better.
So long as you keep good web architecture, where your application server stateless (where all state is kept in the database or in cookies, but not in server-side sessions), you should not care what the actual performance of an individual request is, so long as it is reasonable. Because if your application server is stateless, you can scale that tier horizontally to cope with any need for scalability.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: how do I run code when a node is added to a C# TreeView control I need to run code when a new node is added to a treeview control. Control_Added event that comes with the control does not get fired when a new node is added to the TreeView which is weird as I expected that it was a control, a node I mean. What event should be used for this?
Thanks..
A: There is no event for that. This is not unusual, events are meant to tell your code that something of interest happened, something you don't otherwise know about. The user of your program cannot add a node to the treeview, only your code can do that. You already know about it.
Inheriting a class from TreeView and adding the event you want, as well as a public helper method that adds the node and raises the event is the workaround. It isn't a very good one because there is still a backdoor to add nodes that you cannot easily close.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: android OutOfMemoryError on WVGA800 and not any small screen format When I try and decode a bitmap on an emulator running less than WVGA800 it works fine (phones included) but on larger screens it throws a OutOfMemoryError
Why would that be? would phones with larger screens have more memory?
private Bitmap getBitmap(int assetKey) { return BitmapFactory.decodeResource(mContext.getResources(), assetKey); }
A: Phones with larger displays don't always have more memory than phones will smaller displas. Decoded bitmaps take a lot of of memory, 4 bytes of memory per pixel.
In general it is a good idea to downsample the bitmap if they are too large. You can do this easily:
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = n; // <-- this only decode every nth pixel
Bitmap b = BitmapFactory.decodeResource(mContext, rId, ops);
A: It's generally a good practice to break the data in to samples, to avoid memory exception. you can see the following link for that. you have to use sampleSize more than 1. I have resolved my issues by following this post.
Strange out of memory issue while loading an image to a Bitmap object
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I download an entire webpage (with images) on the iPhone? Is there a way to download an entire webpage for offline viewing with the iPhone SDK? I can use NSString with the contents of the URL, but that would just give me the HTML and no images. Is there any way to do it?
A: The popular open source library ASIHTTPRequest has a class that will do just this for you: download all HTML, images, and other resources associated with the page you're requesting.
It's called ASIWebPageRequest, and you can read the documentation and download it from here: http://allseeing-i.com/ASIHTTPRequest/ASIWebPageRequest
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Provision a Device When it's Not Connected to Computer this is driving me absolutely crazy. I'm trying to deploy an application to one of our developers who just bought a new iPhone, but the problem is that he's nowhere near the office right now so I can't physically connect his device. Any ideas how I can add a provisioning profile to his device manually without him having to travel so far? I've already sent him the profile, and added his UDID to the devices section of the provisioning portal... now I just can't figure out how to add the provisioning profile to his device over the air. Any ideas?
Thank you!
EDIT: already using test flight, but this developers device is under the heading "These teammate's devices were not identified in the embedded.mobileprovision for this build."
A: You can use Testflight
You have to create an account. He has to register with his device with your account (you can send a link, instructions in testflight), this will add a testflight profile to his device. With this you have his UUID and all this stuff. Now sign and export your application following the testflight tutorial and upload it to testflight app. All this done, the client can install your app without needing itunes or a computer.
A: If you have already entered the device's UDID in your portal and have mobileprovisions including it, try Over the Air Provisioning from your web site.
If you don't have a web server under your control, TestFlight offers one as a service. (But I have no affiliation and haven't tried it yet.)
A: ASSUMPTION: Purpose is for testing. If this is a Production distribution in an Enterprise Developer license, I don't have the answer for you.
What I did was, first create an Ad Hoc Distribution Profile containing those devices.
Second, archive your app in XCode.
Third, go to the Archives window (CMD-Shift-2), then pick Archives. Click Share to create an IPA file. MAKE SURE TO SELECT THE CORRECT PROVISIONING PROFILE TO SIGN THE APP WITH AT THIS POINT.
Then, e-mail the IPA file to the person.
This person will then be able to synch the app via iTunes (in iTunes, pick File / Add to Library, browse and pick the file.)
However, when the provisioning profile expires, the app will no longer launch.
A: http://developer.apple.com
he needs to be logged in.
then go to the provisioning portal, and request a certificate. you need to approve it. then he adds this certificate to Xcode organizer and he can user the device
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can you operate on Arrays in Java like in Matlab? I was wondering whether there was a way to do the following, without writing a function or a for loop:
int[] ma = (3,4,4,5,6,7);
ma += 5;
thus, adding 5 to all elements in the array. Matlab allows for such a convenient shortcut.
A: Short answer: No you can't. You need to write a loop to do it.
A: In a word: no. Java has no operations like that. But there's nothing to stop you from writing a method add() that takes an array and an int and adds the int to every element in the array. Write subtract(), multiply(), etc, and you'd have a nice little library for your own use.
A: If you need this a lot looking into Scala might be an option. Scala also runs on the JVM, and has things like folds, which allow you to define these kind of things in very little code.
However, it is a functional language, which requires a different way of thinking than traditional (iterative) programming.
A: Java provides a number of collection classes with functionality similar to what Matlab provides for arrays. The closest match would be java.util.ArrayList, which is backed by an array. You can use the add() method to append items to the collection, instead of a += operator. ArrayList exports a number of interfaces which make it compatible with many of the methods and classes in other java packages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Rails 3 RESTful Authentication - uninitialized constant ApplicationController::AuthenticatedSystem Just installed the upgraded restful_authentication plugin for Rails 3 from https://github.com/Satish/restful-authentication. I'm trying to include code from the plugin in my application helper as follows:
class ApplicationController < ActionController::Base
protect_from_forgery
include AuthenticatedSystem
end
However, when I run the server and navigate to my application on the localhost, I get an error as follows:
uninitialized constant ApplicationHelper::AuthenticatedSystem
AuthenticatedSystem is a module in lib/authenticated_system.rb, so why isn't the include working?
A: Rails 3 doesn't load files in the /lib directory by default anymore :(
Add this to your config/application.rb:
config.autoload_paths << "#{Rails.root}/lib"
And you should be fine. Don't forget to restart your server.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to get JFrame as function argument in java? I wanted to make a different function to make menubar for java application.
In menubar function frame.pack() in action listeners and frame.setJMenuBar statements are required.
So how can we pass frame as object to subclass as argument?
I get errors in
imports..
public class sjava {
public static void CreateAndRunGUI() {
final JFrame frame = new JFrame("MyFrame");
code..
MakeMenuBar(frame);
frame.pack();
frame.setVisible(true);
}
public static void MakeMenuBar(Object frame) {
JMenuBar menubar = new JMenuBar();
menubar.setBackground(new Color(180,160,130));
menubar.setOpaque(true);
menubar.setPreferredSize(new Dimension(800,20));
frame.setJMenuBar(menubar);
JMenu menu1 = new JMenu("menu1");
code..
mitem1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
code..
SwingUtilities.updateComponentTreeUI(frame);
frame.pack();
}
});
code..
mitem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
code..
SwingUtilities.updateComponentTreeUI(frame);
frame.pack();
}
});
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
CreateAndRunGUI();
}
});
}
Can makemenubar function be used without using frame as an argument?
A: You'll have to replace
public static void MakeMenuBar(Object frame) {...}
with
public static void MakeMenuBar(JFrame frame) {...}
otherwise no methods of class JFrame will be accessible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to specify query MediaStore.Audio.Media in Android SDK? I have a ListView of a music albums that are on my SD. I want to make another list that displays the songs that are on the album, when i click it. How to I query MediaStore only for that certain album?
Thanks!
A: Hi this may help you.....
Specify where clause with MediaStore.Audio.Media.ALBUM =
cur = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
proj, whereclause, null, null);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: About styling order list <html>
<head>
<style type='text/css'>
ol li{background-color:green;}
ol li:hover{background-color:lightgreen;}
</style>
</head>
<body>
<ol>
<li>This is first line</li>
<li>Here is second line</li>
<li>And last line</li>
</ol>
</body>
</html>
if we use this coding the number's background color is not changing when we mouse over. i want to change the number's background color too when we mouse over, how can we do it.
A: You've got a couple of options, the first is to use: list-style-position: inside;:
ol li{background-color:green; list-style-position: inside;}
ol li:hover{background-color:lightgreen;}
JS Fiddle demo.
And the second is to use generated content:
ol {
counter-reset: listNumber;
}
ol li {background-color:green; list-style-type: none; counter-increment: listNumber; position: relative; }
ol li:before {
content: counter(listNumber);
background-color: green;
position: absolute;
top: 0;
left: -2em;
width: 1.6em;
display: block;
}
ol li:hover,
ol li:hover:before {background-color:lightgreen;}
JS Fiddle demo.
The latter approach, using generated content, is probably the better approach but with weaker cross-browser support; as it fails in IE<8 (though is supported in IE8+).
A: not only list-style-position should be used, but also text-indent
http://jsfiddle.net/HerrSerker/QtRwa/
ol {
list-style-position: inside;
padding-left: 0;
overflow: hidden;
}
ol li {
background-color:green;
text-indent: -20px;
padding-left: 20px;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: button doens't work ! I'm using .show(), hide(), toogle() and style.visibility Ive faced a problem which I have no idea the why ... so Im here..
http://videoarts.com.br/newSite/addAlbum.php
First, It has to select the "tipo".
If is "foto" a form will show up. When the its filled in the "album nome" the "ok" button will show up and if clicked, will submit the form ! works fine !!!
But, if its selected "video" a new form will show up bellow the same foto's form with a new choice. If youtube is choosen, a link's field will show up. When filled with a right link, the ok button will show up, but ITS NO POSSIBLE TO CLICK IT !
If it selected video and then "arquivo" (its a portuguese word to file) the button also will show up and i have the same problem ... not clickable ...
I use Jquery hide, show and toogle to the forms and document.getelemen(buton).style.visibility to control the button ...
any idea ???
A: The div with an id of 'contactFone' is too long. So it's over lapping the the 'contactEmail' div.
You can set the z-index of the contactEmail div to be higher than the contactFone to fix it.
Put this in your css file
#contactEmail {
z-index:100;
}
A: Add Style to
#contactButton input
{ z-index: 1000;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Is there a split function in xpath? I am trying to split a text from a node <extra>text1|text2|text3|text4</extra> into four parts "|" as the delimiter and reconstruct 4 new nodes as follows.
<g:test1>text1</g:test1>
<g:test2>text2</g:test2>
<g:test3>text3</g:test3>
<g:test4>text4</g:test4>
Here is the code I have, which obviously is not working but should explain what I am trying to do.
<%
Dim objXML, x
Set objXML = CreateObject("MSXML2.DOMDocument")
objXML.async = False
objXML.setProperty "ServerHTTPRequest", True
objXML.Load "http://www.thesite.com/v/myxml.xml"
objXML.setProperty "SelectionLanguage", "XPath"
Dim xmldoc: set xmldoc = CreateObject("MSXML2.DomDocument")
xmldoc.async = false
Dim instruction
Set instruction = xmldoc.createProcessingInstruction("xml", "version=""1.0"" encoding=""UTF-8"" standalone=""yes""")
xmldoc.appendChild instruction
Dim rss: set rss = xmldoc.createElement("rss")
xmldoc.appendChild rss
Dim itemNode2: Set itemNode2 = xmldoc.selectSingleNode(".//rss")
Dim name: Set name = xmldoc.createAttribute("xmlns:g")
name.Value = "http://base.google.com/ns/1.0"
itemNode2.attributes.setNamedItem(name)
Dim itemNode: Set itemNode = xmldoc.selectSingleNode(".//rss")
Dim version: Set version = xmldoc.createAttribute("version")
version.Value = "2.0"
itemNode.attributes.setNamedItem(version)
Dim channel: set channel = xmldoc.createElement("channel")
rss.appendChild channel
For Each x In objXML.documentElement.selectNodes(".//SAVED_EXPORT")
Dim item: set item = xmldoc.createElement("item")
channel.appendChild item
Dim str1: Set str1 = x.selectSingleNode("extra")
Dim gstrarray
gstrarray = split(str1.text,"|")
Dim gstr1: set gstr1 = xmldoc.createElement("g:test1")
gstr1.text =gstrarry(0)
item.appendChild gstr1
Dim gstr2: set gstr2 = xmldoc.createElement("g:test2")
gstr2.text =gstrarry(1)
item.appendChild gstr2
Dim gstr3: set gstr3 = xmldoc.createElement("g:test3")
gstr3.text =gstrarry(2)
item.appendChild gstr3
Dim gstr4: set gstr4 = xmldoc.createElement("g:test4")
gstr4.text =gstrarry(3)
item.appendChild gstr4
Next
Response.Write xmldoc.xml
%>
A: There isn't a split() (or equivalent) function in XPath 1.0.
There is a tokenize() function in XPath 2.0.
One can implement splitting functionality using XSLT 1.0 -- there are several questions wtih good answers in the xslt tag.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Returning an OFFSET subquery result in sqlite3 I'm selecting a random row from a table in SQLite by using a subquery to determine a random OFFSET value:
SELECT id, prev_node, next_node FROM edges WHERE prev_node = ? LIMIT 1
OFFSET abs(random())%(SELECT count(*) FROM edges WHERE prev_node = ?);
This is functionally correct for my task, but it requires two hits to an index:
0|0|TABLE edges WITH INDEX edges_all_prev
0|0|TABLE edges WITH INDEX edges_all_prev
The query is for a random walk that is very likely to visit the same node more than once, so as the number of edges grows it would be helpful to cache the result of the SELECT count(*) subquery.
Can I select the value of that subquery along with my other returned values?
Looking at the VDBE dump for the query, that value is just out of reach. It's in register 8 (moved there in step 21) while the result row is being created from registers 16-18 (step 42):
0|Trace|0|0|0||00|
1|Integer|1|1|0||00|
2|Function|0|0|5|random(0)|00|
3|Function|0|5|4|abs(1)|01|
4|If|7|23|0||00|
5|Integer|1|7|0||00|
6|Null|0|8|0||00|
7|Integer|1|9|0||00|
8|Null|0|10|0||00|
9|Variable|2|11|1||00|
10|Goto|0|47|0||00|
11|OpenRead|2|15|0|keyinfo(4,BINARY,BINARY)|00|
12|IsNull|11|18|0||00|
13|Affinity|11|1|0|d|00|
14|SeekGe|2|18|11|1|00|
15|IdxGE|2|18|11|1|01|
16|AggStep|0|0|10|count(0)|00|
17|Next|2|15|0||00|
18|Close|2|0|0||00|
19|AggFinal|10|0|0|count(0)|00|
20|SCopy|10|13|0||00|
21|Move|13|8|1||00|
22|IfZero|9|23|-1||00|
23|Remainder|8|4|2||00|
24|MustBeInt|2|0|0||00|
25|IfPos|2|27|0||00|
26|Integer|0|2|0||00|
33|Affinity|14|1|0|d|00|
34|SeekGe|3|45|14|1|00|
35|IdxGE|3|45|14|1|01|
36|AddImm|2|-1|0||00|
37|IfNeg|2|39|0||00|
38|Goto|0|44|0||00|
39|IdxRowid|3|16|0||00|
40|Column|3|0|17||00|
41|Column|3|1|18||00|
42|ResultRow|16|3|0||00|
43|IfZero|1|45|-1||00|
44|Next|3|35|0||00|
45|Close|3|0|0||00|
46|Halt|0|0|0||00|
47|Transaction|0|0|0||00|
48|VerifyCookie|0|27|0||00|
49|TableLock|0|9|0|edges|00|
50|Goto|0|11|0||00|
I could create a function that saves the count after it's calculated, but is there a straightforward SQL syntax for requesting the result of that subquery?
A: I wrote the function to save the counts I mentioned at the end of the original post, so here's one possible answer for removing the duplicate index search. I would still like to know if this is doable with straight SQL.
I created a passthrough user function to capture the count from the
subquery as the offset is calculated.
So instead of the original query:
SELECT id, prev_node, next_node FROM edges WHERE prev_node = ? LIMIT 1
OFFSET abs(random())%(
SELECT count(*) FROM edges WHERE prev_node = ?);
I have something more like this:
SELECT id, prev_node, next_node FROM edges WHERE next_node = ? LIMIT 1
OFFSET abs(random())%(
cache(?, (SELECT count(*) FROM edges WHERE prev_node = ?));
The first argument to cache() is a unique identifier for that count. I
could just use the value of prev_node, but due to the application I
need to be able to cache the counts for forward and backward walks
separately. So I'm using "$direction:$prev_node_id" as the key.
The cache function looks like this (using Python):
_cache = {}
def _cache_count(self, key, count):
self._cache[key] = count
return count
conn.create_function("cache", 2, self._cache_count)
And then in the random walk function, I can cons up the hash key and
check whether the count is already known. If it is, I use a variant of
the main query that doesn't include the subquery:
uncached = "SELECT id, next_node, prev_node " \
"FROM edges WHERE prev_node = :last LIMIT 1 " \
"OFFSET abs(random())%cache(:key, " \
" (SELECT count(*) FROM edges WHERE prev_node = :last))"
cached = "SELECT id, next_node, prev_node, has_space, count " \
"FROM edges WHERE prev_node = :last LIMIT 1 " \
"OFFSET abs(random())%:count"
key = "%s:%s" % (direction, last_node)
if key in cache:
count = cache[key]
query = cached
args = dict(last=last_node, count=count)
else:
query = uncached
args = dict(last=last_node, key=key)
row = c.execute(query, args).fetchone()
The cached queries run about twice as fast as the uncached on average (5.7us
vs. 10.9us).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How can I change the product thumbnail display in Magento? I am trying to change the product thumbnails in Magento. I am looking at this line in /app/design/frontend/default/THEME/layout/catalog.xml:
<block type="catalog/product_view_media" name="product.info.media" as="media" template="catalog/product/view/media.phtml"/>
This would lead me to believe that I can change the file /app/design/frontend/default/THEME/template/catalog/product/view/media.phtml. However, when I make changes to this file, nothing changes. Even blanking the file doesn't cause any changes. I have the cache completely disabled, so that can't be the problem.
If I remove the <block... from above, the product thumbnails section disappears completely, so that line must be correct.
What file do I need to edit in order to change the thumbnail display?
A: Search the same file in other themes and packeges (depends on what theme is swithced on in the admin panel). Also on of the easiest way is to look in the place you need to change using f. e. firebug and get relatively unique class name or ID and the search it in design folder (grep etc.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why would an app run fine in the system environment, but not under RVM? I'm trying to get up to speed with RVM.
I have a Rails 2 app that works fine within my system. In other words it worked before I installed RVM and it works if I "turn RVM off" with $ rvm use system.
Under RVM I installed the same Ruby version and patch level as my system Ruby, and then I created a gemset and installed all the gem versions that the app uses.
However, under RVM when I run rake gems I get this result...
$ rake gems
rake/rdoctask is deprecated. Use rdoc/task instead (in RDoc 2.4.2+)
rake aborted!
undefined method `name' for "actionmailer":String
Tasks: TOP => environment
(See full trace by running task with --trace)
With --trace...
$ rake gems --trace
rake/rdoctask is deprecated. Use rdoc/task instead (in RDoc 2.4.2+)
** Invoke gems (first_time)
** Invoke gems:base (first_time)
** Execute gems:base
** Invoke environment (first_time)
** Execute environment
rake aborted!
undefined method `name' for "actionmailer":String
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/rails/gem_dependency.rb:277:in `=='
/Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/dependency.rb:217:in `==='
/Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/dependency.rb:217:in `matching_specs'
/Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `find_all'
/Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/specification.rb:410:in `each'
/Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/specification.rb:409:in `each'
/Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/dependency.rb:216:in `find_all'
/Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/dependency.rb:216:in `matching_specs'
/Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/dependency.rb:238:in `to_specs'
/Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/dependency.rb:256:in `to_spec'
/Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems.rb:1210:in `gem'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/rails/gem_dependency.rb:75:in `add_load_paths'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/initializer.rb:301:in `add_gem_load_paths'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/initializer.rb:301:in `each'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/initializer.rb:301:in `add_gem_load_paths'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/initializer.rb:132:in `process'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/initializer.rb:113:in `send'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/initializer.rb:113:in `run'
/Users/username/project/my_app/config/environment.rb:7
/Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
/Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/activesupport-2.3.11/lib/active_support/dependencies.rb:182:in `require'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/activesupport-2.3.11/lib/active_support/dependencies.rb:547:in `new_constants_in'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/activesupport-2.3.11/lib/active_support/dependencies.rb:182:in `require'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/tasks/misc.rake:4
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:205:in `call'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:205:in `execute'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:200:in `each'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:200:in `execute'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:158:in `invoke_with_call_chain'
/Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:151:in `invoke_with_call_chain'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:144:in `invoke'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/tasks/gems.rake:17
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:205:in `call'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:205:in `execute'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:200:in `each'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:200:in `execute'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:158:in `invoke_with_call_chain'
/Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:151:in `invoke_with_call_chain'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:176:in `invoke_prerequisites'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:174:in `each'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:174:in `invoke_prerequisites'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:157:in `invoke_with_call_chain'
/Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:151:in `invoke_with_call_chain'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/task.rb:144:in `invoke'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/application.rb:112:in `invoke_task'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/application.rb:90:in `top_level'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/application.rb:90:in `each'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/application.rb:90:in `top_level'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/application.rb:129:in `standard_exception_handling'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/application.rb:84:in `top_level'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/application.rb:62:in `run'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/application.rb:129:in `standard_exception_handling'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/lib/rake/application.rb:59:in `run'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rake-0.9.2/bin/rake:32
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/bin/rake:19:in `load'
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/bin/rake:19
Tasks: TOP => environment
When I try to run the app I get...
$ script/server
=> Booting WEBrick
=> Rails 2.3.11 application starting on http://0.0.0.0:3000
NOTE: Gem.source_index is deprecated, use Specification. It will be removed on or after 2011-11-01.
Gem.source_index called from /Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/rails/gem_dependency.rb:21.
NOTE: Gem::SourceIndex#refresh! is deprecated with no replacement. It will be removed on or after 2011-11-01.
Gem::SourceIndex#refresh! called from /Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/rails/vendor_gem_source_index.rb:34.
NOTE: Gem::SourceIndex#load_gems_in is deprecated with no replacement. It will be removed on or after 2011-11-01.
Gem::SourceIndex#load_gems_in called from /Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/source_index.rb:322.
NOTE: Gem::SourceIndex#add_spec is deprecated, use Specification.add_spec. It will be removed on or after 2011-11-01.
Gem::SourceIndex#add_spec called from /Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/source_index.rb:127.
[ ... "NOTE: Gem::SourceIndex" thing repeats a bunch of times ... ]
/Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/rails/gem_dependency.rb:277:in `==': undefined method `name' for "actionmailer":String (NoMethodError)
from /Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/dependency.rb:217:in `==='
from /Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/dependency.rb:217:in `matching_specs'
from /Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `find_all'
from /Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/specification.rb:410:in `each'
from /Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/specification.rb:409:in `each'
from /Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/dependency.rb:216:in `find_all'
from /Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/dependency.rb:216:in `matching_specs'
from /Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/dependency.rb:238:in `to_specs'
from /Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/dependency.rb:256:in `to_spec'
from /Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems.rb:1210:in `gem'
from /Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/rails/gem_dependency.rb:75:in `add_load_paths'
from /Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/initializer.rb:301:in `add_gem_load_paths'
from /Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/initializer.rb:301:in `each'
from /Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/initializer.rb:301:in `add_gem_load_paths'
from /Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/initializer.rb:132:in `process'
from /Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/initializer.rb:113:in `send'
from /Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/initializer.rb:113:in `run'
from /Users/username/project/my_app/config/environment.rb:7
from /Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
from /Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
from /Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/activesupport-2.3.11/lib/active_support/dependencies.rb:182:in `require'
from /Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/activesupport-2.3.11/lib/active_support/dependencies.rb:547:in `new_constants_in'
from /Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/activesupport-2.3.11/lib/active_support/dependencies.rb:182:in `require'
from /Users/username/.rvm/gems/ruby-1.8.7-p174@my_app_rails_2/gems/rails-2.3.11/lib/commands/server.rb:84
from /Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
from /Users/username/.rvm/rubies/ruby-1.8.7-p174/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
from script/server:3
A: Yes, RubyGems has had a very fast development pace lately and is not completely backwards compatible. Try:
gem install rubygems -v 1.3.7
You may have to clear out the gemset to reinstall rubygems...
If you're using rvm, you can change the version of RubyGems with the following command:
rvm rubygems 1.3.7
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Communication between kernel threads in a linux kernel module I'm just beginning to learn the tricks of making a kernel module on linux kernel 2.6. What I'm looking to do is have 3 kernel threads, called the slaves, that need to send data to a 4th kernel thread, called master, and receive their respective responses. The slaves can request at any time, which means I will need some sort of a queue structure and a way to redirect responses to the correct thread.
First I looked at implementing my own queue structure to queue incoming requests - but how do I signal the master of this? I don't want the master to keep polling (as in the case of spinlocks/semaphores). I have a feeling there is a better way to communicate between threads.
Due to lack of documentation (and admittedly inferior searching skills), I'm at a loss on how to implement this. Can you point me in the right direction?
A: You are facing two distinct problems:
*
*The actual communication between the slaves and the master. You can use the FIFO implementation in the kernel (kernel/kfifo.c).
*You need demultiplexing for the master without busy-waiting/polling. You can do it just like in userspace, via poll/epoll on an "event file descriptor" (eventfd). Take a look at the kernel-level API in include/linux/eventfd.h (the implementation is in fs/eventfd.h).
You should probably use a [kfifo, event file] pair for each slave thread. The master thread blocks in a do_poll() call and, when woken up, is able to use the right FIFO based on the fd that was "signaled". Take a look at fs/select.c to have an idea about how you should call do_poll().
You might want to use mutexes to guard the FIFO.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Apache VirtualHost slow lookup I finally managed how to configure properly httpd.conf for my virtualhost needings. This is the relevant part of httpd.conf file
NameVirtualHost *:80
<VirtualHost *:80>
ServerName localhost
DocumentRoot /Applications/XAMPP/htdocs/
</VirtualHost>
<VirtualHost *:80>
ServerName test.local
DocumentRoot /Applications/XAMPP/htdocs/test/
</VirtualHost>
<VirtualHost *:80>
ServerName work.local
DocumentRoot /Applications/XAMPP/htdocs/work/
</VirtualHost>
When I access anything on localhost (i.e. http://localhost/phpmyadmin) everything is very fast.
Whenever I access test.local or work.local (or others I configured) it spends 10-15 seconds on lookup. The following requests are handled correctly and it's very fast but after a minute or so of inactivity, it has to lookup again.
This is my /etc/hosts file
127.0.0.1 localhost
255.255.255.255 broadcasthost
#::1 localhost
fe80::1%lo0 localhost
# Virtualhosts
127.0.0.1 test.local work.local yii.local
How could I fix this annoying issue?
A: Add your virtual hosts to the first line:
127.0.0.1 localhost test.local work.local yii.local
And remove the last line.
That should do the trick. Your vhosts are now an alias for localhost. It's not a good idea to have the same IP-address in multiple lines. This just confuses the DNS-cache.
A: What fixed it for me was editing httpd-vhosts.conf and changing all instances of:
<VirtualHost *:80>
to:
<VirtualHost 0.0.0.0:80>
It was taking about 2-5 seconds to resolve the host, now it is instant. I did not have to modify the order of my sites in my hosts file. This just makes it use ipv4 instead of ipv6 which I'd bet you don't use anyway.
A: For anyone who is using Chrome and still gets slow virtual host lookup, you need to change the virtual host name to something else than .local, eg. change test.local to test.dev.
Explanation and source here: http://bencrowder.net/blog/2012/10/slow-localhost-in-chrome/
A: You should as well implement other parameters to your vhosts file, like separate error logs and server alias
DocumentRoot "D:/xampp/htdocs/asd"
ServerName asd.com.br
ServerAlias asd.com.br
ErrorLog "logs/asd.log"
CustomLog "logs/asd.log" combined
A: Also setting the ip for ServerName in httpd.conf file worked for me
ServerName 127.0.0.1:80
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
} |
Q: SQL - Query Multiple Aggregations based on DateTime - MySQL This is a complex one. But I have a table which has a DATETIME field, and a few other int and float fields which need to be summed and averaged. We want to do the summing and averaging on this table based on the time stamps and ultimately would aim to develop 3 queries which in a sense would build on one another.
So the able looks like this
TIMESTAMP |subj_diff| SCR2 | SCR3
2011-09-20 09:01:37 | 1 | 0.02 | 1.6
2011-09-20 09:04:18 | 3 | 0.09 | 1.8
2011-09-20 14:24:55 | 5 | 0.21 | 1.2
2011-09-21 18:50:47 | 8 | 0.08 | 0.9
2011-09-21 18:54:21 | 9 | 0.12 | 2.1
The three queries that we would like to generate are:
1. Sum up all the preceding items from a previous data up to and including the currently select record. There should also be another column with the total So say for example if we wanted the results between the 20th and 21st the returned table would look like:
TIMESTAMP |subj_diff| SCR2 | SCR3 | COUNT
2011-09-20 09:01:37 | 1 | 0.02 | ... | 1
2011-09-20 09:04:18 | 4 | 0.11 | | 2
2011-09-20 14:24:55 | 9 | 0.32 | | 3
2011-09-21 18:50:47 | 17 | ...
2011-09-21 18:54:21 | 26 |
2. Sum up the results at 5 minute time intervals - similar to the above however the query would return 3 rows as rows 1 & 2 and rows 4&5 would be summed together in the same fashion as above. IN this query its ok if for each 5 min interval that has nothing 0 is returned with a count of 0. E.g.
TIMESTAMP |subj_diff| SCR2 | SCR3 | COUNT
2011-09-20 09:05:00 | 4 | 0.11 | 3.4 | 2
2011-09-20 14:25:00 | 5 | 0.21 | 1.2 | 1
2011-09-21 18:55:00 | 17 | 0.20 | 3.0 | 2
3. Do the same thing in query number 1 for the result set of query number two for every 5 minute interval in the day (i.e. from 00:05:00 to 24:00:00).
This is a rather tricky one, I have no idea how to start this one. Would anyone be able to write SQL to solve this problem?
Heres some basic code using cursors and stored procs but it doesnt really work.
DROP PROCEDURE curdemo;
DELIMITER $$
CREATE PROCEDURE curdemo()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE a datetime;
DECLARE b,c FLOAT;
DECLARE cur1 CURSOR FOR
SELECT msgDate, subj_diff FROM classifier_results
WHERE DATE(msgDate) >= DATE('2011-09-25');
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
CREATE TEMPORARY TABLE IF NOT EXISTS temp_scores (d datetime, acc float);
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO a, b;
IF done THEN
LEAVE read_loop;
END IF;
INSERT temp_scores(d,acc)
SELECT a, SUM(subj_diff) FROM classifier_results
WHERE DATE(msgDate) >= DATE('2011-09-25')
AND msgDate <= a;
END LOOP;
CLOSE cur1;
SELECT * FROM temp_scores;
END;
Cheers!
A: I haven't tested this, but let me know if this works for you:
1.
SET @csum:=0;
SELECT a.msgDate, (@csum:=@csum + a.subj_diff) AS subj_diff
FROM classifier_results a
2.
SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(a.msgDate)/(60*5))*(60*5)) as msgDate, sum(a.subj_diff) AS subj_diff
FROM classifier_results a
3.
SET @csum:=0;
SELECT b.msgDate, (@csum:=@csum + b.subj_diff) AS subj_diff
FROM (
SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(a.msgDate)/(60*5))*(60*5)) as msgDate, sum(a.subj_diff) AS subj_diff
FROM classifier_results a
) b
A: Lets see here...
1:
SELECT TIMESTAMP,
(@var_subj_diff := @var_subj_diff + subj_diff) AS subj_diff,
(@var_SCR2 := @var_SCR2 + SCR2) AS SCR2,
(@var_SCR3 := @var_SCR3 + SCR3) AS SCR3,
(@rownum := @rownum + 1) AS COUNT
FROM classifier_results,
(SELECT @var_subj_diff := 0, @var_SCR2 := 0, @var_SCR3 := 0, @rownum := 0) AS vars
WHERE TIMESTAMP BETWEEN '2011-09-20' AND '2011-09-21'
ORDER BY TIMESTAMP ASC
2:
SELECT FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(TIMESTAMP) / (60 * 5)) * (60 * 5)) AS TIMESTAMP,
SUM(subj_diff) AS subj_diff, SUM(SCR2) AS SCR2, SUM(SCR3) AS SCR3, COUNT(*) AS COUNT
FROM classifer_results
GROUP BY TIMESTAMP
ORDER BY TIMESTAMP ASC
3:
SELECT FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(TIMESTAMP) / (60 * 5)) * (60 * 5)) AS TIMESTAMP,
(@var_subj_diff := @var_subj_diff + SUM(subj_diff)) AS subj_diff,
(@var_SCR2 := @var_SCR2 + SUM(SCR2)) AS SCR2,
(@var_SCR3 := @var_SCR3 + SUM(SCR3)) AS SCR3,
(@rownum := @rownum + 1) AS COUNT
FROM classifier_results,
(SELECT @var_subj_diff := 0, @var_SCR2 := 0, @var_SCR3 := 0, @rownum := 0) AS vars
GROUP BY TIMESTAMP
WHERE TIMESTAMP BETWEEN '2011-09-20' AND '2011-09-21'
ORDER BY TIMESTAMP ASC
Hope I understand correctly, and let me know it some problems show up. :)
A: Try this code -
Create and populale table:
CREATE TABLE classifier_results(
`TIMESTAMP` DATETIME NOT NULL,
subj_diff INT(11) DEFAULT NULL,
scr2 FLOAT(10, 5) DEFAULT NULL,
scr3 FLOAT(10, 5) DEFAULT NULL
);
INSERT INTO classifier_results VALUES
('2011-09-20 09:01:37', 1, 0.02000, 1.60000),
('2011-09-20 09:04:18', 3, 0.09000, 1.80000),
('2011-09-20 14:24:55', 5, 0.21000, 1.20000),
('2011-09-21 18:50:47', 8, 0.08000, 0.90000),
('2011-09-21 18:54:21', 9, 0.12000, 2.10000);
And execute these queries:
-- 1 query
SET @subj_diff = 0;
SET @scr2 = 0;
SET @scr3 = 0;
SET @cnt = 0;
SELECT timestamp,
@subj_diff:=IF(@subj_diff IS NULL, subj_diff, @subj_diff + subj_diff) subj_diff,
@scr2:=IF(@scr2 IS NULL, scr2, @scr2 + scr2) scr2,
@scr3:=IF(@scr3 IS NULL, scr3, @scr3 + scr3) scr3,
@cnt:=@cnt+1 count
FROM classifier_results;
+---------------------+-----------+---------+---------+-------+
| timestamp | subj_diff | scr2 | scr3 | count |
+---------------------+-----------+---------+---------+-------+
| 2011-09-20 09:01:37 | 1 | 0.02000 | 1.60000 | 1 |
| 2011-09-20 09:04:18 | 4 | 0.11000 | 3.40000 | 2 |
| 2011-09-20 14:24:55 | 9 | 0.32000 | 4.60000 | 3 |
| 2011-09-21 18:50:47 | 17 | 0.40000 | 5.50000 | 4 |
| 2011-09-21 18:54:21 | 26 | 0.52000 | 7.60000 | 5 |
+---------------------+-----------+---------+---------+-------+
-- 2 query
SELECT
DATE(timestamp) + INTERVAL 5 * (12 * HOUR(timestamp) + FLOOR(MINUTE(timestamp) / 5)) MINUTE new_timestamp,
SUM(subj_diff) subj_diff,
SUM(scr2) scr2,
SUM(scr3) scr3,
COUNT(*) count
FROM classifier_results
GROUP BY new_timestamp;
+---------------------+-----------+---------+---------+-------+
| new_timestamp | subj_diff | scr2 | scr3 | count |
+---------------------+-----------+---------+---------+-------+
| 2011-09-20 09:00:00 | 4 | 0.11000 | 3.40000 | 2 |
| 2011-09-20 14:20:00 | 5 | 0.21000 | 1.20000 | 1 |
| 2011-09-21 18:50:00 | 17 | 0.20000 | 3.00000 | 2 |
+---------------------+-----------+---------+---------+-------+
-- 3 query
SET @subj_diff = 0;
SET @scr2 = 0;
SET @scr3 = 0;
SET @cnt = 0;
SELECT new_timestamp timestamp,
@subj_diff:=IF(@subj_diff IS NULL, subj_diff, @subj_diff + subj_diff) subj_diff,
@scr2:=IF(@scr2 IS NULL, scr2, @scr2 + scr2) scr2,
@scr3:=IF(@scr3 IS NULL, scr3, @scr3 + scr3) scr3,
@cnt:=@cnt+1 count
FROM (
SELECT
DATE(timestamp) + INTERVAL 5 * (12 * HOUR(timestamp) + FLOOR(MINUTE(timestamp) / 5)) MINUTE new_timestamp,
SUM(subj_diff) subj_diff,
SUM(scr2) scr2,
SUM(scr3) scr3,
COUNT(*) count
FROM classifier_results
GROUP BY new_timestamp
) t;
+---------------------+-----------+---------+---------+-------+
| timestamp | subj_diff | scr2 | scr3 | count |
+---------------------+-----------+---------+---------+-------+
| 2011-09-20 09:00:00 | 4 | 0.11000 | 3.40000 | 1 |
| 2011-09-20 14:20:00 | 9 | 0.32000 | 4.60000 | 2 |
| 2011-09-21 18:50:00 | 26 | 0.52000 | 7.60000 | 3 |
+---------------------+-----------+---------+---------+-------+
Good luck!
A: It looks to me that you might want to delve into database programming using stored procedures and cursors.
Stored Procedures: http://dev.mysql.com/doc/refman/5.5/en/stored-programs-defining.html
Cursors: http://dev.mysql.com/doc/refman/5.5/en/cursors.html
This is a huge ball-o-wax which is beyond the scope of this post.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: iPad/iOS: Managing multiple full screen views? My app needs to switch between a couple of full screen views. These views are toggled by buttons in a custom overlay menu.
There are no tab bars or navigation bars visible. The transition between views may or may not be animated.
As I see it I can either use a single UIViewController and swap out subviews to get the desired effect or use multiple UIViewControllers and use of one Apple's containers (eg navigation controller, tabbar controller, etc), hide the navbar/tabbar and programatically switch "tabs" or push/pop controllers. The third option I suppose is to show each new view modally, but this doesn't feel right.
There is no 'order' in which the views are accessed, so my guess is the navigation controller approach won't really make sense.
Are there any major cons in either approach? Do you have any other suggestions? Will Apple reject the app if I hide the navbar or tabbar on navigation and tabbar controllers?
Thanks in advance for any advice you can offer.
A: I wouldn't use UINavigationController, modal windows, or a UITabBarController. The latter has some possibilities, but is too awkward in general use to be suitable.
Instead, try to use setRootViewController: on the window, as this is reasonably flexible with less overhead than the other approaches.
Choosing between multiple UIViewController subclasses or UIView swapping depends on how your app will be working in general. UIViews like to be separate, and restrict communication to your controller, but are great for more display oriented content.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++ function to chop very small numerical values Is there a C++ function that chops very small numerical values that appear due to approximations of the floating point numbers in the CPU to zero? I want to use this in complex number calculation, so it can appear in either the real or imaginary parts.
A: No such function exists. The problem is that "small" is relative. If you're working on very large numbers, 1.0 can be considered small enough to chop. Similarly, if you're working with small numbers, 10^-30 could still be considered significant.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem in Cakephp + WAMP Installation I am new to cakePHP And I am having a problem getting it working while using WAMP.
I have already copied cakephp folders/files into WAMP's www folder and DocumetRoot "C:\wamp\www\cakephp\app\webroot"
Is there more I need to do? I am getting a page when clicking on localhost from WAMP but it is showing many errors including:
Fatal error: Class 'Debugger' not found in
C:\wamp\www\cakephp\cake\libs\view\pages\home.ctp
Deprecated: Assigning the return value of new by reference is
deprecated in C:\wamp\www\cakephp\cake\libs\inflector.php
A: i think you downloaded the beta version of cake 2.0..
i have encountered that problem too..
you should use cakephp's stable versions...
cakephp 2.0 is now stable.....
A: Did you insert apache .htacces file into root directory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem with insert value in database with json_encode I want insert on a row of database table, following value with following php code(foreach) but after insert get following error, what do i do?
Values:
<div class="column">
<input type="text" name="start_date[1][]" value="1111">
<input type="text" name="end_date[1][]" value="1111">
<input type="text" name="price_change[1][]" value="1111">
</div>
<div class="column">
<input type="text" name="start_date[2][]" value="2222">
<input type="text" name="end_date[2][]" value="2222">
<input type="text" name="price_change[2][]" value="2222">
</div>
<div class="column">
<input type="text" name="start_date[3][]" value="3333">
<input type="text" name="end_date[3][]" value="3333">
<input type="text" name="price_change[3][]" value="3333">
</div>
Php code:
$residence_ups_input = $this->input->post('start_date');
$residence_upe_input = $this->input->post('end_date');
$residence_upc_input = $this->input->post('price_change');
var_dump($residence_ups_input); // output this is: nobool(false)
$residence_p = array();
foreach ($residence_ups_input as $idx => $name) { //line 134
$residence_p[] = array(
'start_date' => $residence_ups_input[$idx],
'end_date' => $residence_upe_input[$idx],
'price_change' => $residence_upc_input[$idx]
);
}
;
$data = array(
//'name' => $this -> input -> post('name'),
'residence_p' => json_encode($residence_p)
);
$this->db->insert('tour_foreign', $data);
Error:
A PHP Error was encountered Severity: Warning Message: Invalid
argument supplied for foreach() Filename: inser.php Line
Number: 134
A: replace
foreach ($residence_ups_input as $idx => $name) {
with
foreach (get_object_vars($residence_ups_input) as $idx => $name) {
you are passing an object to foreach, it wants an associative array. From now on do
json_decode($string, true)
instead of
json_decode($string)
and access the variable like this:
$var['key'];
instead of
$var->key
A: the $residence_ups_input variable is not an array
use this code :
array_push($residence_ups_input,$this->input->post('start_date'));
array_push($residence_upe_input,$this->input->post('end_date'));
array_push($residence_upc_input,$this->input->post('price_change'));
to get the values then use the foreach()
A: Change all columns:
<div class="column">
<input type="text" name="start_date[1][]" value="1111">
<input type="text" name="end_date[1][]" value="1111">
<input type="text" name="price_change[1][]" value="1111">
</div>
....
to:
<form method="post">
<div class="column">
<input type="text" name="start_date[]" value="1111">
<input type="text" name="end_date[]" value="1111">
<input type="text" name="price_change[]" value="1111">
</div>
....
</form>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android - Override method from higher API version and supporting lower API version I'd like to listen for a long key press in my Android application, and from Android 2.0 there is a method
public boolean onKeyLongPress(int keyCode, KeyEvent event)
to override. But what can I do if my app absolutely has to support API 4 (Android 1.6)? I know that I can call API methods with reflection, but I'm pretty sure that I cannot override with reflection.
A: Why don't you just remove @Override annotation above the method? Android 1.6 would ignore it, 2.0 would still interpret it correctly.
A: The easiest is to write two implementations of your custom view class, say:
MyCustomViewBasic extends View {
private MySharedImplementation impl;
}
MyCustomViewKeyLongPress extends View {
private MySharedImplementation impl;
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
// Do something exciting
}
}
These two implementations can share as many implementation details as possible, whilst ensuring that anything not available in API level 4 is not in the shared implementation.
Then have two xml layouts, one for API level 4 and one for API level 4 and above. Use MyCustomViewBasic in the layout for API level 4 and MyCustomViewKeyLongPress in the one for API level 4 and above
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How does unit of work class know which repository to call on commit? * Preface: I'm pretty new to the unit of work pattern *
My goal is to implement a unit of work class that will be able to keep track of all objects that have been changed throughout a given transaction. Everything I read about the unit of work pattern has it side by side with the repository pattern. So this is the approach I'd like to use.
Say for example I create a new User. On my unit of work object, I have a list of newly created objects, so I add my new User to this list. My user repository has a method titled Create, which takes in a User and calls a stored procedure to add the data to the database. When I call commit on my unit of work, how will it know which repository and method to call based on the list of new objects? Say it contains a User object and a Comment object. Both are newly created and need to be added on commit. I'm uncertain how to accomplish this.
Could somebody explain this a bit better and maybe even a small example if possible?
Thanks.
A: UnitOfWork is an infrastructural pattern that is already implemented by ORM, just like Identity Map. You don't have to reinvent the wheel. Repository on the other hand is a part of your domain model. Repository and UnitOfWork operate at different levels. UnitOfWork does not need to call Repository because it does not know what Repository is. It deals with different abstractions. It has a built-in cache of entities and it knows what state these entities are in. UnitOfWork however can be injected into Repository.
Proper implementation of UnitOfWork, IdentityMap, Change Tracking, Lazy loading is tedious. You should really be using existing ORM as an infrastructure layer that helps you keeping focus on what is important - domain.
A: This is typically implemented via change tracking , whatever action that happens on an entity the Unit of work/session/context is aware and performs the appropriate action on commit.
Change states could include New, Modified and Deleted.
check this link for more info.
It might help to use an implementation of it to get a better idea.
The entity framework implements the unit of work pattern. Maybe using it will let you understand it better.
A: One of most common ways of solving this is using inversion of control.
For example, you've your classes User and Comment, and you've implemented a generic repository IRepository<TDomainObject>. That's getting a repository of User or Comment is just giving the TDomainObject parameter:
*
*IRepository<User>
*IRepository<Comment>
Later you've configured who's implementing IRepository<User> and IRepository<Comment>, so if you use something like Microsoft Pattern & Practices' Common Service Locator, and we're in the body of commit method in your unit of work:
foreach(DomainObject some in NewObjects)
{
((IRepository<DomainObject>)ServiceLocator.Current.GetInstance(Type.GetType(string.Format("NamespacesToGenericRepository.IRepository`1[[{0}]]", some.GetType().FullName)))).Add(some);
}
Note IRepository<TDomainObject> has a contravariant TDomainObject generic parameter which type must inherit a base type of Domain Object called DomainObject, which permits an upcast of something like IRepository<User> to IRepository<DomainObject>.
In other words, your IRepository<TDomainObject> interface signature will look like this:
public interface IRepository<out TDomainObject>
where TDomainObject : DomainObject
This is just a summary and/or hint about how to implement locating the concrete repository so an unit of work of domain objects can manage ones of any specialized domain object.
If you want to learn more about inversion of control check this Wikipedia article:
*
*http://en.wikipedia.org/wiki/Inversion_of_control
And, because of my own experience, I'd like to suggest you Castle Windsor as inversion of control framework of choice:
*
*http://www.castleproject.org/container/
A: You have multiple approaches:
*
*Change tracking, by creating a UnitOfWork class that stores changes in memory till you ask to commit, an implementation could be: RegisterAdd(entity), RegisterDelete(entity), RegisterUpdate(entity), .... then Commit(); which will iterate through all registered changes and commit. (http://msdn.microsoft.com/en-us/magazine/dd882510.aspx)
*You can use TransactionScope as a distributed transaction to group all updates and commit at the end of unit of work. (how to implement Unit Of Work just using just TransactionScope and sqlconnections)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I see Objects Inside Heap & Stack in C#.Net Is it possible to see contents of stack and heap after every line of execution. I want to see it as it will give clear idea about memory allocation and deallocation in .Net. With your
If any document or link which will clear my doubts with your answer please share.
A: SOS or PssCor are a good place to start, along side WinDbg.
Once you've got that sorted out; attach WinDbg to your process, the load the debugger extension. For example:
.load C:\pathtoextensions\psscor4.dll
After that, you can issue the !dumpheap or !dumpstack commands.
The output of both of these commands is very raw. !dumpheap -stat will give you a "statistical" overview of your heap. The type, the number allocated, and the bytes in total for all allocations.
This isn't a super straightforward task. It'll take a while to get enough practice with WinDbg if you haven't used it before.
What you can do is set a breakpoint on a method using !bpmd, and use the commands mentioned above, then step over using the p command, and re-run the commands.
I'm sure there are other commercial tools like ANTS Profiler or dotTrace that may get the job done - but I don't have a lot of experience with either tool.
Once you've gotten started, you can ask (new) more specific questions about SOS or Psscor.
A: Stack:
var stackInfo = new StackTrace();
Heap? Nope, you'd need to use a profiler, debugger, or appropriate APIs. Not a straightforward task. If you try it and have difficulties, best to ask a more specific question.
A: You can also inspect the heap using the dotnet-dump tool:
*
*https://learn.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-dump
dotnet tool install --global dotnet-dump
dotnet-dump collect [-h|--help] [-p|--process-id] [-n|--name] [--type] [-o|--output] [--diag]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Servlets vs Beans I need advice from experienced developers regarding the software architecture of a project.
The need is to provide with a REST interface for an API so that a customer can :
1) authenticate themselves (this also involves handling account creation)
2) Issue get/add/update/delete() requests on resources (for example store a new book description [title+author..])
There is no need (for now) for WSDL or other complicated stuff. I'd say I prefer to avoid WSDL if possible, since I wont definitely use it. This won't be used for a website, only API direct use.
I've read many things but need a clear status on the following :
- Would you use servlets or beans ?
- to handle authentication, is going stateful a good idea ? What's the best and simple way to handle sessions ?
I'm looking for the easiest way to go, since my knowledge of J2EE is quite low at the moment.
Thanks for your time !
A: In a word? Both. You want both servlets and POJO interface-based beans, but not to do the same thing.
If you want REST, you'll use servlets. Those are the HTTP listeners in Java EE, and REST is based on HTTP.
With that said, I'd recommend using interface-based POJOs to implement the code that does all the work. It'll make your code easier to test and change.
REST is one deployment choice among many. If you stick with interface-based POJOs, you'll be able to change deployment strategy simply by using a different wrapping on the bean.
The REST layer should do nothing besides authentication and authorization, binding and validation. Let it defer to the POJO bean to get the work done.
Servlets handle sessions either with URL rewriting or cookies. Leverage what they give you.
But REST services should be stateless; no sessions, no state saved between calls.
You can use a Filter to check authentication before making the call. It's cross-cutting that way. Think of Filters as aspects for HTTP.
A: If the clients are going to be using a Web interface to get to your site, than a session based system is a better way to go. If it's just going to be a service api used by programs, then use HTTP Authentication.
If you're going for a service api, you would likely be best served by looking at one of the RESTy frameworks like JAX-RS. You can use this for an actual website, but it's not typically used that way (so the examples don't really match up to the domain).
If you're doing a website, then look at one of the action frameworks like Stripes or Struts 2. These will allow you to bind to RESTy URLs, but they're also great for doing web sites.
For any of these it would be better to have a base understand of Servlets, notably HTTP, the workflow, differences between redirects and forward, etc. since these frameworks leverage the basic Servlet model.
All of this can be done readily with raw Servlets, the frameworks just make things easier, and both the JAX-RS and Stripes/Struts 2 are pretty low impact to get going.
A:
authenticate themselves (this also involves handling account creation)
Servlets have built-in security capabilities as well as several libraries (Spring security, Apache Shiro).
There is no need (for now) for WSDL or other complicated stuff.
WSDL is most commonly used to describe SOAP web service.
Would you use servlets or beans ? - to handle authentication
You mean enterprise Java beans? They won't help you, you still need something to handle HTTP requests - where servlets come into play. But you will probably like to have something to implement the actual business logic - servlets are only gateway, don't implement logic there.
Technically you can expose EJB via SOAP (but you wanted REST) or use JAX-RS (part of Java EE stack), but obviously it uses servlets underneath.
is going stateful a good idea
In principle - REST is stateless, there is no conversational state. However authenticating on every request might cost too much. So you will at the end HTTP sessions (handled easily with servlets) at least to store JSESSIONID.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Open part of html page in UIWebView guys.
I want to load only part of web page, but I can't do it.
Man from Russian forum told, that I can use PHP, but I can't create this in my iOS app.
He send this code:
> <?php
> $url = "http://www.shesterenka.com";
> $unique_start = "<h1>";
> $unique_end = "</h1>";
> function weather($url, $unique_start, $unique_end) {
> $code = file_get_contents($url);
> preg_match('/'.preg_quote($unique_start,
> '/').'(.*)'.preg_quote($unique_end, '/').'/Us', $code, $match);
> return $match[1];
> }
> echo weather($url, $unique_start, $unique_end); ?>
Thank you very much.
Sorry for my bad English.
A: What part you want to load on UIWebView? If you know what content needs to be displayed on webView then load with loadHTMLString method. for example:
NSString* content = @"Hello World";
NSString* beforeBody = @"<html><head></head><body>";
NSString* afterBody = @"</body></html>";
NSString* finalContent = [[beforeBody stringByAppendingString:content]
stringByAppendingString: afterBody];
[webView loadHTMLString:finalContent baseURL:nil];
A: Here's a worked example for you. It uses All See Interactive to make the HTTP request.
In the header file I have:
#import <UIKit/UIKit.h>
#import "ASIHTTPRequest.h"
@interface testViewController : UIViewController <UIWebViewDelegate>{
UIWebView *webView;
}
@end
And in the implementation file I have:
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, self.view.frame.size.height)];
[webView setDelegate:self];
[webView setScalesPageToFit:YES];
NSURL *url = [NSURL URLWithString:@"http://www.shesterenka.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
self.view = webView;
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
NSString *unique_start = @"<h1>";
NSRange i = [responseString rangeOfString:unique_start];
NSString *unique_end = @"</h1>";
NSRange j = [responseString rangeOfString:unique_end];
if(i.location != NSNotFound && j.location != NSNotFound)
{
NSString *weather = [responseString substringFromIndex:i.location];
weather = [responseString substringToIndex:j.location];
[webView loadHTMLString:weather baseURL:nil];
} else {
NSLog(@"strings not found");
}
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
NSLog(@"Error: %@",error);
}
A: That isn't loading part of a web page, it is loading the entire html and returning part of it.
$code = file_get_contents($url); is reading the entire URL's html.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Regex to test whether there are more than two digits in a string As far as I know, \d{2,} matches 2 or more consecutive digits, but I need to know whether there are any 2 digits in a string.
I would also appreciate some good links to password strength meters.
What I use now is
function passwordStrengthPercent(pwd,username)
{
var score = 0, special = /(.*[!,@,#,$,%,^,&,*,?,_,~,;,:,`,|,\\,\/,<,>,\{,\},\[,\],=,\+])/
if (pwd.length < 8 ) return 0
if (pwd.toLowerCase() == username.toLowerCase()) return -1
score += pwd.length * 4
score += ( checkRepetition(1,pwd).length - pwd.length )
score += ( checkRepetition(2,pwd).length - pwd.length )
score += ( checkRepetition(3,pwd).length - pwd.length )
score += ( checkRepetition(4,pwd).length - pwd.length )
if (pwd.match(/(.*[e].*[e].*[e])/)) score -= 15//most common letter in passswords?
if (pwd.match(/(.*[a].*[a].*[a])/)) score -= 15//most common letter in passswords?
if (pwd.match(/(.*[o].*[o].*[o])/)) score -= 10//most common letter in passswords?
if (pwd.match(/^\l+$/) || pwd.match(/^\d+$/) ) return score/2//there was w here in regexp
if (pwd.match(/(.*[0-9].*[0-9].*[0-9])/)) score += 10
//todo additional rules 11
if (pwd.match(special)) score += 15
if (pwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) score += 15
if (pwd.match(/(w)/) && pwd.match(/(d)/)) score += 15
if (pwd.match(special) && pwd.match(/(d)/)) score += 10
if (pwd.match(special) && pwd.match(/(w)/)) score += 10
if ( score < 0 ) return 0
if ( score > 100 ) return 100
return score
}
A: You can try
^.*\d.*\d.*$
which will only match if (at least) two digits are included.
A: You can just use:
\d.*\d
That matches two numerals anywhere in the line, even with other characters between them.
A: check if there are Exactly two digits:
^[^\d]*\d[^\d]*\d[^\d]*$
see the test with grep:
kent$ echo "23
2 3
ax3x2x
aaaaa23
a222
2
3x3x4
3 4 5"|grep -P "^[^\d]*\d[^\d]*\d[^\d]*$"
23
2 3
ax3x2x
aaaaa23
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQL Server - Data deletion issue I currently got 2 DEV SQL Servers which is used by 4 Developers for their day to day work.
Yesterday, data out of few tables on DEV instance got deleted
Now I'm struggling how to track back who had deleted the data as everybody is saying they haven't deleted the data. Only failed login auditing was enabled on SQL Server
How can we track back - who deleted the data on that SQL SERVER?
Is there any way moving forward, I can keep track of DELETE/DROP statement which someone is executing on SQL SERVER
Regards
A: Unless you have some form of auditing on that database or these tables, there's no way to find out who exactly did that.
If you want to be able to know who did it, then implement DML triggers to send auditing data to audit tables.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery chunk not running I have the following jquery below. When the user clicks .commentCount, I want this div called #commentSec to open up, and then some other elements on the site change. This jquery chunk runs fine.
However, the second chunk, onclick of a close button called .closeComments, doesn't run at all. What am I doing wrong? Do I have to return true or something in the first jquery section?
$('.commentCount').click( function() {
$('#commentSec').css({ 'display' : 'inline', 'height' : 'auto', 'padding' : '10px', 'padding-bottom' : '0px', 'margin-bottom' : '10px', 'margin-left' : '10px', 'z-index' : '10'});
$('#commentSec h3').css({ 'display' : 'block'});
$('#rightcolumn').css({ 'opacity' : '.3'}); //Transparent rightcolumn
});
Second Chunk:
$('.closeComments').click( function() {
$('#commentSec').css({ 'display' : 'none'});
$(this).css({'opacity' : '.9'});
$('#rightcolumn').css({ 'opacity' : '1'}); //Undo transparent rightcolumn
});
HTML/PHP:
<h3><b>' . $useranswering . '\'s</b> ANSWER</h3><img class="closeComments" src="../Images/bigclose.png" alt="close"/>
<span><a class="prev" >← previous answer</a><a class="next" href="">next answer →</a></span>
<div>
<p>' . $answer . '</p>
<form method=post>
<input type="hidden" value="'. $ansid .'" name="answerid">
<textarea rows="2" cols="33" name="answercomment">Comment on this answer</textarea>
<input type="image" src="../Images/commentSubmit.png"/>
A: only issue that comes to my mind is that probably you might have multiple [XX comments] links, and having multiple [commentsSec]
now, you can only have one block with one ID. here is perfectly working example:
<style>
.comment { display: none;}
</style>
<div class="comment-container"><span class="open-comment">[xx comments]<
<div class="comment">Lorem Ipsum<span class="close-comment">[close]<
</div>
<div class="comment-container"><span class="open-comment">[xx comments]<
<div class="comment">Lorem Ipsum<span class="close-comment">[close]<
</div>
<script>
$(document).ready(function(){
$(".open-comment").click(function(){
$(this).parent().find(".comment").show({duration: 1000});
});
$(".close-comment").click(function(){
$(this).parent().hide({duration: 1000});
});
});
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript Stopwatch not starting at zero I've got a basic stopwatch here, but the problem is I think it begins counting when the page loads as opposed to when the start button is clicked. Likewise, when you reset and start again the same problem happens.
<form>
<input type="button" value="Start count!" onclick="doTimer()" />
<input type="text" id="txt" />
<input type="button" value="Stop count!" onclick="stopCount()" />
<input type="button" value="Reset!" onclick="resetCount()" />
</form>
<script type="text/javascript">
var start = new Date().getTime();
var elapsed = '0.0';
var t;
var timer_is_on=0;
function timedCount() {
var time = new Date().getTime() - start;
elapsed = Math.floor(time / 100) / 10;
if(Math.round(elapsed) == elapsed) { elapsed += '.0'; }
document.getElementById('txt').value=elapsed;
t=setTimeout("timedCount()",50);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on=1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on=0;
}
function resetCount() {
document.getElementById('txt').value='0.0';
var elapsed = '0.0';
}
</script>
I've tried defining the start variable onclick of the start button but not had much success so far. Any help is much appreciated thank you.
A: The problem you're having is your recording the start as soon as the page loads instead of when the user actually clicks on the start button. To record the start when the user actually clicks on the button change your doTimer function to the folowing
function doTimer() {
if (!timer_is_on) {
start = new Date().getTime();
timer_is_on=1;
timedCount();
}
}
A: You'll have to include another reset in doTimer():
function doTimer() {
if (!timer_is_on) {
start = new Date().getTime();
timer_is_on=1;
timedCount();
}
}
See the running version here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP Regex: Replace anything that isn't a dot or a digit? I'm trying to see if a string is an IP address. Since IPv6 is rolling out it's better to support that too, so to make it simple, i just want to replace anything that isn't a dot or a number.
I found this regex on stackoverflow by searching:
\d+(?:\.\d+)+
but it does the opposite of what i want. Is it possible to inverse that regex pattern?
Thanks!
A: Try the following:
[^.0-9]+
Matches anything that is not a dot or a number
A: This regex will match anything that isn't a dot or a digit:
/[^\.0-9]/
A: I might try something like this (untested):
Edit:
Old regex was way off, this appears to do better (after testing):
find: .*?((?:\d+(?:\.\d+)+|))
replace: $1
do globally, single line.
In Perl: s/.*?((?:\d+(?:\.\d+)+|))/$1/sg
A: Regex shortcuts are case sensitive. I think you were trying to do something like this, but what you want is capital D
[\D] = any non-digit.
in php it looks like this:
preg_replace('/[\D]/g', '', $string);
javascript its like this:
string.replace(/[\D]/g, '');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: LookupEdit in XtraGrid cell value goes blank This is what I have:
public class ViewModel
{
public BindingList<Row> Rows { get; set; }
public BindingList<MyElement> Selectables { get; set; }
}
public class Row
{
public MyElement Selected { get; set; }
}
public class MyElement
{
public string Value { get; set; }
public string Friendly { get; set; }
}
This is what I want:
An XtraGrid with a column that has a combobox editor in each cell. The values of the dropdown options are different for different rows. Specifically the available options are subsets of ViewModel.Selectables, the subset is defined by businessrules at runtime.
This is how I try to make this happen:
I create three BindingSources
*
*viewModelBindingSource: with DataSource = ViewModel
*rowsBindingSource: with DataSource = viewModelBindingSource AND DataMember = Rows
*selectablesBindingSource with DataSource = viewModelBindingSource AND DataMember = Selectables
I set the grid's DataSource to rowsBindingSource.
I create an In-place Editor Repository for a LookupEdit in the grid.
I set the repositoryItemLookUpEdit's DataSource to selecteablesBindingSource
I set the repositoryItemLookUpEdit as the ColumnEdit value of the column
I hook up to gridViews ShownEditor event:
this.gridView1.ShownEditor += gridView1_ShownEditor;
In gridView1_ShownEditor(object sender, EventArgs e) method I can then have a reference to the view so I can do something like this:
GridView view = sender as GridView;
var newSelectables = new BindingList<MyElement>();
// businesslogic to populate newSelectables ...
var bs = new BindingSource(newSelectables, "");
edit = (LookUpEdit)view.ActiveEditor;
edit.Properties.DataSource = bs;
This works to the extent that I get the new options in the clicked combobox, and selecting the option sets the value to the bound object, that is Row.Selected.
And now to my problem, when cell looses focus, the cell content turns blank.
This seems to be caused somehow by the fact that I create a new BindingSource with new, because if I ommit this change of DataSource then the values in ViewModel.Selectables are used instead, and it works as expected.
So, does anyone know why the text displayed in the cell goes blank after it looses focus in this case??
A: I had the same issue few days back but i didn't find any solution for it. What i understood from it is that the values you are binidng to the grid column containing ComboEdit or LookupEdit must match the Vlaue Member value of the ComboEdit/LookUpEdit Collection.
If it gets find the matched value than it'll show the display member value in the cell otherwise the cell value will be blank.
This is what i got from my working experience on it.
A: I had a similar problem. In my case the problem was due to changing DataSource property of repositoryItemLookupEdit in the column.
When new DataSource in current row is more restricted and is not able to show other row's values, cells in those rows go blank.
To resolve this,
You may use the ShownEditor event and the code sample in the link below:
http://documentation.devexpress.com/#WindowsForms/DevExpressXtraGridViewsBaseColumnView_ShownEditortopic
The trick is,
Instead of setting the DataSource of repositoryItemLookupEdit, you get the view.ActiveEditor as a LookupEdit and set its DataSource. Then, other rows are not affected.
Here is a code sample:
void eAdvBandedGridView1_ShownEditor(object sender, EventArgs e)
{
GridView view = sender as GridView;
if (view.FocusedColumn.FieldName == "CenterID" && view.ActiveEditor is LookUpEdit)
{
LookUpEdit editor = view.ActiveEditor as LookUpEdit;
vVoucherItemInfoDTO item = view.GetFocusedRow() as vVoucherItemInfoDTO;
if (lastFetchedAccount == null || lastFetchedAccount.ID != item.AccountID)
{
lastFetchedAccount = accountServiceClient.GetAccountInfo(item.AccountID);
}
if (lastFetchedAccount.AllowAllCenters)
editor.Properties.DataSource = GlobalDataStore.CenterList;
else
editor.Properties.DataSource = lastFetchedAccount.AllowedCenterList;
}
}
A: Ok so I figured part of it. I am not EXACTLY sure why the content goes blank. But it has to do with the fact that I had instantiated new objects that populate the list newSelectables.
I guess that when the cell looses focus, the XtraGrid turns to the original repositoryItemLookUpEdit which points to ViewModel.Selectables to get the DisplayValue of the item. Since the selected item doesn't exist in the original list this fails. If I reuse the original objects instead of cloning them it seems to work.
A: You can override this behavior by adding an event handler on the Editor associated with the combobox. eg
private void goalTypeEditor_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
{
if (e.DisplayText == "")
{
string goalTypeId = (string)e.Value;
RefDataSet refData = ((IParentView)ParentView).RefData;
string goalTypeLabel = refData.GoalType.FindByGoalTypeID(goalTypeId).Label;
e.DisplayText = "(No longer in use) " + goalTypeLabel;
}
}
A: *
*Set DisplayMember of the LookUp to the name of the column that you wanna show
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Unable to align views properly I've been trying to successfully align the views so they look the same on other phones but I can't succeed. I just can't get it to work. Here is the background:
I want a TextView in the middle of the green zone, and in the middle of the blue zone, and an imageview in the orange zone. I already asked this and I got a suggestion to use layout_weight here. But I can't correctly calculate the weight. How can I do this? Is the layout_weight is the right way to go? how do I calculate it?
The measures:
The left and right side of the screen (yellow) are empty.. 40 px each..
The green zone have a TextView at the centrer .. 236 px
The orange zone has an imageview at the center .. 44 px
The blue zone has a TextView at the center .. 120 px
The xml I used for the custom_row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:orientation="horizontal"
android:layout_height="wrap_content" android:paddingTop="10dip" android:paddingBottom="10dip">
<TextView android:id="@+id/Start_Numbering" android:textSize="19.5dip"
android:layout_width="0dp" android:layout_height="wrap_content"
android:layout_weight="0.3" android:background="@drawable/list_number_bg"
android:gravity="center"
/>
<ImageView android:id="@+id/Start_ImageView"
android:layout_weight="0.1" android:layout_height="fill_parent" android:scaleType="center"
android:layout_width="0dp" android:src="@drawable/list_noaudioavailable"
android:gravity="center"
></ImageView>
<TextView android:id="@+id/Start_Name" android:textColor="#a7e9fe"
android:textSize="25dip" android:layout_width="0dp"
android:layout_weight="0.6"
android:gravity="center" android:background="@drawable/list_name_bg"
android:layout_height="wrap_content" />
A: If you want your layout to be flexible for different screen sizes then you DON'T want to hard code pixel widths instead you should use layout_weights as was the answer in your previous question. For a ViewGroup you can define a total weightSum and then the individual weights must be defined for each of the children which must add up to the weightSum of the parent. Here is a simple example that is similar to what you described above using black and white colors:
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="20">
<View android:id="@+id/view1"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:background="@android:color/white"/>
<View android:id="@+id/view2"
android:layout_weight="7"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:background="@android:color/black"/>
<View android:id="@+id/view3"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:background="@android:color/white"/>
<View android:id="@+id/view4"
android:layout_weight="7"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:background="@android:color/black"/>
<View android:id="@+id/view5"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:background="@android:color/white"/>
</LinearLayout>
The measures:
The left and right side of the screen (yellow) are empty.. 40 px each..
The green zone have a TextView at the centrer .. 236 px
The orange zone has an imageview at the center .. 44 px
The blue zone has a TextView at the center .. 120 px
just convert those pixels vales into width valuse and use the sum of those pixels values as the weightSum in the parent
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can we use `LoadLibrary ` having our application compiled with Visual Studio 2010 and static runtime? What I want is simple - have C++ application that would be compiled with static runtime ( /MT, /MTd flags ) and be capable to open, call, etc classes and thare functions from DLLs (using LoadLibrary, C++). Is such thing possible?
A: It is not impossible. But making it universal and reliable is a very long distance shot. There is no standardized metadata format in C++ that lets you know that you are passing the correct arguments. Even the name of the exported class or function isn't easily guessable, it is a compiler implementation detail.
COM Automation would be an example where these problems are solved. Covered by the ActiveX Test Container. Or the reflection support in languages like Java or .Net managed languages. Not C++.
A: I think you're mixing things up. Just because it's called a "static" runtime, it just means that the code for standard C and C++ libraries is statically linked into your application. In general, this will never put any limitations on what your application can do.
All of the standard library classes like ifstream and functions like printf will be usable whether their code is inside your EXE in the static runtime, or outside your EXE in the dynamic runtime. All of the Win32 functions like LoadLibrary and GetProcAddress are always outside of your application in regular Windows DLLs (like Kernel32.dll), so they certainly aren't affected by your runtime choice.
I'd say that your real problem is trying to call C++ methods using GetProcAddress. That Win32 API is only meant for dynamically calling C functions. The first problem that you'll hit is that you won't be able to find names of methods due to C++'s name mangling. You might also have problems allocating objects. My intuition tells me that it would be almost impossible to get working correctly.
Here are three suggested alternatives in place of directly calling C++ methods using GetProcAddress:
*
*Wrap your C++ methods in C functions.
*Use a C++ framework like COM or Qt plugins to set up dynamic DLL interfaces.
*Use a different platform such as .NET or Java; one that has full support for object-oriented reflection and dynamic invocation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using the Dictionary method in C# I am currently using the Dictionary method in C# to index a text file successfully, although in this case I would like to index more than one keyword (#HostName). I have tried adding an additional IF statement to the method although it doesn't appear to work - by that I mean it seems to break the whole method.
var dictionary = new Dictionary<string, string>();
var lines = File.ReadLines("probe_settings.ini");
var ee = lines.GetEnumerator();
while (ee.MoveNext())
{
if (ee.Current.StartsWith("#PortNo"))
{
string test = ee.Current;
if (ee.MoveNext())
{
dictionary.Add(test, ee.Current);
}
else
{
throw new Exception("File not in expected format.");
}
}
}
Is it possible to index another term in this method? How could it be done?
Below is the file it is reading:
#CheckName1
HTTP Check
#PortNo1
80
#CheckName2
HTTPS Check
#PortNo2
443
A: Do you mean another test using else if besides if (ee.Current.StartsWith("#PortNo"))? I don't see why not. Post (some more) code.
A: while (ee.MoveNext())
{
if (ee.Current.StartsWith("#MatchOne") || ee.Current.StartsWith("#MatchTwo"))
{
string test = ee.Current;
if (ee.MoveNext() && !dictionary.ContainsKey(test))
{
dictionary.Add(test, ee.Current);
}
else
{
throw new Exception("File not in expected format.");
}
}
}
or use for loop
for( int i =0 ; i < lines.length -1 ;i++)
{
if (!string.IsNullOrEmpty(lines[i]) && lines[i].StartsWith("#MatchOne") || lines[i].StartsWith("#MatchTwo"))
{
string test = lines[i];
if ( !dictionary.ContainsKey(test))
{
dictionary.Add(test, lines[i+1]);
}
else
{
throw new Exception("File not in expected format.");
}
}
}
A: You could use Linq and its ToDictionary() method instead - this would create a dictionary using any line that start with # as key, and the next line as value:
var lines = File.ReadAllLines("probe_settings.ini");
var dictionary = lines.Zip(lines.Skip(1), (a, b) => new { Key = a, Value = b })
.Where(l => l.Key.StartsWith("#"))
.ToDictionary(l => l.Key, l => l.Value);
There's some overhead involved since this will iterate over the file twice (because is using Zip()) but that shouldn't matter for a rather small configuration file.
You can use the dictionary then like this:
string someValue = dictionary["#CheckName2"]; //returns "HTTPS Check"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Help needed in SQL Query-Update I have a Table Called Student_Details which contains the following columns:
ID, Roll_No, Student_Name, Student_Address, Student_Class.
ID is the primary key.
I have a problem where the record of every student is split into two rows.
For example, the first row contains: 1, 20, john, '', '', and the second
'2', '', '', 'ABCDEFG', 'A'.
I want to update the data in the Student_Address and Student_Class
fields in the row with ID 1 from the data in row 2, and then
delete row 2. The result in the example would be 1,20,'john',
'ABCDEFG', 'A'.
Is there any way to do this? I do not want to use a cursor, because
the database has around 50000 rows.
A: Do not have SQL Server installed, but made this work in MySQL using standard SQL syntax so it should work with you too.
Note, that I created 2 update-s for each column as MySQL does not seem to support the UPDATE table SET (col1, col2) = (<a subquery with 2 columns>) syntax.
I also wrap UPDATE subquery in another one, which is only necessary because of some MySQL restriction.
The 3 queries should probably be run in one transaction:
update student_details s0 set s0.student_address =
(
select student_address from (
select s1.id, s1.roll_no, s2.student_address
from student_details s1
join student_details s2
on s2.id=s1.id+1
) sub where sub.id = s0.id
)
where s0.roll_no <> '';
update student_details s0 set s0.student_class =
(
select student_class from (
select s1.id, s1.roll_no, s2.student_class
from student_details s1
join student_details s2
on s2.id=s1.id+1
) sub where sub.id = s0.id
)
where s0.roll_no <> '';
delete from student_details where roll_no='';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Python Exception handling when Importing First file:
class E1Exception (Exception):
def __init__(self,x):
self.x=x
def raiser (self,x):
self.x=x
if x=='So sue me':
raise E1Exception('New Yorker')
else:
try:
number = (int)(x)
pass
except ValueError:
raise ValueError ()
Second file:
import e1a
from e1a import *
def reporter (f,x):
try:
print f(x)
return ('no problem')
except ValueError:
return ('Value')
except E1Exception:
return ('E1')
else:
return ('generic')
Question 1:
Does the function raiser have to be static in order to be used in the second file?
The problem is the E1Exception is never caught any solution?
A: The problem is that the error is never "raised"
http://docs.python.org/tutorial/errors.html
You have to write raise E1Exception(x) somewhere with some x value.
A:
Does the function raiser have to be static in order to be used in the
second file?
Python doesn't have a concept of "static". What do you mean by "static"?
Also, I don't think you realize what (int)(x) is doing. That looks to me like you're trying to cast x as an int. And although it works, it's only by coincidence. What you're really doing is invoking the int function on x. So that is equivalent to
number = int(x)
That's not related to your questions, but I thought I should point that out in case anyone gets confused.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jquery add line break and truncate + add "..." after x amount of characters I'm trying to figure out a way to accomplish 2 things:
1. A line break after 4 characters or first word.
2. Truncate + add "..." (only if the amount of characters exceed 20 characters)
Example: 2008 WALKER STATION THE BRIDGE 1.5L
Would like it to display:
2008
WALKER STATION ...
I need #1 to happen every time, but only #2 if the text is more 20 characters.
I've got the line breaking down with the following code:
$(window).load(function(){
$(".wine-name").each(function() {
var html = $(this).html().split(" ");
html = html[0] + "<br>" + html.slice(1).join(" ");
$(this).html(html);
});
HTML:
<div class="wine-name">2008 WALKER STATION THE BRIDGE 1.5L</div>
A: One way of doing this is to use:
var string, p1,p2,p3;
$('.wine-name').each(
function(){
string = $(this).text();
p1 = string.substring(0,4);
p2 = string.substring(5);
if (p2.length > 20){
p3 = p2.substring(0,19) + '...';
p2 = p3;
}
newString = p1 + '<br />' + p2;
$(this).html(newString);
});
JS Fiddle demo.
A: Here you go:
$( '.wine-name' ).each( function () {
var words, str;
words = $( this ).text().split( ' ' );
str = words.shift() + '<br>';
while ( words.length > 0 && ( str.length + words[0].length ) < 24 ) {
str += ' ' + words.shift();
}
if ( words.length > 0 ) {
str += ' ...';
}
$( this ).html( str );
});
Live demo: http://jsfiddle.net/XpmpQ/1/
A: Well, you may set up it the CSS way using text-overflow property which is pretty weill supported (but not in FF for some strange reason), depending on your needs, the CSS way (without any script) would do the job, or even better. Have a look at Google by searching text-overflow ellipsis if you don't know what I'm talking about.
Sorry to bother if you already know this, I just pointed out an alternative that I thought would help.
A: I think you are looking for something like this:
var s = "2008 hello world";
// Find the index of the first space or use 4
var i = Math.min(4, s.indexOf(" "));
var part1 = s.substr(0, i);
var part2 = s.substr(i);
// Add ellipsis if part2 is longer than 5 characters
if (part2.length > 5) part2 = part2.substr(0, 5) + '..';
// Output for testing
alert('"' + part1 + '", "' + part2 + '"');
jsFiddle demo
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cakephp containable order not working I am using cakephp containable to retrieve related models
$this->Order->find('first',
array(
'conditions'=>$conditions,
'contain' =>
array(
'OrderItem'=>array(
'Item'=>
array(
'order' => array('Item.item_number ASC')
)
),
'Location','Campaign', "Customer")
)
);
I'm using this to generate an invoice, and would like to have the items sorted by item_number.
But for some reason the sort isn't working.
Any ideas?
The SQL generated is very long. but you can see the issue from this snippet that the order by is in the wrong query - - ie in the Item which is being select by id -- only one item. (And there is a seperate query for each item in the order. )
SELECT `OrderItem`.`order_id`, `OrderItem`.`item_id`,
`OrderItem`.`quantity`, `OrderItem`.`id` FROM `order_items` AS `OrderItem` WHERE
`OrderItem`.`order_id` = (3144)
And
SELECT `Item`.`id`, `Item`.`campaign_id`, `Item`.`item_number`, `Item`.`description`,
`Item`.`order_unit`, `Item`.`order_price`, `Item`.`maxQuantity`, `Item`.`sale_unit`,
`Item`.`sale_price`, `Item`.`approx`, `Item`.`min_weight`, `Item`.`max_weight`,
`Item`.`avail`, `Item`.`filename` FROM `items` AS `Item` WHERE `Item`.`id` = 122
ORDER BY `Item`.`item_number` ASC
What I would like to see is the first query do a inner join Items.id on OrderItem.item_id and order that query by item_number, but I see that containable generates separate queries for each related model.
A: Make sure you have added:
var $actsAs = array('Containable');
to the Model, or
$this->Order->Behaviors->attach('Containable');
to the action. It isn't clear from your post if you have this already.
Also you should elaborate on isn't working - what isn't? Unexpected results? nothing at all?
A: You might want to try Linkable instead:
https://github.com/Terr/linkable
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cannot send Image data type from web service I use this lines of code in web service to send data:
byte[] bajtat = (byte[])dr["Logo"];
MemoryStream ms = new MemoryStream(bajtat, 0, bajtat.Length);
ms.Write(bajtat, 0, bajtat.Length);
Image img = Image.FromStream(ms, true);
var partite = new Partite
{
EmriPartite = dr.GetString(2),
/*
* SqlDataReader.GetString - gets the value of the specified column as a string
*/
NrPartive = dr.GetInt32(1),
Akronimi = dr.GetString(4),
Foto = img
};
and it shows me error:
System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type System.Drawing.Bitmap was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
at
A: There should not be any problem in sending image data as byte[] from WebService using WCF technology. You can use [DataMember] byte[] for you DataContract class. Read the image data completely to byte[] field. And send using WCF service.
At the receiving part in WP7, you can have
< Image Source={Binding MyImageSource} />
Where MyImageSource is a BitmapSource Type.
And you can set its instance .SetSource(new MemoryStream(buffer, 0, buffer.Length));
Where buffer is the byte[].
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript class change doesn't change CSS3 gradient in Chrome I have a simple div with a CSS3 gradient as background, its original background is declared from a CSS file, where I also declare that this div with another class should have another CSS3 gradient as background. When adding the class to the div with JavaScript the background changes as it should in Firefox, but stays as it was in Chrome. I know the class is added because other styles of the class change as they should.
You can see it in the example here.
A: The CSS is just inconsistent. There needs to be alpha on each of the gradients if you want the same effect in each browser. This works in chrome. http://jsfiddle.net/gradbot/vQZtu/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Not able to create new Firebird database I am new to Firebird. I installed Firebird Superserver 2.5 with "Install as application" option. I also installed FlameRobin GUI front-end. When I am trying to create a new database with SYSDBA username and masterkey as password, it displays following error:
I am installing on Windows 7 and want to use it on a single PC.
A: Well, is the server running? If you installet it as a application and server is running then there should be FireBird icon in the system tray. If there isn't then start the server, ie execute command line
fbserver.exe -a
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get an Answer from a web service after sending Get request in iOS I'm a novice in iOS developing, and have some problems with understanding web service organization. I want to send a Get query to the URL. And I do it so:
-(BOOL) sendLoginRequest{
NSString *getAction = [NSString stringWithFormat:@"action=%@&username=%password=%@",@"login",self.log.text, self.pass.text];
NSString *getUserName = [NSString stringWithFormat:@"username=%@",self.log.text];
NSString *getPassword = [NSString stringWithFormat:@"username=%@",self.pass.text];
NSData *getDataAction = [getAction dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getLengthAction = [NSString stringWithFormat:@"%d", [getDataAction length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http:http://www.site.fi/api/"]];
[request setHTTPMethod:@"GET"];
[request setValue:getLengthAction forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:getLengthAction];
self.urlConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
NSAssert(self.urlConnection != nil, @"Failure to create URL connection.");
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
the answer may be "true" or "false"
but how can I take this answer?
A: Send [self.urlConnection start]; and implement the NSURLConnectionDelegate methods to receive the response. Alternatively use ASIHTTPRequest and the block handlers, which to my way of thinking are much easier to write for beginners, provided you don't need to run on iOS pre-4.1.
You will gather the data returned as NSData; just convert that to a string, and either call boolValue on the string (check the docs for its rather strange tests), or use a specific set of your own tests.
A: You should define next methods to get answer:
*
*Start connection: [self.urlConnection start];
*Check server response:
- (void)connection:(NSURLConnection *)theConnection didReceiveResponse:(NSURLResponse *)response
*Collect data that servers sends you:
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data
*Be sure to manage errors:
- (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error
*Check received data:
- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection
To be more sure that you correctly understood me check NSURLConnection Class Reference
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting Street address in android using GPS and google maps I wan't to get the street name that I'm standing in using the GPS of my android and google maps.
can you please help me?
thank you
A: Use the Geocoder class - there's some useful functions like getFromLocation for example. Give the method longitude and latitude and function returns list of addresses that are known to describe the area immediately surrounding the given latitude and longitude. More information about Geocoder class
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++ Custom "List" implementation doesn't work I tried to create a list container with similar access of elements in c++ as in C#
I'm totally lost now because my main method first printed weird numbers.
The RList class should be like:
RList<ClassName or Primitive> VariableName;
VariableName.AddData(Class or Primitive);
VariableName[IndexOfElement] get the element
VariableName.RemoveAt(IndexOfElement) remove element
Can you tell me where I went totally wrong?
int main()
{
RList<int> Numbers;
Numbers.AddData(5);
Numbers.AddData(100);
Numbers.AddData(1500);
for (unsigned int x = 0; x < Numbers.GetLength(); x++)
{
cout << Numbers[0] << endl;
}
cin.get();
return 0;
}
Here is the Header file. I read that you have to put everything in header if you work with template.
#ifndef RList_H
#define RList_H
#include <new>
template <class T> class RList
{
private:
unsigned int m_Length;
T* ListObject;
void AllocateNew(T obj);
void RemoveIndex(unsigned int N);
public:
RList();
~RList();
void AddData(T obj);
void RemoveAt(unsigned int N);
unsigned int GetLength() { return m_Length; }
T operator[](unsigned int N){if (N < m_Length && N >= 0) {return (ListObject[N]);} return NULL; }
};
template <class T>
RList<T>::RList()
{
this->m_Length = 0;
}
template <class T>
RList<T>::~RList()
{
delete[] this->ListObject;
}
template <class T>
void RList<T>::AddData(T obj)
{
this->AllocateNew(obj);
this->m_Length++;
}
template <class T>
void RList<T>::RemoveAt(unsigned int N)
{
if( N < this->m_Length && N >= 0)
{
if ((this->m_Length - 1) > 0)
{
this->RemoveIndex(N);
this->m_Length--;
}
else
{
throw "Can't erase last index!";
}
}
}
template <class T>
void RList<T>::AllocateNew(T obj)
{
if (this->m_Length == 0)
{
this->ListObject[0] = obj;
}
else
{
T* NewListObject = new T [this->m_Length + 1];
for (unsigned int x = 0; x < this->m_Length; x++)
{
NewListObject[x] = this->ListObject[x];
}
NewListObject[this->m_Length] = obj;
delete [] ListObject;
this->ListObject = NewListObject;
delete [] NewListObject;
}
}
template <class T>
void RList<T>::RemoveIndex(unsigned int N)
{
T* NewListObject = new T [this->m_Length - 1];
for (int x = 0; x < this->m_Length -1; x++)
{
if (x != N)
{
NewListObject[x] = this->ListObject[x];
}
}
delete [] ListObject;
this->ListObject = NewListObject;
}
#endif // RList_H
A: Lots of problems:
*
*Constructors should initialize all members
*Rule of three not implemented (on owned pointers).
*Horrible spacing (you need to format that code better).
*All your array memory allocation is wrong.
Allocate:
template <class T>
void RList<T>::AllocateNew(T obj)
{
if (this->m_Length == 0)
{
// This will not work as you have not allocated the area for ListObjects.
// I don't think this is a special case. You should have allocated a zero
// length array in the constructor then then else part would have worked
// like normal when adding the first element.
this->ListObject[0] = obj;
}
else
{
// OK good start
T* NewListObject = new T [this->m_Length + 1];
// Rather than do this manually there is std::copy
for (unsigned int x = 0; x < this->m_Length; x++)
{
NewListObject[x] = this->ListObject[x];
}
NewListObject[this->m_Length] = obj;
// Though unlikely there is a posability of an exception from a destructor.
// So rather than call delete on a member you should swap the member and the
// temporary. Then when the object is a good state you can delete the old one.
delete [] ListObject;
this->ListObject = NewListObject;
// Definately do NOT do this.
// as you have just stored this pointer into ListObject.
// ListObject is now pointing at free'ed memory.
delete [] NewListObject;
// So I would have done (for the last section
// std::swap(this->ListObject, NewListObject);
// ++this->m_Length;
// // now we delete the old data
// delete [] NewListObject; // (remember we swapped above)
}
}
RemoveIndex
template <class T>
void RList<T>::RemoveIndex(unsigned int N)
{
T* NewListObject = new T [this->m_Length - 1];
for (int x = 0; x < this->m_Length -1; x++)
{
if (x != N)
{
// You need to compensate for the fact that you removed one
// element (otherwise you have a hole in your new array).
NewListObject[x] = this->ListObject[x];
}
}
// Same comment as above.
// Do not call delete on a member.
// Make sure the object is a good state before doing dangerous stuff.
delete [] ListObject;
this->ListObject = NewListObject;
}
A: if (this->m_Length == 0)
{
this->ListObject[0] = obj;
}
You have to allocate ListObject before you can do this.
Note: there are many problems with your implementation, you should post it to codereview, or check a book to see how to implement a proper vector.
A: You've got a lot of problems, but this one will surely crash your program:
(at the end of AllocateNew):
this->ListObject = NewListObject;
delete [] NewListObject;
Now, this->ListObject is pointing to memory that's been freed.
A:
Can you tell me where I went totally wrong?
You're reinventing the STL vector class. You can write a thin-wrapper around it to provide the API you want, but it's probably easier to use the the class as-is. Your example would look like this:
#include <iostream>
#include <vector>
using namespace std;
int main( )
{
vector< int > Numbers;
Numbers.push_back( 5 );
Numbers.push_back( 100 );
Numbers.push_back( 1500 );
for ( unsigned int x = 0; x < Numbers.size( ); x++ )
{
cout << Numbers[x] << endl;
}
cin.get();
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Regular exp to check minumum 200 characters, including spaces I need to create a regular expression to check for a minimum of 200 characters, including spaces. It should accept any characters from the keyboard I am new to javascript. How do I do it?
A: A regular expression which matches all characters, with a minimum of 200 is this one:
/[\S\s]{200,}/
*
*\S - Any non-whitespace characters
*\s - Any whitespace character
*[\S\s] - Any non-whitespace and whitespace character = any characters
*[\S\s]{200,} - Any character, at least 200 times.
A: I would have to agree with the person that commented on your answer. A regular expression is not the way to go (at least with the limited information you have provdided). If you go to the mdn entry on strings you will see that every string in JavaScript has a property that you can access called "length" which tells you exactly how many characters/bytes the string is composed of. Like so:
var myNewString = 'foo and bar';
myNewString.length //returns 11
'foo and bar'.length //returns 11
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why the addClass is not working in this code In the below Code of my function when i use CSS it works fine. when I add this CSS to a class it is not working
function setTab(selection) {
$("#"+selection).css('background', '#CC0000');
$("#"+selection).css('color', '#ffffff');
// Both the Above statements works fine
$("#"+selection).addClass("selectedclass");//doesnot work
}
.selectedclass li{
background: #CC0000;
color: #ffffff;
}
A: What I bet is happening is that the class is being overruled by another style. Which is the the most obvious in this case. The reason the first two lines of code work is becaue they edit the style directly, where adding a class, the cascading rules still would apply
Try these:
<style type="text/css">
/* I'm guess at what I think you need, since I don't know your HTML structure. */
body .selectedclass li,
body ul .selectedclass li ,
body ol .selectedclass li {
background: #CC0000;
color: #ffffff;
}
</style>
Your code is simple, so it's probably correct. But you could clean it up a bit like so:
function setTab(selection)
{
if ( typeof(selection) == "string" )
{
$( '#' + selection ).addClass( "selectedclass" );
}
}
A: Is it possible that there is a more specific selector than the class selector being applied? Have you looked at the element in Firebug to see where the element is getting its properties? Using the first two statements, you're setting the style directly on the element, which will take precedence. Using the second, it will depend on the various styles that you have defined, their order and specificity. Could also be that your class is applied to the wrong element, i.e., directly to the li instead of the parent ul (ol). In that case you need to change your rule to li.selectedClass.
Also, did you know that you can chain the jQuery functions together? And css has an overload that takes a map of key/value pairs.
function setTab(selection) {
$("#"+selection).css({'background-color': '#CC0000', 'color' : '#ffffff'});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ZF: routing. How to make correct route? I have several templates:
/admin/
/somecode1/somecode2/
/staticpage.htm
Trying to enter on /admin/. Doing follow:
$router->addRoutes(array(
'adminsys' => new Zend_Controller_Router_Route('/:module/:controller/:action/*', array('module' => 'admin', 'controller' => 'index', 'action' => 'index')),
'page_catalog' => new Zend_Controller_Router_Route('/:code/:page', array('module' => 'default', 'controller' => 'Staticcatalog', 'action' => 'index', 'code' => '', 'page' => '')),
'static' => new Zend_Controller_Router_Route_Regex('([\wА-Яа-я\-\_]+)\.(htm|html)', array('module' => 'default', 'controller' => 'static', 'action' => 'index')
));
also I tried to change 'adminsys' on :
'adminsys' => new Zend_Controller_Router_Route('/admin/:controller/:action/*', array('module' => 'admin', 'controller' => 'index', 'action' => 'index')),
or
'adminsys' => new Zend_Controller_Router_Route('/admin/*', array('module' => 'admin', 'controller' => 'index', 'action' => 'index')),
But all time it routes on 'page_catalog'.
If I comment it, I can enter /admin/. But not with 'page_catalog'.
What I'm doing wrong here?
A: When you define routes, you define the general one first, and then you go more and more specific after. The router takes your routes 'last one first' and stops on the first that matches.
This means that if '/admin' could also work for the 'page_catalog' route, it would use this one, before even trying to match 'adminsys' route. And that's the thing, '/admin' could be a 'page_catalog' url where :code param would be 'admin'.
The second variant of the adminsys route is a good one, you just have to make it the last one of your routes in order to avoid any more general route to match first :
$router->addRoutes(array(
'page_catalog' => new Zend_Controller_Router_Route('/:code/:page', array('module' => 'default', 'controller' => 'Staticcatalog', 'action' => 'index', 'code' => '', 'page' => '')),
'static' => new Zend_Controller_Router_Route_Regex('([\wА-Яа-я\-\_]+)\.(htm|html)', array('module' => 'default', 'controller' => 'static', 'action' => 'index')),
'adminsys' => new Zend_Controller_Router_Route('/admin/:controller/:action/*', array('module' => 'admin', 'controller' => 'index', 'action' => 'index'))
));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: objective-c none nil array comes up as nil in if/else statement The following code is not working as expected. I am setting an array after creating a view but before displaying. I used NSLog to test that the array is set but the if/else sees the array as empty.
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(@"Planlist is nil %d / has %d objects", (planListArr == nil), [planListArr count]);
if (planListArr == nil || [planListArr count] == 0) { ... }
else {
NSLog(@"Planlist is empty");
}
}
Logs
2011-09-25 13:54:39.764 myVI[2938:13303] Planlist is nil 0 / has 8 objects
2011-09-25 13:54:39.765 myVI[2938:13303] Planlist is empty
PlanList is defined as
NSArray *planListArr;
@property (nonatomic, retain) NSArray *planListArr;
A: if (planListArr == nil || [planListArr count] == 0) { ... }
else {
NSLog(@"Planlist is empty");
}
Expanded, this becomes:
if (planListArr == nil || [planListArr count] == 0) {
...
} else {
NSLog(@"Planlist is empty");
}
So basically, it looks like you have your NSLog() statement in the wrong branch.
A: (!plainListArray && [plainListArray count]>0) ? NSLog(@"PlainList array has %d items",[plainListArray count] : NSLog(@"Oops! Array is not been initialized or it has no items");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Accumulate data for batch updates and send it after passing threshold limits of size or after timed duration? Is it a good strategy to accumulate in webserver memory upto a specific limit of data over time that is being written to the database & send it as batch updates after every specified interval or after data grows bigger than threshold size.
Such kind of data would be very small like just adding a relationship between two entities which means adding just a set of ids to the rows.
(Of course, the delayed data should be such that is not expected to be immediately visible).
Are there any disadvantages of this approach ?
Usage: Building web application using Cassandra DB, with Java & JSF.
A: The main disadvantage is that it requires another thread to implement the timeout (a small amount of complexity) However the benefits are likely to be much greater.
A simple way to implement this is to use a wait/notify (there doesn't appear to be a good solution using the concurrency library)
private final List<T> buffered = new ArrayList<T>();
private final int notifySize = ...
private final int timeoutMS = ...
public synchronized void add(T t) {
buffered.add(t);
if (buffered.size() >= notifySize)
notifyAll();
}
public synchronized void drain(List<T> drained) throws InterruptedException {
while(buffered.isEmpty())
wait(timeoutMS);
drained.addAll(buffered);
buffered.clear();
}
The add and drained can be called by any number of threads, however I imagine you would have only one thread draining, until it is interrupted.
A: Short answer: this is a bad idea.
Cassandra's batch operations (e.g. http://pycassa.github.com/pycassa/api/pycassa/batch.html) are there to allow you to group updates in an idempotent unit. This allows you to retry the batch as a unit, so the purpose is roughly similar to a transaction in a relational database.
However, unlike the transaction analogy, the impact on performance is negligible and in fact making the load artificially "bursty" is usually counterproductive.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: IOS: turn off camera In my app I use iphone camera, but the process is very low when I open it; then I want to start the process when I shows a splashscreen.
The problem is that when splashscreen ends I don't want to show camera.
Then while I show splashscreen I want to start process of camera and quit it before splashscreen disappear. Is it possible?
A: First up, Apple specifically advise against using splash screens in their Human Interface Guidelines document. I don't know if your app would get rejected for it, but best not to try.
Second, it sounds like you need to optimise the startup of your application and probably the first view controller. To do this, you need to put off loading/initialising everything you can until it's actually needed (known as "lazy initialisation). All code in applicationDidFinishLaunching: in your app delegate and your view controller's init method, loadView, viewDidLoad, viewWillAppear, viewDidAppear should be reviewed for stuff that could be done later.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: problem running JUnit tests with Ant in Eclipse. Beginner question I'm learning these days how to use ant to run automated test folowing this tutorial.
I have JUnit in the classpath of my project. All seem to work fine and I can include it in my classes:
import junit.framework.TestCase; //line20
public class SimpleLattice1DTest extends TestCase{
...
}
My build.xml is:
<?xml version="1.0"?>
<project name="Ant-Test" default="compile" basedir=".">
<!-- Sets variables which can later be used. -->
<!-- The value of a property is accessed via ${} -->
<property name="src.dir" location="." />
<property name="build.dir" location="build" />
<property name="dist.dir" location="dist" />
<property name="docs.dir" location="docs" />
<property name="test.dir" location="jlife/tests" />
<property name="test.report.dir" location="test/report" />
<!-- Deletes the existing build, docs and dist directory-->
<target name="clean">
<delete dir="${build.dir}" />
<delete dir="${docs.dir}" />
<delete dir="${dist.dir}" />
</target>
<!-- Creates the build, docs and dist directory-->
<target name="makedir">
<mkdir dir="${build.dir}" />
<mkdir dir="${docs.dir}" />
<mkdir dir="${dist.dir}" />
<mkdir dir="${test.report.dir}" />
</target>
<!-- Compiles the java code (including the usage of library for JUnit -->
<target name="compile" depends="clean, makedir">
<javac srcdir="${src.dir}" destdir="${build.dir}">
</javac>
</target>
<!-- Creates Javadoc -->
<target name="docs" depends="compile">
<javadoc packagenames="src" sourcepath="${src.dir}" destdir="${docs.dir}">
<!-- Define which files / directory should get included, we include all -->
<fileset dir="${src.dir}">
<include name="**" />
</fileset>
</javadoc>
</target>
<!--Creates the deployable jar file -->
<target name="jar" depends="compile">
<jar destfile="${dist.dir}\CoreTest.jar" basedir="${build.dir}">
<manifest>
<attribute name="Main-Test" value="test.CoreTest" />
</manifest>
</jar>
</target>
<!-- Run the JUnit Tests -->
<!-- Output is XML, could also be plain-->
<target name="junit" depends="compile">
<junit printsummary="on" fork="true" haltonfailure="yes">
<formatter type="xml" />
<batchtest todir="${test.report.dir}">
<fileset dir="${src.dir}">
<include name="**/*Test*.java" />
</fileset>
</batchtest>
</junit>
</target>
</project>
When i run it into eclipse I get the following error:
[javac] C:\Documents and
Settings\noname\Documenti\JLife_git\JLife_git\JLife\src\jlife\tests\SimpleLattice1DTest.java:20:
package junit.framework does not exist
[javac] import junit.framework.TestCase;
I suppose there's something wrong with it, but I have no idea. Could someone put me in the right direction?
A: Your javac target doesn't specify anything apart from the source and target directory - it doesn't add any classpath entries; you'll need to add an entry for the appropriate JUnit jar file. See the javac task documentation for more details. You may want to specify the path to JUnit as a classpath attribute, a nested element, or a reference to a path declared elsewhere.
A: You need to specify the directory that contains your .class files and your external jars (like junit).
e.g.
<!-- Populates a class path containing our classes and jars -->
<path id="dist.classpath">
<fileset dir="${lib}"/>
<pathelement path="${build}"/>
</path>
<!-- Compile the java code place into ${build} -->
<target name="compile" depends="-dirty" description="Compile the source.">
<javac srcdir="${source}" destdir="${build}" includeantruntime="false">
<classpath refid="dist.classpath"/>
<exclude name="${test.relative}/**/*"/>
</javac>
</target>
Here's the complete file I took that excerpt from in case you need ideas for how to setup other common things (emma, javadoc, etc)
<project name="imp" default="dist" basedir="..">
<description>Buildscript for IMP</description>
<property name="source" location="src"/>
<property name="lib" location="lib"/>
<property name="history" location="test_history"/>
<property name="web-tests" location="/var/www/tests"/>
<property name="web-files" location="/var/www/files"/>
<property name="web-javadoc" location="/var/www/javadoc"/>
<property name="web-emma" location="/var/www/emma"/>
<property name="emma.dir" value="${lib}"/>
<property name="test" location="${source}/imp/unittest"/>
<property name="test.relative" value="imp/unittest"/>
<property name="javadoc-theme" value="tools/javadoc-theme"/>
<!-- directories for generated files -->
<property name="build" location="build"/>
<property name="build-debug" location="debug"/>
<property name="build-coverage" location="coverage"/>
<property name="dist" location="dist"/>
<property name="reports" location="reports"/>
<property name="coverage-emma" location="${reports}/coverage/emma"/>
<!-- Populates a class path containing our classes and jars -->
<path id="dist.classpath">
<fileset dir="${lib}"/>
<pathelement path="${build}"/>
</path>
<path id="debug.classpath">
<fileset dir="${lib}"/>
<pathelement path="${build-debug}"/>
</path>
<!-- import emma. This classpath limits the coverage to just our classes -->
<path id="debug.imp.classpath">
<pathelement path="${build-debug}"/>
</path>
<taskdef resource="emma_ant.properties" classpathref="debug.classpath"/>
<!--
Shouldn't ever need to use this from the command line. IRC saith that the "private"
internal use only sort of targets are prefixed with '-'.
dirty because it's the opposite of the 'clean' target.
-->
<target name="-dirty">
<tstamp/>
<mkdir dir="${build}"/>
<mkdir dir="${build-debug}"/>
<mkdir dir="${build-coverage}"/>
<mkdir dir="${dist}"/>
<mkdir dir="${reports}"/>
<mkdir dir="${coverage-emma}"/>
</target>
<!-- clean up all the generated files and direcories -->
<target name="clean" description="Deletes all files and directories created by this script.">
<delete dir="${build}"/>
<delete dir="${build-debug}"/>
<delete dir="${build-coverage}"/>
<delete dir="${dist}"/>
<delete dir="${reports}"/>
<delete dir="${coverage-emma}"/>
</target>
<!-- Compile the java code place into ${build} -->
<target name="compile" depends="-dirty" description="Compile the source.">
<javac srcdir="${source}" destdir="${build}" includeantruntime="false">
<classpath refid="dist.classpath"/>
<exclude name="${test.relative}/**/*"/>
</javac>
</target>
<!-- Compile the java code with debug info place into ${build} -->
<target name="compile-debug" depends="-dirty" description="Compile the source with debug information.">
<javac
srcdir="${source}"
destdir="${build-debug}"
includeantruntime="false"
debug="true"
debuglevel="lines,vars,source"
>
<classpath refid="debug.classpath"/>
</javac>
</target>
<!-- roll up everyting into a single jar file -->
<target name="dist" depends="clean, compile" description="Generate the distribution file for IMP.">
<!-- Copy the library .jars to the directory where the IMP distribution will be located -->
<copy todir="${dist}">
<fileset dir="${lib}"/>
</copy>
<!-- TODO: Generate the MANIFEST.MF file on the fly -->
<jar jarfile="${dist}/imp.jar" basedir="${build}" manifest="tools/MANIFEST.MF"/>
<!-- dump to web server -->
<copy todir="${web-files}">
<fileset dir="${dist}"/>
</copy>
</target>
<!-- build and run the tests then report the results in HTML -->
<target name="test" depends="compile-debug" description="Run all the JUnit tests and outputs the results as HTML.">
<!-- run the tests -->
<junit printsummary="true" haltonerror="false" haltonfailure="false">
<classpath refid="debug.classpath"/>
<formatter type="xml"/>
<batchtest fork="true" todir="${reports}">
<fileset dir="${source}">
<include name="${test.relative}/**/*Test*.java"/>
<exclude name="${test.relative}/**/AllTests.java"/>
</fileset>
</batchtest>
</junit>
<!-- report the results -->
<junitreport todir="${reports}">
<fileset dir="${reports}" includes="TEST-*.xml"/>
<report todir="${reports}"/>
</junitreport>
<!-- update the latest results file to be commited -->
<copy file="${reports}/TESTS-TestSuites.xml" tofile="${history}/test-results-latest.xml"/>
<!-- dump to webserver -->
<copy todir="${web-tests}">
<fileset dir="${reports}"/>
</copy>
</target>
<!-- run emma code coverage tool and publish results in HTML -->
<target name="emma" depends="compile-debug" description="Checks code coverage with Emma.">
<!-- put the magic emma juice into the classes -->
<emma>
<instr
instrpathref="debug.imp.classpath"
destdir="${coverage-emma}/instr"
metadatafile="${coverage-emma}/metadata.emma"
merge="true"
/>
</emma>
<!-- run the tests -->
<junit fork="true" printsummary="true" haltonerror="false" haltonfailure="false">
<classpath>
<pathelement location="${coverage-emma}/instr"/>
<path refid="debug.classpath"/>
</classpath>
<batchtest fork="true" todir="${reports}">
<fileset dir="${source}">
<include name="${test.relative}/**/*Test*.java"/>
<exclude name="${test.relative}/**/AllTests.java"/>
</fileset>
</batchtest>
<jvmarg value="-Demma.coverage.out.file=${coverage-emma}/coverage.emma"/>
<jvmarg value="-Demma.coverage.out.merge=true"/>
</junit>
<!-- publish the coverage report -->
<emma>
<report sourcepath="${source}" verbosity="verbose">
<fileset dir="${coverage-emma}">
<include name="*.emma"/>
</fileset>
<html outfile="${web-emma}/index.html"/>
</report>
</emma>
</target>
<!-- publish javadoc -->
<target name="javadoc" description="Creates javadoc for IMP.">
<delete dir="${web-javadoc}"/>
<javadoc
sourcepath="${source}"
defaultexcludes="no"
destdir="${web-javadoc}"
author="true"
version="true"
use="true"
windowtitle="IMP: Integrated Mechanisms Program"
overview="${source}/overview.html"
classpathref="debug.classpath"
stylesheetfile="${javadoc-theme}/stylesheet.css"
/>
<copy file="${javadoc-theme}/javadoc.jpg" tofile="${web-javadoc}/javadoc.jpg"/>
</target>
<target name="all" description="Runs test, emma, javadoc, and dist targets.">
<antcall target="test"/>
<antcall target="emma"/>
<antcall target="javadoc"/>
<antcall target="dist"/>
</target>
</project>
A: The eclipse classpath is separate from your ant environment. In your build file, when you call javac you need to supply a classpath attribute.
You can define the classpath at the top of the file with the rest of your properties, like this:
<path id="classpath">
<fileset dir="[path to libraries]" includes="**/*.jar" />
</path>
and then use it in each call to javac by setting the classpathref attribute, like this:
<javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath" />
A: If you observe the error stack, you will find the following line, just above the error line you mentioned...
[javac] [search path for class files: C:\Program Files\Java\jre6\lib\resource...
This line shows all the jars available in the class path for this ant target execution.
You will definitely not find the desired jar over here i.e. junit-x.x.x.jar (junit-4.8.2.jar)
Now go to eclipse -> Window -> preferences -> Ant -> Runtime -> Global Entries -> Add Jars add junit-4.8.2jar (which you will find in your project lib directory)
If you play around the Ant -> Runtime -> classpath and the classpath related error line in the error stack, you will understand the issue.
Hope this solves your problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.