text
stringlengths 8
267k
| meta
dict |
---|---|
Q: plotting multiple sets of different data points on a graph in R I'm trying to plot several sets of ordered pairs on the same plot, using R. I don't need a line between them, because that's already taken care of by a simple linear regression. Here's some sample code:
sw_sd <- c(0, 20)
sw_r <- c(5, 10)
aa_sd <- c(0, 16)
aa_r <- c(5, 8)
png("5-airline-cals.png")
plot.new()
plot.window(xlim=c(0,25), ylim=c(0,12))
plot(c(aa_sd, aa_r))
plot(sw_sd,sw_r, pch=22, main="Capital Allocation Lines", xlab="Standard Deviation", ylab="Expected Return")
sw_cal=lm(sw_r~sw_sd)
aa_cal=lm(aa_r~aa_sd)
abline(sw_cal, col="forestgreen", lwd=3)
abline(aa_cal, col="blue", lwd=3)
legend(1, 9, c("Southwest Airlines","American Airlines"), cex=0.8, col=c("forestgreen","blue"), lwd=3);
box()
dev.off()
The sd pairs are the x coordinates, and the r are the y coordinates. I need both sets of x-y pairs on the same scatter plot. This is simplified data, but you get the idea.
A: Sorry for the drive by RTFM comment. Here's some more detail.
Using base graphics, I would accomplish what you're doing via something like this:
plot(c(sw_sd,aa_sd),c(sw_r,aa_r), pch = 22,
col = rep(c('forestgreen','blue'),each = 2),main="Capital Allocation Lines",
xlab="Standard Deviation", ylab="Expected Return")
abline(lm(sw_r~sw_sd),col = 'forestgreen',lwd = 3)
abline(lm(aa_r~aa_sd),col = 'blue',lwd = 3)
The reason I mentioned points and lines was because you were asking how to plot multiple sets of points on the same graph. The general strategy with base graphics in R is you initialize a plot with a single call to plot and then you add to it using things like points, lines, abline etc.
Your calls to plot.new and plot.window aren't really necessary; if you're just starting with R you probably won't need to use them for a while, really.
In general, each time you call plot, R will start a new plotting device. So your repeated calls to plot are just going back and starting over again. You'll notice that your resulting plot didn't end up having y axis limits of 0 to 12. That's because each time you called plot anew you were starting over from scratch, as if the previous commands never happened. This is also why the other set of points didn't appear.
Finally, the recommendation to read ?plot was a bit misleading, since really ?plot.default is a bit more informative for beginners. It has little nuggets like being able to pass x and y axis limits directly, passing type = "n" to create an empty plot with the right dimensions that you can then add to, etc.
A: A quick ggplot-based answer:
dat <- data.frame(sd=c(0,20,0,16),
r=c(5,10,5,8),
airline=rep(c("Southwest","American"),each=2))
library(ggplot2)
theme_update(theme_bw())
qplot(sd,r,data=dat,colour=airline)+geom_smooth(method="lm")+
labs(x="Standard Deviation",y="Expected Return")+
scale_colour_manual(value=c("forestgreen","blue"))
A: Using the data frame of Ben but with lattice:
library(lattice)
xyplot(r~sd, data=dat, groups=airline,
type=c('p', 'r'),
auto.key=list(space='right'),
main="Capital Allocation Lines",
xlab="Standard Deviation", ylab="Expected Return")
You will find detailed information in ?panel.xyplot and ?xyplot.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Splash screen opens only first time application starts There is an application with 2 activities: Splash screen and main screen. After installing application it shows splash, then finishes Splash activity and starts main activity. Then i test 3 scenarios:
*
*App is launched, second activity showed on screen. I kill app process by DDMS, launch app again — everything is right — i see splash again, then second activity
*App is launched, second activity showed on screen. I press back key, then kill process, launch application again — everything all right too, it launch splash first
*App is launched, second activity showed on screen. I press home key, then kill process, launch application again — and there is surprise — application starts on second activity, escaping splash.
What`s wrong?
There is some others question like this one, but i still got no answer.
Can anybody explain this behavior?
A: Splash screens aren't a real good idea anyway since it gives the user the feeling that the application is an add-on and breaks slightly the whole system life cycle.
But if you really want to have a splash screen on the launch Activity, there are two options. One is to have two views inside a root RelativeLayout. One with the splash screen inside an ImageView and another layout with the actual content of the activity. Then, hide the ImageView with your favorite animation.
Alternatively, you can use a fragment instead of the content layout and load the Activity instances (What used to be done with ActivityGroup).
Update:
Ok, I forgot to mention why is that happening in your app.
In any Android application we have a loosely bound set of activities and (usually) when we launch a new Activity it gets added to an Activity stack (to manage the back behavior). I say usually because you can change that behavior if required (launchMode).
When you press the back button the stack is emptied and the activity terminated. On the other hand, when pressing the home button, the stack is saved and restored when relaunching.
The Android life cycle can be a bit of a headache sometimes, but once you understand it is really well thought through.
here is some further reading: Activity and Task Design Guidelines
A: Application always starts from where you were before....
Lets say you have 5 seconds.
You open the app for 4 seconds with the splash screen.
You close the app.
You open it.
There is only 1 second left for the splash screen
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: check if oracle database is available I am looking to write a C# class to run at regular intervals that check if an oracle database is available/online/can be connected to. I am wondering what is the best way to achieve this? How can i check if an oracle database is available?
A: http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson01.aspx
Basically, you periodically open a connection to your database (and then close it). If it doesn't throw an exception, the database is available (although it may have other issues that aren't apparent from a simple connection).
A: As MusiGenesis said you can open and close a connection and check for the error conditions but also be sure to make a simple query like "select 1 from dual;" and check for the result because with a simple connection you may not get some of the low level errors like "ORA-01507 : Database not mounted" or "ORA-01034 : Oracle not available".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Display contents from ListView defined in regular Activity Android I wanted to create a search view like the one Google uses. For this I created the following XML layout, which basically is a search bar and a button in the upper section of the screen and a ListView at the bottom of it.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayoutSearch"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#FF394952">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" >
<EditText android:layout_height="wrap_content" android:id="@+id/searchTextBar" android:layout_width="wrap_content" android:layout_weight="1">
<requestFocus></requestFocus>
</EditText>
<Button android:layout_height="fill_parent" android:layout_width="wrap_content" android:id="@+id/searchButton" android:text="Buscar"></Button>
</LinearLayout>
<ListView
android:id="@+id/searchResultList"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_alignParentBottom="true"
android:layout_weight="1.0" />
</LinearLayout>
And this is the code of the textViewResource that the ArrayAdapter demands on its constructor:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</TextView>
Now, this is the code of the activity. So far, I just want to display the view with the contents (that's why I'm using a static String array for now).
public class SearchActivity extends Activity{
static final String[] COUNTRIES = new String[] {
"Afghanistan", "Albania", "Algeria"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item, COUNTRIES);
ListView lv = (ListView)this.findViewById(R.id.searchResultList);
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
}
}
However, when I run the activity I see the search bar but it doesn't display the ListView.
I've tried changing the extension of SearchActivity to ListActivity, but the program just crashes when I try to start it. I'm also aware of the existence of the Search Interface, but I just want to see this particular method work.
Why it doesn't display the contents of the ListView? Is there a way to fix this?
Thanks in advance
A: If you are going to use ListActivity you should be aware that ListActivity already has a ListView instance. You need to call its setListAdapter method to set the adapter for its ListView instead of instantiating your own ListView and setting the adapter on it. You can call getListView to get a handle on ListActvity's ListView and then set the click listener on that.
A: If you want to extend ListActivity then you must have a ListView with id @android:id/list. Change the id of your ListView, that should fix the crash when extending ListActivity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make a title blink until it becomes active with jQuery? I have a javascript chat. When a user receives a message, I want the title to blink until it becomes active. (like Gmail Talk)
For example:
*
*You are in an other tab. Title is My website
*Someone talks to you. Title blinks betwen My website and User says: bla bla
*So you click the tab, and now the title is My website
How can I achieve that using jQuery ?
What i tried so far: (blinking never stop playing)
var isOldTitle = true;
var oldTitle = "oldTitle";
var newTitle = "newTitle";
function changeTitle() {
document.title = isOldTitle ? oldTitle : newTitle;
isOldTitle = !isOldTitle;
setTimeout(changeTitle, 700);
}
changeTitle();
A: Full solution:
var isOldTitle = true;
var oldTitle = "oldTitle";
var newTitle = "newTitle";
var interval = null;
function changeTitle() {
document.title = isOldTitle ? oldTitle : newTitle;
isOldTitle = !isOldTitle;
}
interval = setInterval(changeTitle, 700);
$(window).focus(function () {
clearInterval(interval);
$("title").text(oldTitle);
});
A: Pinouchon's answer works but if I had to add an interval check so it didn't speed up the title changing when one person messaged multiple times in a row.
So I had
if(timeoutId)
{
clearInterval(interval);
}
interval = setInterval(changeTitle, 700);
Basically if the interval had already been set, clear it and then reset it.
A: Just remember to call clearInterval on focus:
(function() {
var timer,
title = $('title'),
title_text = title.text();
$(window).blur(function() {
timer = setInterval(function() {
title.text(title.text().length == 0 ? title_text : '');
}, 2000)
}).focus(function() {
clearInterval(timer);
title.text(title_text);
});
})();
A: You can try this one. You can call the blink function to start switching between two titles and call stop, when you dont want this anymore.
var title = document.title;
var interval = 0;
function blink(title1, title2, timeout){
title2 = title2 || title;
timeout = timeout || 1000;
document.title = title1;
interval = setInterval(function(){
if(document.title == title1){
document.title = title2;
}else{
document.title = title1;
}
}, timeout);
}
function stop(){
clearInterval(interval);
document.title = title;
}
blink('My blinking title!');
setTimeout(function(){
stop();
}, 5000)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Combine two vim commands into one I'm having trouble combining two vim commands, specifically <C-w>s and <leader>x into <leader>r (i.e. split window and open spec counterpart of current file). Any help?
Thanks!
A: It would help if you'd post what exactly you've tried that didn't work. Generally, doing what you describe should be simple. It should be enough to put this in your .vimrc file:
nmap <leader>r <c-w>s<leader>x
This maps <leader>r to expand to the key sequence <c-w>s<leader>x. Note that these are not "commands", as you call them in your question, they're "mappings". A "command" is something completely different in vim, you can read up on that with :help user-commands.
One thing to be careful of is using nmap instead of nnoremap. The command nmap maps the sequence on the left to the sequence on the right while re-using mappings that have already been defined. On the other hand, nnoremap creates a mapping with the original meanings of the keys, so in your case won't work (since <leader>x is defined by some plugin). This is one possible reason you may have failed while trying to do it, but I can't tell from your question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PostgreSQL: IN A SINGLE SQL SYNTAX order by numeric value computed from a text column A column has a string values like "1/200", "3.5" or "6". How can I convert this String to numeric value in single SQL query?
My actual SQL is more complicated, here is a simple example:
SELECT number_value_in_string FROM table
number_value_in_string's format will be one of:
*
*##
*#.##
*#/###
I need to sort by the numeric value of this column. But of course postgres doesn't agree with me that 1/200 is a proper number.
A: I would define a stored function to convert the string to a numeric value, more or less like this:
CREATE OR REPLACE FUNCTION fraction_to_number(s CHARACTER VARYING)
RETURN DOUBLE PRECISION AS
BEGIN
RETURN
CASE WHEN s LIKE '%/%' THEN
CAST(split_part(s, '/', 1) AS double_precision)
/ CAST(split_part(s, '/', 2) AS double_precision)
ELSE
CAST(s AS DOUBLE PRECISION)
END CASE
END
Then you can ORDER BY fraction_to_number(weird_column)
If possible, I would revisit the data design. Is it all this complexity really necessary?
A: This postgres SQL does the trick:
select (parts[1] :: decimal) / (parts[2] :: decimal) as quotient
FROM (select regexp_split_to_array(number_value_in_string, '/') as parts from table) x
Here's a test of this code:
select (parts[1] :: decimal) / (parts[2] :: decimal) as quotient
FROM (select regexp_split_to_array('1/200', '/') as parts) x
Output:
0.005
Note that you would need to wrap this in a case statement to protect against divide-by-zero errors and/or array out of bounds issues etc if the column did not contain a forward slash
Note also that you could do it without the inner select, but you would have to use regexp_split_to_array twice (once for each part) and you would probably incur a performance hit. Nevertheless, it may be easier to code in-line and just accept the small performance loss.
A: I managed to solve my problem. Thanks all.
It goes something like this, in a single SQL. (I'm using POSTGRESQL)
It will sort a string coming in as either "#", "#.#" or "1/#"
SELECT id, number_value_in_string FROM table ORDER BY CASE WHEN position('1/' in number_value_in_string) = 1
THEN 1/substring(number_value_in_string from (position('1/' in number_value_in_string) + 2) )::numeric
ELSE number_value_in_string::numeric
END ASC, id
Hope this will help someone outhere in the future.
A: Seeing your name I cannot but post a simplification of your answer:
SELECT id, number_value_in_string FROM table
ORDER BY CASE WHEN substr(number_value_in_string,1,2) = '1/'
THEN 1/substr(number_value_in_string,3)::numeric
ELSE number_value_in_string::numeric END, id;
Ignoring possible divide by zero.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Example code of FBML App that uses signed_request? We did not know that Oct 1 is also deadline for signed_request.
Does anyone have example code to do signed_request for FBML apps?
We are trying to beat the deadline on Oct 1. Thanks!
A: The signed_request documentation shows how to do it in PHP. It's pretty easy to do in any language.
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery form validation event with pop-up resizing query I'm currently showing the user a pop-up form - http://colorpowered.com/colorbox/ - which so far seems to be the only one i've found compatible with all browsers (Round of applause to IE for not been compatible in other ones).
I'm also using with this the jQuery form validation engine - https://github.com/posabsolute/jQuery-Validation-Engine to help ensure all fields are complete.
I have set out to - When the user clicks submit and all validation is passed, for them to be redirected to another window saying thank you etc.. The problem is, this is a smaller window and so I needed to resize it, which I have successfully, but regardlous of if they've passed the validation or not.
The code that works to resize the pop-up is:
function resize() {
$.colorbox.resize({innerWidth:432, innerHeight:280});
};
With the "onclick" event attached to the submit button -
onclick="top.resize()"
Now i've taken a look at the examples the validator gives to see if I can return True or False should the form validation be passed, I managed to find this in the form of an alert:
<a href="#" onclick="alert('is the form valid?'+jQuery('#formID').validationEngine('validate'))">Evaluate form</a>
Now I thought I could replicate this into my code to only run the 'Resize' if the validation passes (When the resize runs and the validation hasn't been passed, the form skews and disorientates within it). This is my end result so far but to no avail:
function resize() {
if($('#jobForm').validationEngine('validate')) == 'true'){
$.colorbox.resize({innerWidth:432, innerHeight:280});
}
};
Within the console, the error i get is 'Uncaught SyntaxError: Unexpected token ==' but i'm sure this just isn't the problem.
This is where i hit a grey area and any advice would be hugely appreciated.
Many thanks in advance.
A: This line is indeed incorrect, your parens are unbalanced:
if($('#jobForm').validationEngine('validate')) == 'true'){
Change it to this, and see if your problem goes away:
if($('#jobForm').validationEngine('validate') == 'true'){
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get a fragment to load from an unspecified html? After making the menu disappear I cannot get my content to show without listing a specific html.
HERE is the HTML:
<div id="header">
<h1>N300 Project Gallery</h1>
</div>
<div id="container">
<div id="utility">
<ul>
<li><a href="about.html">About</a></li>
<li><a href="projects.html">Projects</a></li>
</ul>
</div>
<div id="index-content">?</div>
<div id="footer">This is the footer</div>
</div>
Here is my script:
$(document).ready(function() {
$('#utility a').click(function(e){
e.preventDefault();
$('#utility').hide('normal',loadContent);
});
function loadContent() {
$('#index-content').load(url+ '#content')
}
});
HERE IS THE FRAGMENT I WANT TO MOVE:
<div id="content">
<p>Hello! My name is Brittany Shephard.</p>
</div>
A: Where is the url in loadContent() coming from ?
In case you'll need to pass it from the e.target href attribute, create an anonymous function for hide's callback, and from the pass the url to loadContent. Somtehing like:
$(document).ready(function() {
$('#utility a').click(function(e){
e.preventDefault();
$('#utility').hide('normal', function() {
loadContent($(e.target).attr('href'));
});
});
function loadContent(url) {
$('#index-content').load(url + ' #content');
}
});
A: Note that you need an extra space before #content in the URL you pass to .load() if you want the fragment loading behavior (+ ' #content' instead of + '#content').
Your fragment is in a separate file, correct?
Assuming your fragment is returned from projects.html #content, try:
function loadContent() {
$('#index-content').load($(this).attr('href')+ ' #content');
}
From the JQuery docs for hide, this is set to the hidden DOM node in the callback. I'm assuming you want to load URL from the anchor you're hiding, so you need to grab the href attribute from that node.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Crop MS Word Images using Matlab Activex control I am using MATLAB to paste and caption plots into Microsoft Word. I would like to also crop these images using the ActiveX control.
something like:
word = actxserver('Word.Application')
word.Visible = 1
op = invoke(word.Documents,'Add')
invoke(word.Selection,'Paste')
invoke(word.Selection,'CropBottom',CropAmount) <----- Except there is no function that will allow me to crop.
I am modifying the MATLAB File Exchange "save2word.m"
Thanks
A: Consider this example:
%# create plot and copy to clipboard
plot(rand(10,1))
print -dmeta
%# open MS-Word
Word = actxserver('Word.Application');
Word.Visible = true;
%# create new document
doc = Word.Documents.Add;
%# paste figure from clipboard
Word.Selection.Paste
%# crop the image
doc.InlineShapes.Item(1).PictureFormat.CropBottom = 100;
%# save document, then close
doc.SaveAs2( fullfile(pwd,'file.docx') )
doc.Close(false)
%# quit and cleanup
Word.Quit
Word.delete
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MVC3: Areas and routes I configured my MVC3 app to use Areas (/Company1, /Company2, etc).
I am successful at calling /Company1/{controller}/{action} and I would like to add another parameter to the route so that I could call it /Company1/Chicago/{controller}/{action} or /Company1/Detroit/{controller}/{action}.
I am imagining that in my solution folder structure it would flow similarly: Areas/Company1/Controllers/Chicago/{controller}, Areas/Company1/Views/Chicago/{view}.
What is involved to add that parameter to the route mapping?
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Detection - the title of the URL and the URL How to detect, if there is any URL in the text and title it has (if any)?
If there is one, then it should change the URL:
from: http://stackoverflow.com
into:
<detected:url="http://stackoverflow.com"/>
I need also to retrieve titles from external links like this example:
<title:http://stackoverflow.com/="the actual title from the stackoverflow"/>
A: This is for single URL case:
$url = "http://www.stackoverflow.com/";
$check_result = get_detected_and_title( $url );
function get_detected_and_title( $url )
{
$detected = '<detected:url="'.$url.'"/>';
$title = '';
$tmp_html = file_get_contents( $url );
preg_match('/<title>(.*)<\/title>/', $tmp_html, $res);
$title = '<title:'.$url.'="'.$res[1].'"/>';
return array( $detected, $title );
}
Actually, after looking through SO's pages, I think this is more close to what you looking for. Although it needs some adjustment: How to mimic StackOverflow Auto-Link Behavior
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Does one need to close both NetworkStream and TcpClient, or just TcpClient? I'm reading the documentation on TcpClient.Close() and noticed this:
Calling this method will eventually result in the close of the associated Socket and will also close the associated NetworkStream that is used to send and receive data if one was created.
So, correct me if I'm wrong but this says that if one calls Close() on the TcpClient that the NetworkStream will also be closed.
So then why at the end of the code example are both Close() called?
networkStream.Close();
tcpClient.Close();
Would it be just as fine to only call tcpClient.Close();?
A: NetworkStream and TcpClient implement IDisposable. So best practise in my opinion is to pack it into a using block, so you never need to close or dispose it manually.
A: Closing the client does not close the stream, it's in the doc of the GetStream method.
For the reference, have a look to this discussion : How to properly and completely close/reset a TcpClient connection?
A: Responding to this question since no one else did so that I may accept an answer.
According to Hans, calling NetworkStream.Close() is unnecessary because TcpClient.Close() closes its underlying NetworkStream.
A: You should Just do "TcpClient.Close()"
Or if you must, type both
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: On properties and accessors Assuming that header declaration contains
@property(nonatomic, assign) DoublyLinkedList *doublyLinkedList;
Is there any difference between
[[self doublyLinkedList] release];
[self setDoublyLinkedList:nil];
and
[doublyLinkedList release];
doublyLinkedList= nil
Is one preferred over another? Why?
A: There is no difference.
The second option might be ever so slightly faster, because it doesn't use the getter/setter methods.
Just so we're clear, are you retaining doublyLinkedList when you assign it? Because otherwise you're over-releasing.
And unless you have a good reason, I would skip all this and use retain instead of assign, and self.doublyLinkedList = nil to release/clear it.
e.g.
definition
@property(nonatomic, retain) DoublyLinkedList *doublyLinkedList;
in use
self.doublyLinkedList = nil;
and on dealloc
-(void)dealloc{self.doublyLinkedList=nil;[super dealloc];}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to use a value inside a method outside of that method (location) I'm am new to android, and I am attempting make a program that would send one's latitude and longitude to a database and store it there. However, I've hit a problem: I can't figure out how to be able to use the lat and lng obtained. The loc.getLatitude() and loc.getLongitude() are inside the method mylocationlistner which does not allow me to use outside of that... What am I supposed to do?????
public class MyLocation2 extends MapActivity {
private MapView myMap;
private MyLocationOverlay myLocOverlay;
private MapController controller;
Location loc;
LocationManager lm;
LocationListener ll;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initMap();
initMyLocation();
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
**double lat = location.getLatitude();
double lng = location.getLongitude();**
} //as u can see, they are inside here
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
UpdateLoc(lat, lng); **<------THIS IS WHERE I WANT TO PLUG THE VALUES IN**
}
/**
* Initialise the map and adds the zoomcontrols to the LinearLayout.
*/
private void initMap() {
myMap = (MapView) findViewById(R.id.mymap);
@SuppressWarnings("deprecation")
View zoomView = myMap.getZoomControls();
LinearLayout myzoom = (LinearLayout) findViewById(R.id.myzoom);
myzoom.addView(zoomView);
myMap.displayZoomControls(true);
}
/**
* Initialises the MyLocationOverlay and adds it to the overlays of the map
*/
private void initMyLocation() {
myLocOverlay = new MyLocationOverlay(this, myMap);
myLocOverlay.enableMyLocation();
myMap.getOverlays().add(myLocOverlay);
controller = myMap.getController();
myLocOverlay.runOnFirstFix(new Runnable() {
public void run() {
controller.setZoom(17);
controller.animateTo(myLocOverlay.getMyLocation());
}
});
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
myLocOverlay.enableMyLocation();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
myLocOverlay.disableMyLocation();
}
public void UpdateLoc(final double latitude, final double longitude){
InputStream is = null;
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new DoubleNameValuePair("latitudeE6",latitude));
nameValuePairs.add(new DoubleNameValuePair("longitudeE6",longitude));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://bryankim.in/program/UpdateUserLoc.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
}
//for <String, Double> NameValuePair
public class DoubleNameValuePair implements NameValuePair {
String name;
double value;
public DoubleNameValuePair(String name, double value) {
this.name = name;
this.value = value;
}
@Override
public String getName() {
return name;
}
@Override
public String getValue() {
return Double.toString(value);
}
}
}
A: First stop and take some time to learn Java. You won't get very far without knowing how to express what you are attempting to say.
To get the data (latitude and longitude) to where you need it, write updateLoc then pass the values to that method.
A: Why don't you just call your method as soon as you receive the Latitude / Longitude?
public void onLocationChanged(Location location) {
UpdateLoc(location.getLatitude(), location.getLongitude());
}
Although, instead of calling the UpdateLoc method directly, since it will run on the Thread of the listener, you should consider using your internet connection code inside an AsyncTask.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Enable colored output in mvim I'm running rspec from within mvim with :!rspec spec/lib, however if I include --color flag, I get
[32m.[0m[32m.[0m[32m.[0m[32m.[0m[32m.[0m[32m.[0m[32m.[0m
Finished in 0.01708 seconds
[32m7 examples, 0 failures[
I tried --tty flag which works with rstakeout, but no help.
A: Unfortunately this is not possible.
MacVim does it's own graphics rendering, which is not implemented as/via a terminal emulator, so it has no concept of ANSI color codes etc. I believe I remember the author of MacVim commenting that this will never be supported, which is a shame.
When I was using MacVim, I'd run rspec --no-color to at least avoid the escape sequences cluttering the output.
I've since switched to vim (running inside tmux in full-screen iTerm2) and it's nice to get back the color output of console commands.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Custom sensitivity settings on gyroscope through android api, or kernel? I own a samsung galaxy tab 10.1 4g lte-- and am starting to play with the sensors onboard. I looked up the mems gyro on board and found that (you can see for yourself on pg 9) that there are 4 different condition settings to change the sensitivity of the gyro from 250 degrees per second to up to like 2500 degrees per second. I am pretty sure that the lower setting will allow for a finer resolution of reading, while the higher settings can account for larger amounts of motions ( the reading at highest resolution (250) would probably max out at 250). Does anyone know what the default setting is and how to change it? If i had to guess I would bet the setting is on +-500 or +-1000 by default.
Thanks for the help in advance.
A: On registering your listener, you can specify the rate at which the events should be received.
registerListener (SensorEventListener listener, Sensor sensor, int rate)
You can choose from a variety of rates enumerated by SensorManager class:
SENSOR_DELAY_NORMAL, SENSOR_DELAY_UI, SENSOR_DELAY_GAME, or SENSOR_DELAY_FASTEST
Moreover, even the rate values are just a hint for the system, it's not necessarily receiving events at your specified rate.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: cakePHP - Download File through Controller I'm using the cakePHP framework for my website and I would like to create an action which, rather than sending HTML, instead echos the contents of a file. It can't be stored in a public directory, as the data is confidential.
Before using the framework, I accomplished this by rewriting /downloads/KEY/FILE to file.php?key=KEY&file=FILE
However, I can't find any clear way to do this using cakePHP. Essentially, I'd like a way to either:
*
*When a user accesses a controller action from its URL a .jar file is sent, not a webpage.
*A URL is redirected to a PHP file which separately connects to a database and serves the file.
Note that cakePHP is at my domain root. Also, as I'm using SSL for the transfer and I do not ow n a wildcard certificate, I cannot use a subdomain.
A: use Media view: http://book.cakephp.org/view/1094/Media-Views
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WPF app does not execute Application_Exit method when user closes main window I have a WPF/C# 4.0 App which has an Application file XAML that is:
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="XXX.App"
Startup="Application_Startup"
Exit="Application_Exit"
>
<Application.Resources>
</Application.Resources>
And its exiting method is:
//it seems that it never passes here. Transferred to MainAppWindow_WindowClosing
private void Application_Exit(object sender, ExitEventArgs e)
{
this.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
}
It never passes in this piece of code when the application user closes it. Is it supposed to work this way? Am I doing something wrong?
A: I have never used it but the docs say that
Occurs just before an application shuts down, and cannot be canceled.
An application can shut down for either of the following reasons:
*
*The Shutdown method of the Application object is called, either
explicitly or as determined by the ShutdownMode property.
*The user ends the session by logging off or shutting down.
So in your case, these conditions might not be met. Have you tried changing the ShutDownMode?
A: Application_Exit method will call when you shutdown the application by Application.Current.Shutdown() method or close all windows from your application. (it will call when last window will be closed).
If you call Application.Current.Shutdown() method then it will automatically close all opened windows. Pleaese make sure that your all windows are closed or not ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: scheduling a task in Android I'm trying to develop an app for Android and I want my app
to receive as input the time (year, month, day, hour, minute) and the app
should put a message on the screen at that time.
Any ideas on how can I schedule a task ?
A: You can use the AlarmManager
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Floating Point Exception with Numpy and PyTables I have a rather large HDF5 file generated by PyTables that I am attempting to read on a cluster. I am running into a problem with NumPy as I read in an individual chunk. Let's go with the example:
The total shape of the array within in the HDF5 file is,
In [13]: data.shape
Out[13]: (21933063, 800, 3)
Each entry in this array is a np.float64.
I am having each node read slices of size (21933063,10,3). Unfortunately, NumPy seems to be unable to read all 21 million subslices at once. I have tried to do this sequentially by dividing up these slices into 10 slices of size (2193306,10,3) and then using the following reduce to get things working:
In [8]: a = reduce(lambda x,y : np.append(x,y,axis=0), [np.array(data[i* \
chunksize: (i+1)*chunksize,:10],dtype=np.float64) for i in xrange(k)])
In [9]:
where 1 <= k <= 10 and chunksize = 2193306. This code works for k <= 9; otherwise I get the following:
In [8]: a = reduce(lambda x,y : np.append(x,y,axis=0), [np.array(data[i* \
chunksize: (i+1)*chunksize,:10],dtype=np.float64) for i in xrange(k)])
Floating point exception
home@mybox 00:00:00 ~
$
I tried using Valgrind's memcheck tool to figure out what is going on and it seems as if PyTables is the culprit. The two main files that show up in the trace are libhdf5.so.6 and a file related to blosc.
Also, note that if I have k=8, I get:
In [12]: a.shape
Out[12]: (17546448, 10, 3)
But if I append the last subslice, I get:
In [14]: a = np.append(a,np.array(data[8*chunksize:9*chunksize,:10], \
dtype=np.float64))
In [15]: a.shape
Out[15]: (592192620,)
Does anyone have any ideas of what to do? Thanks!
A: Did you try to allocate such a big array before (like DaveP suggests)?
In [16]: N.empty((21000000,800,3))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
...
ValueError: array is too big.
This is on 32bit Python.
You would actually need 20e6*800*3*8/1e9=384 GBytes of memory!
One Float64 needs 8 bytes.
Do you really need the whole array at once?
Sorry, did not read post properly.
Your array with k=8 subslices is already about 4.1 GByte big. Maybe that is the problem?
Does it work if you use only 8 instead of 10 for the last dimension?
Another suggestion, i would try first to resize the array, then fill it up:
a = zeros((4,8,3))
a = resize(a, (8,8,3))
a[4:] = ones((4,8,3))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: How to determine object's owner in Objective-C program? Are there any tools available as part of XCode4 that per given object will tell you "who owns it at any time?"
A: Yes. The Allocaitons instrument can answer that. Turn on retain count tracking and run your app. You can then click through any object (you'll typically only want to track live allocations) and see an inventory of all retains/releases related to that object.
All retains not balanced by a release from the same object indicates an ownership relationship.
It isn't 100% precise, but it works well enough (and is improving with each release).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Consuming Spring (SOAP) web service in a java servlet Is there any way to consume a SOAP based Spring web service without generating stubs on the client (as suggested by umpteen threads pointing to JAX-WS)?
Here is my complete scenario:
I have 2 web applications, say APP1 & APP2, both of which have Spring support. APP2 exposes it's APIs as Spring-WS that accept POJOs (Reqeust and Response objects) via. SOAP. Now, I want to call these web services from APP1, but would like to avoid having to create stubs using the WSDL frmo APP2. Is this possible?
For more detail, here is one of my web service's operation:
@PayloadRoot(localPart = "CreateNewRequest", namespace = "myNameSpace")
public CreateNewReqResponse createNewRequest( CreateNewReqRequest requestObj ) throws Exception
{
NewCase newCase = this.localSpringService.createNewCase( requestObj.getParam1(), requestObj.getParam2() );
CreateNewReqResponse response = this.objectFactory.createCreateNewReqResponse();
CreateNewReqResponseObject responseObject = this.objectFactory
.createCreateNewReqResponseObject();
if( null != newCase )
{
responseObject.setParam1( newCase.getParam1() );
responseObject.setParam2( newCase.setParam2() );
}
responseObject.setCaseRequestedDate( caseRequestedDate );
}
response.setResponseObject( responseObject );
return response;
}
Now, as you can see, the web service method accepts CreateNewReqRequest and returns CreateNewReqResponse. What I am trying to figure out is how can I call this web service from APP1, which does not have any clue about these classes - CreateNewReqRequest and CreateNewReqResponse? Is there no other way other than creating stubs in APP1 (from the WSDL) using JAX-WS?
Both the applications in question are our own (that is we have developed them) but run on different servers, because of which APP1 can not call the web service directly - cross-domain policy. Hence, I will writing a servlet in APP1 which will consume the web service exposed by APP2.
A: At the end of they day SOAP is simple a protocol on top of HTTP. So if you wish to forgo the usage of JAX-WS, you could start using raw http connections and hand code the SOAP requests and manually parse the SOAP Response on your own. This would simply mean you are re - inventing the wheel which is JAX-WS Client stubs.
So If you absolutely want to avoid Stub creation, have a go it at with HTTP post and get Messages at the WSDL end point URL.
What the client Stub does is simply abstract out that implementation for you. i.e. you will not have to deal with nitty gritty of SOAP/WSDL and http connection, you would be dealing with SOAP at a higher level, i.e through Java Objects.
You could also look into other libraries such as Apache CXF or Axis, but even there you will have to generate client stubs.
Thus the question you want to ask is, Do you want to really go in and manually muck around with http connections and SOAP XMLs or let the a framework take do that grunt work for you.
Reply to Nitin's comment follows below
To answer your questions, 1. Yes you will have to re-create the stubs if the WSDL changes, if you are not using the stubs but parsing everything manually you will have to change that code. So effectively there is no difference between the two. Your program will have to change if the WSDL (i.e. the contract between client and service) changes. This would be same even for REST, i.e. if the contract published by the service changes(Maybe the parameters, or the action etc), you will have to Change your client code. There is no escaping that. Hopefully, the public Webservices would have been designed in such a way to allow future modification, and such modifications wouldn't happen overnight thus giving you enough time to modify your code. This issue has nothing to do with how the web service has been implemented i.e. Spring Web Service has nothing to do with.
You seem to be missing the point of the Client stubs that a SOAP framework like JAX-WS, Axis, CXF generate for you. The Client Stub is one way to talk to the Web service. It is not the only way. The Client stub is the preferred method, because it abstracts outout the nitty gritties of handling SOAP calls manually. So, rather then you re inventing the wheel and implementing a SOAP(XML) parsing library, you can concentrate your efforts on the actual application that you are writing. In your actual program you would only have to deal with POJOs and never have to worry about how the SOAP magic happens i.e. how to convert your data and package it up in a SOAP message, send that SOAP Message to the Service using a HTTP connection, handle the response, Parse the response SOAP Message and retrieve the data you care about. All of this you avoid by using the POJOs. You set the properties for request, make a method call to the client stub service method, and recieve an object, everything else is you don't have to worry about (ideally).
I hope this clear things up a bit.
A: Take a look at WebServiceTemplate class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Library of standard compiler warnings/errors I am wondering whether you know of a way to demystify a given compiler warnings/error Xcode throws at you.
As a new developer to Objective-C, i would find it to be of value to know why some warnings happen, see examples of a code that would cause an error and explain the solution.
Are you aware of any resources that offer more insight into this?
A: "some warnings happen, see examples of a code that would cause an error and explain the solution."
It's best for you to provide code samples.
Why?
From http://developer.apple.com/library/ios/#documentation/DeveloperTools/gcc-4.2.1/gcc/Standards.html#Standards
"There is no formal written standard for Objective-C or Objective-C++. The most authoritative manual is “Object-Oriented Programming and the Objective-C Language”, available at a number of web sites..."
This means that tt's best for you to provide a specific warning and the associated code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: IIS7 Application pool best practices configuration Is there a guideline or site in where I can information about best practices for configuring IIS 7 Application Pools?
A: Take a look at http://technet.microsoft.com/en-us/library/cc753734(WS.10).aspx for an IIS 7 overview but look at the Understanding Sites, Applications and Virtual Directories section http://learn.iis.net/page.aspx/150/understanding-sites-applications-and-virtual-directories-on-iis-7/
Hard to really put together best practices since each setup is different, however it usually comes down to performance vs security.
The short answer there is to group similar security requirements into the same app pools but don't be afraid to make additional app pools.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Node to string without parent information I use xpath to get a NodeList. Then I use this code to get a string representation, but it also has the parent nodes.
StringWriter sw = new StringWriter();
try {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.transform(new DOMSource(node), new StreamResult(sw));
} catch (TransformerException e) {
e.printStackTrace();
}
return sw.toString();
How can I only get the self or decendant as string? And maybe steal the namespace declariations from the parent?
A: You don't show how the nodes in the node-set were selected. Most probably they are elements and this is the cause of your problem.
The solution is simple:
Construct and use an XPath expression that selects only the wanted text nodes.
For example, instead of :
/x/y/z
use
/x/y/z/text()
The last expression selects any text node that is a child of any element named z that is a child of any element named y that is a child of the top element, named x.
UPDATE:
The OP has clarified in a comment:
"Thanks, I tried this, but it only gives my real text in node. I want
a string reresentation of everything (nodes and text) in the current
node, without the information of the parent nodes. E.g if I would just
have a xml file and open it with a text editor and then copy out some
subtree. Do you know what I'm talking about?"
This can be accomplished in XSLT, using
<xsl:copy-of select="yourExpression/node()"/>
Alternatively, if your XML API allows it, for every selected node use:
theSelectedNode.InnerXml
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery UI Dialog Overlay Height & Width is not matching the window size Problem
Jquery UI overylay is causing browser's scroll bars to show up. I am using latest Jquery and Jquery UI without any theme.
Code
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="includes/js/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="includes/js/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
</head>
<body>
<a href="#">open modal</a>
<div id="dialog" style="display:none;">test</div>
<script type="text/javascript">
$('a').click(function () {
$('#dialog').dialog({modal: true});
});
</script>
</body>
</html>
This is extremely simple one. I have no idea why it creates scroll bars.
Any ideas on this one? I will be really glad.
Thank you in advance.
P.S.
I'm trying to add Jquery UI to a theme that I have to work with. I tried to eleminate as much as CSS rules as I can.
Right now I'm not so sure if this problem is not related to FireFox (7.0.1). When I use modal dialog window on the theme (UI has theme) I am working with and go back to test.html (without UI theme), problem occurs again.
If I am using in both windows (with theme) both is ok with the theme.
Does anyone experienced similar problem?
A: I solved my problem with using blockUI.
If anyone experiences similar problem here is another possible solution;
//Get The Height Of Window
var height = $(window).height();
//Change Overlay Height
$(".jquery-ui-dialog-overlay-element").css('height',height);
If you experience width related problems, you could do the same with adding var width = $(window).width(); variable to your page and changing overlay's width with .css()
A: I ran into this issue as well. Adding the following CSS fixed it.
.ui-widget-overlay {
position: fixed;
}
A:
Does anyone experienced similar problem?
I have and I added the following to my CSS. It puts the scroll bar on the page all the time in an inactive state when not needed. It prevents the page from appearing to "jump" when something is added to the page that activates the scrollbar.
html {overflow-y: scroll;}
Not sure if it works with your theme but worth a try.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Thrust Complex Transform of 3 different size vectors Hello I have this loop in C+, and I was trying to convert it to thrust but without getting the same results...
Any ideas?
thank you
C++ Code
for (i=0;i<n;i++)
for (j=0;j<n;j++)
values[i]=values[i]+(binv[i*n+j]*d[j]);
Thrust Code
thrust::fill(values.begin(), values.end(), 0);
thrust::transform(make_zip_iterator(make_tuple(
thrust::make_permutation_iterator(values.begin(), thrust::make_transform_iterator(thrust::make_counting_iterator(0), IndexDivFunctor(n))),
binv.begin(),
thrust::make_permutation_iterator(d.begin(), thrust::make_transform_iterator(thrust::make_counting_iterator(0), IndexModFunctor(n))))),
make_zip_iterator(make_tuple(
thrust::make_permutation_iterator(values.begin(), thrust::make_transform_iterator(thrust::make_counting_iterator(0), IndexDivFunctor(n))) + n,
binv.end(),
thrust::make_permutation_iterator(d.begin(), thrust::make_transform_iterator(thrust::make_counting_iterator(0), IndexModFunctor(n))) + n)),
thrust::make_permutation_iterator(values.begin(), thrust::make_transform_iterator(thrust::make_counting_iterator(0), IndexDivFunctor(n))),
function1()
);
Thrust Functions
struct IndexDivFunctor: thrust::unary_function<int, int>
{
int n;
IndexDivFunctor(int n_) : n(n_) {}
__host__ __device__
int operator()(int idx)
{
return idx / n;
}
};
struct IndexModFunctor: thrust::unary_function<int, int>
{
int n;
IndexModFunctor(int n_) : n(n_) {}
__host__ __device__
int operator()(int idx)
{
return idx % n;
}
};
struct function1
{
template <typename Tuple>
__host__ __device__
double operator()(Tuple v)
{
return thrust::get<0>(v) + thrust::get<1>(v) * thrust::get<2>(v);
}
};
A: To begin with, some general comments. Your loop
for (i=0;i<n;i++)
for (j=0;j<n;j++)
v[i]=v[i]+(B[i*n+j]*d[j]);
is the equivalent of the standard BLAS gemv operation
where the matrix is stored in row major order. The optimal way to do this on the device would be using CUBLAS, not something constructed out of thrust primitives.
Having said that, there is absolutely no way the thrust code you posted is ever going to do what your serial code does. The errors you are seeing are not as a result of floating point associativity. Fundamentally thrust::transform applies the functor supplied to every element of the input iterator and stores the result on the output iterator. To yield the same result as the loop you posted, the thrust::transform call would need to perform (n*n) operations of the fmad functor you posted. Clearly it does not. Further, there is no guarantee that thrust::transform would perform the summation/reduction operation in a fashion that would be safe from memory races.
The correct solution is probably going to be something like:
*
*Use thrust::transform to compute the (n*n) products of the elements of B and d
*Use thrust::reduce_by_key to reduce the products into partial sums, yielding Bd
*Use thrust::transform to add the resulting matrix-vector product to v to yield the final result.
In code, firstly define a functor like this:
struct functor
{
template <typename Tuple>
__host__ __device__
double operator()(Tuple v)
{
return thrust::get<0>(v) * thrust::get<1>(v);
}
};
Then do the following to compute the matrix-vector multiplication
typedef thrust::device_vector<int> iVec;
typedef thrust::device_vector<double> dVec;
typedef thrust::counting_iterator<int> countIt;
typedef thrust::transform_iterator<IndexDivFunctor, countIt> columnIt;
typedef thrust::transform_iterator<IndexModFunctor, countIt> rowIt;
// Assuming the following allocations on the device
dVec B(n*n), v(n), d(n);
// transformation iterators mapping to vector rows and columns
columnIt cv_begin = thrust::make_transform_iterator(thrust::make_counting_iterator(0), IndexDivFunctor(n));
columnIt cv_end = cv_begin + (n*n);
rowIt rv_begin = thrust::make_transform_iterator(thrust::make_counting_iterator(0), IndexModFunctor(n));
rowIt rv_end = rv_begin + (n*n);
dVec temp(n*n);
thrust::transform(make_zip_iterator(
make_tuple(
B.begin(),
thrust::make_permutation_iterator(d.begin(),rv_begin) ) ),
make_zip_iterator(
make_tuple(
B.end(),
thrust::make_permutation_iterator(d.end(),rv_end) ) ),
temp.begin(),
functor());
iVec outkey(n);
dVec Bd(n);
thrust::reduce_by_key(cv_begin, cv_end, temp.begin(), outkey.begin(), Bd.begin());
thrust::transform(v.begin(), v.end(), Bd.begin(), v.begin(), thrust::plus<double>());
Of course, this is a terribly inefficient way to do the computation compared to using a purpose designed matrix-vector multiplication code like dgemv from CUBLAS.
A: How much your results differ? Is it a completely different answer, or differs only on the last digits? Is the loop executed only once, or is it some kind of iterative process?
Floating point operations, especially those that repetedly add up or multiply certain values, are not associative, because of precision issues. Moreover, if you use fast-math optimisations, the operations may not be IEEE compilant.
For starters, check out this wikipedia section on floating-point numbers: http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: "Main loop" in a Java application on JBoss server I am creating a JBoss server to deploy a java application which will be a REST-like servlet taking data from requests and placing them into a SQL database.
My main question: Is it possible to set up a class on the JBoss server which is not run based on requests but is more like a main loop. I.e. just a loop which will "sleep" then check some information and either do something or sleep again.
Basically what I am trying to do is write a bunch of data to a file, once that file fills up to a certain point, write it all at once to the database to reduce connection overhead.
My best guess is that I could write any kind of class with a loop and have it run in the way I want(as long as my "sleep" technique was correct to allow for the servlet on the same JBoss time to run).
What I don't know though is how to get that main loop to run constantly; Just call it in the constructor?? The only way I know how to have things run on the server currently is to have a mapping set up in the web.xml and actively make a web page request information from the server...
Is there a better(read easier) service than JBoss and java for something like that
Thanks in advance, I have searched pretty hard for an explanation of something like this but it seems I am missing the right keyword...
A: Have a look at @Startup and @Singleton beans.
In short, you can write something like this:
@Startup @Singleton
public class MainLoopBean {
@PostConstruct
public void mainLoop() {
}
}
Ideally you should couple this with the timer service. When some amount of work is done and you want to pause, just schedule the method to be invoked later and return.
A: If the connection overhead is really affecting your performance, you can change the setting for connection pooling in JBoss. This would make the application simpler, more robust and scalable. Writing to one file does not scale up to multiple parallel connections. It also requires more IO than writing to the DB directly.
A: Why are you considering loops at all? Why not set up a JMS queue and a listener on it, that way whenever something happens, you're able to respond. No need for loops, no special hooks, nothing.
Alternatively, if you're actually interested in doing something more complicated, look into the Java Connector Architecture, which provides you these kinds of hooks as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jquery show/hide button to change tooltip I have the jquery code below that changes the text in the button to show/hide but I would also like to change the tooltip/title when the button is hovered over with the mouse to also say show/hide
$('#HideShow').click(function()
{
if ($(this).text() == "Show")
{
$(this).text("Hide");
}
else
{
$(this).text("Show");
};
});
How can I use jquery to also change the tooltip/title to show/hide when the button is changed?
A: $('#HideShow').click(function() {
if ($(this).text() == "Show") {
$(this).text("Hide").attr("title", "Hide");
} else {
$(this).text("Show").attr("title", "Show");
}
});
A: use the attr command
so $(this).attr("attribute to change", "new value");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to handle forward references of XML IDREF with JAXB XmlAdapter during unmarshal? Is it possible to handle forward references of XML IDREF elements in JAXB XmlAdapter during the unmarshal process? For example, I have the following XML complexType:
<xs:complexType name="person">
<xs:complexContent>
<xs:sequence>
<xs:element name="dateOfBirth" type="xs:dateTime" minOccurs="0"/>
<xs:element name="firstName" type="xs:string" minOccurs="0"/>
<xs:element name="gender" type="xs:string" minOccurs="0"/>
<xs:element name="guardian" type="xs:IDREF" minOccurs="0"/>
<xs:element name="homePhone" type="xs:string" minOccurs="0"/>
<xs:element name="lastName" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexContent>
</xs:complexType>
where the guardian field could reference another Person-type element elsewhere in the document. I am currently using an XmlAdapter when marshalling so that the first time an object is marshalled, it is marshalled by containment, and any subsequent occurances of this object are marshalled by reference. See a previous question of mine. However, due to how my XML instance documents are created, the first occurrence of a Person element could happen after an IDREF to it occurs.
Is this something that is possible? Or do I need to approach this differently? Thanks!
A: I have an answer to your related question I outlined how an XmlAdapter could be used to implement the use case where the first occurrence of an object was marshalled via containment/nesting and all other occurrences were marshalled by reference:
*
*Can JAXB marshal by containment at first then marshal by @XmlIDREF for subsequent references?
Option #1 - @XmlID/@XmlIDREF
If all of your Person objects are all represented through nesting and you want to introduce some key based relationships then you are best of using @XmlID to mark a field/property as the key, and @XmlID to map a field/property as a foreign key. Your Person class would look something like:
@XmlAccessorType(XmlAccessType.FIELD)
public class Person {
@XmlID
private String id;
@XmlIDREF
private Person guardian;
}
For More Information
*
*http://blog.bdoughan.com/2010/10/jaxb-and-shared-references-xmlid-and.html
Option #2 - Using XmlAdapter
If you updated the XmlAdapter from my previous answer to be:
package forum7587095;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class PhoneNumberAdapter extends XmlAdapter<PhoneNumberAdapter.AdaptedPhoneNumber, PhoneNumber>{
private List<PhoneNumber> phoneNumberList = new ArrayList<PhoneNumber>();
private Map<String, PhoneNumber> phoneNumberMap = new HashMap<String, PhoneNumber>();
@XmlSeeAlso(AdaptedWorkPhoneNumber.class)
@XmlType(name="phone-number")
public static class AdaptedPhoneNumber {
@XmlAttribute public String id;
public String number;
public AdaptedPhoneNumber() {
}
public AdaptedPhoneNumber(PhoneNumber phoneNumber) {
id = phoneNumber.getId();
number = phoneNumber.getNumber();
}
public PhoneNumber getPhoneNumber() {
PhoneNumber phoneNumber = new PhoneNumber();
phoneNumber.setId(id);
phoneNumber.setNumber(number);
return phoneNumber;
}
}
@XmlType(name="work-phone-number")
public static class AdaptedWorkPhoneNumber extends AdaptedPhoneNumber {
public String extension;
public AdaptedWorkPhoneNumber() {
}
public AdaptedWorkPhoneNumber(WorkPhoneNumber workPhoneNumber) {
super(workPhoneNumber);
extension = workPhoneNumber.getExtension();
}
@Override
public WorkPhoneNumber getPhoneNumber() {
WorkPhoneNumber phoneNumber = new WorkPhoneNumber();
phoneNumber.setId(id);
phoneNumber.setNumber(number);
phoneNumber.setExtension(extension);
return phoneNumber;
}
}
@Override
public AdaptedPhoneNumber marshal(PhoneNumber phoneNumber) throws Exception {
AdaptedPhoneNumber adaptedPhoneNumber;
if(phoneNumberList.contains(phoneNumber)) {
if(phoneNumber instanceof WorkPhoneNumber) {
adaptedPhoneNumber = new AdaptedWorkPhoneNumber();
} else {
adaptedPhoneNumber = new AdaptedPhoneNumber();
}
adaptedPhoneNumber.id = phoneNumber.getId();
} else {
if(phoneNumber instanceof WorkPhoneNumber) {
adaptedPhoneNumber = new AdaptedWorkPhoneNumber((WorkPhoneNumber)phoneNumber);
} else {
adaptedPhoneNumber = new AdaptedPhoneNumber(phoneNumber);
}
phoneNumberList.add(phoneNumber);
}
return adaptedPhoneNumber;
}
@Override
public PhoneNumber unmarshal(AdaptedPhoneNumber adaptedPhoneNumber) throws Exception {
PhoneNumber phoneNumber = phoneNumberMap.get(adaptedPhoneNumber.id);
if(null != phoneNumber) {
if(adaptedPhoneNumber.number != null) {
phoneNumber.setNumber(adaptedPhoneNumber.number);
}
return phoneNumber;
}
phoneNumber = adaptedPhoneNumber.getPhoneNumber();
phoneNumberMap.put(phoneNumber.getId(), phoneNumber);
return phoneNumber;
}
}
Then you will be able to unmarshal XML documents that look like the following where the reference happens first:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
<phone-number id="A"/>
<phone-number id="B">
<number>555-BBBB</number>
</phone-number>
<phone-number id="A">
<number>555-AAAA</number>
</phone-number>
<phone-number xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="work-phone-number" id="W">
<number>555-WORK</number>
<extension>1234</extension>
</phone-number>
<phone-number xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="work-phone-number" id="W"/>
</customer>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Object's ownership, after "return". Clarification needed Assuming, the following declaration for class A
@property(nonatomic, assign) DoublyLinkedList *doublyLinkedList;
, that as part of init, initialized the object
- (id)init {
self = [super init];
if (self) {
doublyLinkedList = [[DoublyLinkedList alloc] init];
}
return self;
}
and that a method
- (DoublyLinkedList*) doSomethingAndReturn {
that ultimately
return doublyLinkedList;
Does class A owns the doublyLinkedList after the return?
A: EDIT: init added with alloc
You are not calling retain on it, but in init you are calling alloc on it, so it does have a retain count of 1 -- you own it and you should release it in dealloc.
You could simply alloc it and release it in dealloc. The caller of the property can choose whether to retain. Another option would be to create the object in init, autorelease it and then assign it to the property with (retain) instead of (assign). That way, if other places in the code alloc and assign to that property, the object you alloc'd will get released. Then in dealloc, what it's currently assigned to will get released.
Yet another option if you don't want others to set it would be to have a (readonly) property and a _doubleLinkedList iVar and then @synthesize doublyLinkedList = _doubleLinkedList. Then you can allocate it once in init and know that no one else will assign it, and then release it in dealloc.
A good analogy is that when you retain, you're putting a leash on it. Multiple items can put a leash on that object. It is freed only when everyone has taken the leash off.
A good guide to read:
Apple's Memory Management Programming Guide
Specifically from that doc, these rules help:
You own any object you create You create an object using a method
whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for
example, alloc, newObject, or mutableCopy).
You can take ownership of an object using retain A received object
is normally guaranteed to remain valid within the method it was
received in, and that method may also safely return the object to its
invoker. You use retain in two situations: (1) In the implementation
of an accessor method or an init method, to take ownership of an
object you want to store as a property value; and (2) To prevent an
object from being invalidated as a side-effect of some other operation
(as explained in “Avoid Causing Deallocation of Objects You’re
Using”).
When you no longer need it, you must relinquish ownership of an
object you own You relinquish ownership of an object by sending it a
release message or an autorelease message. In Cocoa terminology,
relinquishing ownership of an object is therefore typically referred
to as “releasing” an object.
You must not relinquish ownership of an object you do not own This
is just corollary of the previous policy rules, stated explicitly.
A: Objects aren't really "owned" in that way. Objective-C will free up the memory for an object when its retain count gets to 0. If class A depends on doubleLinkedList being "kept alive" as long as an instance of class A is alive, then object A retains doublyLinkedList to increase that retain count by 1. When object A returns a reference to doublyLinkedList as you have above, then the caller who receives that result may elect to retain the object as well, which would increase the retain count by one again.
So try not to think of it as owning an object. Instead, think of it as expressing an interest in the existence of an object. As long as someone continues to be interested in that object, as expressed by its retain count, then the object will not be deallocated.
A: As you've defined it, class A has not ever retained doublyLinkedList. So no, it has no stake in it. In fact because doublyLinkedList is not retained by class A, it could be deallocated at any time during execution and cause an EXEC_BAD_ACCESS crash.
There are two obvious ways to deal with this.
*
*Class A should retain doublyLinkedList while it's using it, and autorelease it before it returns it.
*Another 'parent' object can retaining both doublyLinkedList and the instance of class A, and it's up to that 'parent' object to make sure doublyLinkedList doesn't get deallocated while the class A object is using it.
Edit:
If you alloc-init the object when you initialize Class A, as you've added above, then you should only release the object when Class A is deallocated. This makes for a simple object life-cycle. An instance of Class A is created, it creates a DLL object. That object persists until the Class A instance is destroyed. If other objects want to use the DLL, they simply request it from the class A instance, and retain it.
The goal with retain release is to code in such a way that you can be sure you have an EVEN number of retain calls, and release calls on an object. For every:
- (id)init {
self = [super init];
if (self) {
doublyLinkedList = [[DoublyLinkedList alloc] init];
}
return self;
}
You need a:
-(void)dealloc {
[super dealloc];
[doublyLinkedList release]
}
If your class a object is going to be creating and processing more than one DLL object, then don't create it in -(id)init and use retain for the property declaration.
then:
ClassA *newClassAObject = [[ClassA alloc] init]; // create class a object
newClassAObject.doublyLinkedList = [[[DoublyLinkedList alloc] init] autorelease]; // make a DLL object, only retained by class a object.
DoublyLinkedList *dll = [newClassAObject doSomethingAndReturn]; // process the list somehow
[dll retain] // we own this now
newClassAObject.doublyLinkedList = nil; // class A object gives up interest in dll.
newClassAObject.doublyLinkedList = [[[DoublyLinkedList alloc] init] autorelease]; // now process another one.
... and on and on ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is a servicebus? I've read about nservicebus countless times on the net, but still don't get what a service bus is.
All I think is it is a way for very disparate systems to talk to each other? In which case, I don't see why it is any better than WCF?
I've seen the thread on here about what a service bus is but it still hasn't clicked.
Thanks
A: Assuming that you have read these pages http://particular.net/nservicebus and http://docs.particular.net/nservicebus/architecture/nservicebus-and-wcf you'll find that NServiceBus makes communicating with services much easier.
It wraps WCF by taking care of the poisoned and transactional elements of messaging as well as offering out of the box Pub / Sub style messaging. Benefits that NServiceBus will take care of include:
*
*Long-running stateful processes Using WF on top
*On-premise messaging
*Client can send messages if server is offline
*Poison message detection and dispatching
*Poison messages re-processing
*Subscriptions persist after restart
*Polymorphic message dispatch
*Polymorphic message routing
*Message-driven unit testing
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: sCrypt implementation in JavaScript? Someone asked about a JavaScript implementation of bCrypt a while back and appears to have written their own code to handle the implementation. Does anyone have an implementation of sCrypt in JavaScript?
A: If you are talking about tenebrix, the choice of scrypt was better then bcrypt for the goals set. I so far have only found one incomplete javascript implementation of scrypt and hit on this page while searching.
https://github.com/byrongibson/scrypt-js https://github.com/cheongwy/node-scrypt-js was all I found so far, and seems no code yet.
Guess as a new reason I can't just comment on this above like I wanted, sigh.
A: https://github.com/tonyg/js-scrypt is an emscripten-compiled version of Colin Percival's scrypt() function.
A: Here are the two I can find:
*
*https://github.com/barrysteyn/node-scrypt
*https://github.com/cheongwy/node-scrypt-js
I've tried only barrysteyn's node-scrypt, and its excellent. He recently put a lot of effort into making the library conform to javascript conventions, and the API is great.
A: The answer linked above points to a project that no longer exists.
This project, however, is still around: https://github.com/tonyg/js-scrypt
A: I'll toss my implementation into the ring: https://github.com/cryptocoinjs/scryptsy. It is based upon https://github.com/cheongwy/node-scrypt-js, but has been cleaned up and tested in both Node.js and the browser.
A: Here are two options:
*
*https://github.com/ricmoo/scrypt-js
*https://github.com/dchest/scrypt-async-js
They're pretty comparable.
A: Tony's works great in chrome, chrome's js executes cost of 16384 faster than CryptSharp's SCrypt does. Around 200ms for chrome and 450ms for CryptSharp.
Trouble is that IE takes upwards of 24 seconds and FF upwards of 16 seconds.
Unfortunately, not all browsers are created equal..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Can I use Kinect on a Mac? Studying vision, I would like to play with the Microsoft Kinect.
Can I use it on my Mac?
I have not found any Library for Mac and fear virtualization on my laptop to use Linux.
A: I've accessed Kinect data on OSX using openframeworks and the ofxKinect addon (which uses libfreenect and libusb).
It's not the only option, just I've used and worked 'out of the box'.
A: Try downloading the Zigfu Dev Bundle for mac (http://www.zigfu.com) - that should get you up to speed with kinect development on mac.
A: Using Kinect on Mac is as easy as ordering Latte.
But there is also a lot of confusion on the Internet and sites that seem to be old and give you the wrong advice such as installing a separate sensor library in addition to OpenNI. Just go to the basic website and download SDK for your MAC:
http://www.openni.org/openni-sdk/
You might need to have prerequsities though I assume you have already installed them, such as:
sudo port install libtool
sudo port install doxygen
restart comp
sudo port install libusb-devel +universal
Troubleshooting:
"sudo rm -f /opt/local/lib/libusb-1.0.0.dylib"
"sudo port clean libusb"
"sudo port install libusb +universal"
No need to compile anything. You should be able to run ./Samples/Bin/SimpleViewer right away after you run sudo ./install.sh.The PROBLEM might be that you have already tried to run it unsuccessfully and put a camera in the wrong state. I have seen errors such as USB intercase cannot be set etc. as a side effect.
Running your code in Eclipse is a different story and may require a few extra steps and changing your Ubuntu code (using openni namespace, different includes, etc.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Adjust code to detect multiple circles instead of just 1 in OPENCV I have got this circle detection working but only detects 1 circle. How would I adjust code to detect multiple circles(max circles that will be detected is 22 as using it for snooker). I presume i would be editing the circle detectoin method but i am stuck:(
#include <stdio.h>
#include "cv.h"
#include "highgui.h"
#include <iostream>
#include <math.h>
#include <string.h>
#include <conio.h>
using namespace std;
IplImage* img = 0;
CvMemStorage * cstorage;
CvMemStorage * hstorage;
void detectCircle( IplImage *frame );
int main( int argc, char **argv )
{
CvCapture *capture = 0;
IplImage *frame = 0;
int key = 0;
hstorage = cvCreateMemStorage( 0 );
cstorage = cvCreateMemStorage( 0 );
//CvVideoWriter *writer = 0;
//int colour = 1;
//int fps = 25;
//int frameW = 640;
//int frameH = 480;
//writer = cvCreateVideoWriter("test.avi",CV_FOURCC('P', 'I', 'M', '1'),fps,cvSize(frameW,frameH),colour);
//initialise camera
capture = cvCaptureFromCAM( 0 );
//check if camera present
if ( !capture )
{
fprintf( stderr, "cannot open webcam\n");
return 1;
}
//create a window
cvNamedWindow( "Snooker", CV_WINDOW_AUTOSIZE );
while(key !='q')
{
//get frame
frame = cvQueryFrame(capture);
//int nFrames = 50;
//for (int i=0; i<nFrames;i++){
//cvGrabFrame(capture);
//frame = cvRetrieveFrame(capture);
//cvWriteFrame(writer, frame);
//}
//check for frame
if( !frame ) break;
detectCircle(frame);
//display current frame
//cvShowImage ("Snooker", frame );
//exit if Q pressed
key = cvWaitKey( 20 );
}
// free memory
cvDestroyWindow( "Snooker" );
cvReleaseCapture( &capture );
cvReleaseMemStorage( &cstorage);
cvReleaseMemStorage( &hstorage);
//cvReleaseVideoWriter(&writer);
return 0;
}
**void detectCircle( IplImage * img )
{
int px;
int py;
int edge_thresh = 1;
IplImage *gray = cvCreateImage( cvSize(img->width,img->height), 8, 1);
IplImage *edge = cvCreateImage( cvSize(img->width,img->height), 8, 1);
cvCvtColor(img, gray, CV_BGR2GRAY);
gray->origin = 1;
// color threshold
cvThreshold(gray,gray,100,255,CV_THRESH_BINARY);
// smooths out image
cvSmooth(gray, gray, CV_GAUSSIAN, 11, 11);
// get edges
cvCanny(gray, edge, (float)edge_thresh, (float)edge_thresh*3, 5);
// detects circle
CvSeq* circle = cvHoughCircles(gray, cstorage, CV_HOUGH_GRADIENT, 1, gray->height/50, 5, 35);
// draws circle and its centerpoint
float* p = (float*)cvGetSeqElem( circle, 0 );
if( p==null ){ return;}
cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), 3, CV_RGB(255,0,0), -1, 8, 0 );
cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), cvRound(p[2]), CV_RGB(200,0,0), 1, 8, 0 );
px=cvRound(p[0]);
py=cvRound(p[1]);**
cvShowImage ("Snooker", img );
}
A: Your code finds all circles - you just draw one:
// draws circle and its centerpoint
float* p = (float*)cvGetSeqElem( circle, 0 );
if( p==null ){ return;}
cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), 3, CV_RGB(255,0,0), -1, 8, 0 );
cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), cvRound(p[2]), CV_RGB(200,0,0), 1, 8, 0);
px=cvRound(p[0]);
py=cvRound(p[1]);
You should do it in cycle, something like:
for( int i=0; i < circles->total; i++ )
{
float* p = (float*) cvGetSeqElem( circles, i );
// ... d draw staff
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: iPhone app crashes on device but not simulator. Accessing local files with UIWebView, possible [NSBundle mainBundle] issue? I was hoping you guys could help me what is wrong with my code that is causing my app to crash on my device but not the simulator. It is a very simple app, I just have local files displayed in a UIWebView. Here is what I am using in my .m
NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"localHTML/mobile"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
I'm only posting this code because I feel like something in here is causing the problem, but what do I know, let me know if you need to see something else.
Here is the crash log. Some of this probably isn't helpful, but I figured I'll post the entire thing since I don't know what to look for.
Incident Identifier: 9598C96E-EA38-4C54-B39F-BBD245648E48
CrashReporter Key: cb7605a41daea519012d6fd4f52c4b19fb584743
Hardware Model: iPhone3,1
Process: Cannon Mobile [5129]
Path: /var/mobile/Applications/E5760D01-689A-41A3-A6CA-45E007B7C27A/Cannon Mobile.app/Cannon Mobile
Identifier: Cannon Mobile
Version: ??? (???)
Code Type: ARM (Native)
Parent Process: launchd [1]
Date/Time: 2011-09-30 19:26:57.951 -0400
OS Version: iPhone OS 4.3.3 (8J2)
Report Version: 104
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x00000000, 0x00000000
Crashed Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 libsystem_kernel.dylib 0x3558fa1c __pthread_kill + 8
1 libsystem_c.dylib 0x356663b4 pthread_kill + 52
2 libsystem_c.dylib 0x3565ebf8 abort + 72
3 libstdc++.6.dylib 0x35628a64 __gnu_cxx::__verbose_terminate_handler() + 376
4 libobjc.A.dylib 0x3449d06c _objc_terminate + 104
5 libstdc++.6.dylib 0x35626e36 __cxxabiv1::__terminate(void (*)()) + 46
6 libstdc++.6.dylib 0x35626e8a std::terminate() + 10
7 libstdc++.6.dylib 0x35626f5a __cxa_throw + 78
8 libobjc.A.dylib 0x3449bc84 objc_exception_throw + 64
9 CoreFoundation 0x3098048a +[NSException raise:format:arguments:] + 62
10 CoreFoundation 0x309804c4 +[NSException raise:format:] + 28
11 Foundation 0x341dd188 -[NSURL(NSURL) initFileURLWithPath:] + 64
12 Foundation 0x341dd128 +[NSURL(NSURL) fileURLWithPath:] + 24
13 Cannon Mobile 0x000033da -[Cannon_MobileViewController refresh:] (Cannon_MobileViewController.m:48)
14 Cannon Mobile 0x000034ec -[Cannon_MobileViewController viewDidLoad] (Cannon_MobileViewController.m:62)
15 UIKit 0x30a18f08 -[UIViewController view] + 104
16 UIKit 0x30a172ae -[UIWindow addRootViewControllerViewIfPossible] + 26
17 UIKit 0x30b42538 -[UIWindow setRootViewController:] + 160
18 Cannon Mobile 0x00002fb6 -[Cannon_MobileAppDelegate application:didFinishLaunchingWithOptions:] (Cannon_MobileAppDelegate.m:22)
19 UIKit 0x30a1781a -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 766
20 UIKit 0x30a11b5e -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 266
21 UIKit 0x309e67d0 -[UIApplication handleEvent:withNewEvent:] + 1108
22 UIKit 0x309e620e -[UIApplication sendEvent:] + 38
23 UIKit 0x309e5c4c _UIApplicationHandleEvent + 5084
24 GraphicsServices 0x30269e70 PurpleEventCallback + 660
25 CoreFoundation 0x30957a90 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 20
26 CoreFoundation 0x30959838 __CFRunLoopDoSource1 + 160
27 CoreFoundation 0x3095a606 __CFRunLoopRun + 514
28 CoreFoundation 0x308eaebc CFRunLoopRunSpecific + 224
29 CoreFoundation 0x308eadc4 CFRunLoopRunInMode + 52
30 UIKit 0x30a10d42 -[UIApplication _run] + 366
31 UIKit 0x30a0e800 UIApplicationMain + 664
32 Cannon Mobile 0x00002f20 main (main.m:14)
33 Cannon Mobile 0x00002ec8 start + 32
Thread 1:
0 libsystem_kernel.dylib 0x355903ec __workq_kernreturn + 8
1 libsystem_c.dylib 0x356676d8 _pthread_wqthread + 592
2 libsystem_c.dylib 0x35667bbc start_wqthread + 0
Thread 2 name: Dispatch queue: com.apple.libdispatch-manager
Thread 2:
0 libsystem_kernel.dylib 0x35590fbc kevent + 24
1 libdispatch.dylib 0x35261032 _dispatch_mgr_invoke + 706
2 libdispatch.dylib 0x3526203a _dispatch_queue_invoke + 86
3 libdispatch.dylib 0x352615ea _dispatch_worker_thread2 + 186
4 libsystem_c.dylib 0x3566758a _pthread_wqthread + 258
5 libsystem_c.dylib 0x35667bbc start_wqthread + 0
Thread 3 name: WebThread
Thread 3:
0 libsystem_kernel.dylib 0x3558dc5c semaphore_wait_signal_trap + 8
1 libsystem_kernel.dylib 0x3558df52 semaphore_wait_signal + 2
2 libsystem_c.dylib 0x35664734 pthread_mutex_lock + 256
3 WebCore 0x35f533ee _ZL17_WebTryThreadLockb + 150
4 WebCore 0x35f5332e _ZL14WebRunLoopLockP19__CFRunLoopObservermPv + 14
5 CoreFoundation 0x30957a2e __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 10
6 CoreFoundation 0x3095945e __CFRunLoopDoObservers + 406
7 CoreFoundation 0x3095a760 __CFRunLoopRun + 860
8 CoreFoundation 0x308eaebc CFRunLoopRunSpecific + 224
9 CoreFoundation 0x308eadc4 CFRunLoopRunInMode + 52
10 WebCore 0x35f5327e _ZL12RunWebThreadPv + 382
11 libsystem_c.dylib 0x3566630a _pthread_start + 242
12 libsystem_c.dylib 0x35667bb4 thread_start + 0
Thread 0 crashed with ARM Thread State:
r0: 0x00000000 r1: 0x00000000 r2: 0x00000001 r3: 0x00000000
r4: 0x3f86348c r5: 0x00000006 r6: 0x1d59051c r7: 0x2fe10f90
r8: 0x3ed19bf8 r9: 0x00000065 r10: 0x3180e2f0 r11: 0x3ed0c964
ip: 0x00000148 sp: 0x2fe10f84 lr: 0x3619b3bb pc: 0x360c4a1c
cpsr: 0x00000010
Thanks so much for your help.
A: Check the application bundle being produced by Xcode. Does it contain the localHTML/mobile directory and all the files you are expecting?
(Right-click on appname.app under the Products section in the Xcode navigator panel, select 'Reveal in Finder', then right-click on the app bundle in Finder and select 'Show package contents')
A: Well, I'm not exactly sure why this is crashing. From the looks of it you're not doing anything radically wrong. I'd guess it had something to do with the file path, or the file not being there. The line that's killing it is [NSURL fileURLWithPath:path] and you can skip that line by using - (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)ext subdirectory:(NSString *)subpath instead of pathForResource:. Not sure if that will solve your problem, but it's worth a shot.
Edit: oh, one difference between the simulator and the device, is the file system on the device is case-sensitive, while it's not on osx/the simulator. Could there be a case issue in your file name or file path?
Try some NSLog's to see where the problem is.
NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"localHTML/mobile"];
NSLog(@"Path is %@",path);
NSURL *url = [NSURL fileURLWithPath:path];
NSLog(@"URL is %@",url);
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
If you see in the console "Path is null" then you're specifying something wrong in your pathForResource call.
A thought:
If you've added files to your Xcode project, but not included them in the build target, they won't be added to app bundle.
if localHTML and mobile are "groups" in Xcode, not actual folders, then they're ignored when the app is compiled. Xcode groups mean NOTHING, in relation to the compiled app (look into folder references for a way to make folders in your app bundle).
A: Since you haven't posted the exception, I'm guessing the problem is you passed nil to +fileURLWithPath:. Why would you get nil on the device but not the simulator? Simple answer: case sensitivity. The filesystem on the device is case sensitive, but the default HFS+ filesystem on Mac OS X is not. You're asking for localHTML/mobile/index.html, but if any of those characters have the wrong case, then -pathForResource:ofType:inDirectory: is going to end up handing back nil on the device. Since you haven't tested if it's nil, you're passing it directly to +fileURLWithPath: and this is likely throwing an exception as a result.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Vim bind some hotkeys different to filetype I want to bind something like this:
*
*For CSS, HTML files: <c-space> <c-x><c-n>
*For Ruby files: <c-space> <c-x><c-u>
How to do this?
A: The documentation is more complete, precise and correct, but briefly:
Make a file in your ftplugin folder (create this folder if necessary) starting with the filetype you'd like to use.
├── vim
│ ├── after
│ ├── autoload
│ ├── bundle
│ ├── ftplugin
│ │ ├── python.vim
│ │ ├── rnoweb.vim
│ │ └── tex.vim
│ └── syntax
and in one of of these files, the python.vim one for example, a line like
noremap! <buffer> <F5> <Esc>:w<CR>:!python % <CR>
will be a bind only defined for this filetype, just in this buffer. Make sure filetype plugin on or similar appears in your vimrc.
Edit: excellent suggestions by Peter Rincker incorporated: noremap version of map command and <buffer> flag. He also reminds us to use setlocal instead of set in our filetype plugin files.
A: Use autocmd:
autocmd filetype css inoremap <buffer> <c-space> <c-x><c-n>
autocmd filetype html inoremap <buffer> <c-space> <c-x><c-n>
autocmd filetype ruby inoremap <buffer> <c-space> <c-x><c-u>
A: Put the following in your .vimrc. Substitute the do stuff lines with your bindings.
:if match(@%, ".css") >=0
: do css stuff
:endif
:if match(@%, ".rb") >=0
: do ruby stuff
:endif
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: I want to get all contacts in windows phone 7 in a list I want to get a list of all contacts in my windows phone OS to edit in all contacts and save it ?
I know that Microsoft.Phone.Tasks; get contacts application can I get this contacts and edit it without show it from this class ?
I want it in windows phone 7 not 7.1
A: Contacts are readonly in Mango and are not available at all before Mango. Here how you can read them in Mango: http://msdn.microsoft.com/en-us/library/hh286414%28v=vs.92%29.aspx
I think with the choosers from Microsoft.Phone.Tasks you can only add new contacts (with user's consent). You can't delete or modify existing contacts.
A: You can do lot of those stuff within windows live.com site.
I wanted to get all contacts from my Mango, but i couldn't get it within the phone.
So, what I did was,
I synced all my contacts to SkyDrive on windows live, and exported it from live.com web site.
you can export contacts to a excel sheet and do what ever you want from it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: CSS rounded corner for on first-generation iPhones The following code works in all desktop browsers Chrome and Safari on the Desktop as well as recent iPhones and all Android devices I've tested. However, in first-generation iPhones and the iPhone 3G, the top left corner of the <img> is not rounded.
The other CSS I have for rounding corners (on <h1> elements) on the iPhone seems to work fine on these older devices. It's just the rounding for the <img> element that does not work.
Relevant Javascript:
var profilePhoto = document.createElement("img");
profilePhoto.setAttribute("src","http://example.com/photo.jpg");
profilePhoto.setAttribute("alt","");
profilePhoto.setAttribute("class","menu-first");
profilePhoto.setAttribute("style","float:left; border:0; padding:0!important; margin-top:0!important; -webkit-border-top-right-radius:0; -webkit-border-top-left-radius:.5em;");
document.getElementById('menu-container').appendChild(profilePhoto);
Relevant HTML:
<div id="menu-container"></div>
I am aware of the "rounded corners don't show up if the radius is greater than half the image height or width" issue, and that's not what is going on here. The radius is a tiny fraction of the image size.
JSFiddle: http://jsfiddle.net/RaK3T/
(Wow, JSFiddle actually works on iPhone 3G, that's awesome!)
UPDATE: I suppose it very well might be the iOS version that matters more than the phone model. It appears to work fine in iOS v4.3.2, but not in iOS v3.
A: It sounds like you're running into an issues in certain older browsers, whereby the border is drawn as a logical layer beneath the foreground image.
The effect is that the rounded borders are indeed drawn, but the foreground image is then placed on top of them, and is not clipped. This obviously only affects the <img> tag, since it's the only tag that has foreground images.
This issue was a big deal a few years ago. It afflicted some browsers but not others, but certainly for older versions of Firefox and most Webkit browsers, it was an issue.
The problem was quickly spotted and was fixed (somewhat quicker with Webkit than Firefox, if memory serves), and we all moved on.
But it is still an issue for web developers needing to support older versions of these browsers.
There are three workable solutions:
*
*Use a background-image style instead of a foreground <img>.
*Ignore the problem and let older browsers live with square corners (oh the horror!).
*Use any one of the old-school rounded corner hacks that draw the corners in manually.
Personally my preference is for option 2, I appreciate it doesn't actually answer the question, but I don't have an issue with it: it's a cosmetic detail on old browsers; you wouldn't try to get this working on IE6, would you? (would you??).
If that isn't good enough for you then option 1 is the typical solution that most people went with at the time. But isn't good semantically, and has issues if you need to scale the image, etc.
And the less said about option 3, the better.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Why am I getting this nhibernate NonUniqueObjectException? The following method queries my database, using a new session. If the query succeeds, it attaches (via "Lock") the result to a "MainSession" that is used to support lazy loading from a databound WinForms grid control.
If the result is already in the MainSession, I get the exception:
NHibernate.NonUniqueObjectException : a different object with the same identifier value was already associated with the session: 1, of entity: BI_OverlordDlsAppCore.OfeDlsMeasurement
when I attempt to re-attach, using the Lock method.
This happens even though I evict the result from the MainSession before I attempt to re-attach it.
I've used the same approach when I update a result, and it works fine.
Can anyone explain why this is happening?
How should I go about debugging this problem?
public static OfeMeasurementBase GetExistingMeasurement(OverlordAppType appType, DateTime startDateTime, short runNumber, short revision)
{
OfeMeasurementBase measurement;
var mainSession = GetMainSession();
using (var session = _sessionFactory.OpenSession())
using (var transaction = session.BeginTransaction())
{
// Get measurement that matches params
measurement =
session.CreateCriteria(typeof(OfeMeasurementBase))
.Add(Expression.Eq("AppType", appType))
.Add(Expression.Eq("StartDateTime", startDateTime))
.Add(Expression.Eq("RunNumber", runNumber))
.Add(Expression.Eq("Revision", revision))
.UniqueResult() as OfeMeasurementBase;
// Need to evict from main session, to prevent potential
// NonUniqueObjectException if it's already in the main session
mainSession.Evict(measurement);
// Can't be attached to two sessions at once
session.Evict(measurement);
// Re-attach to main session
// Still throws NonUniqueObjectException!!!
mainSession.Lock(measurement, LockMode.None);
transaction.Commit();
}
return measurement;
}
A: I resolved the problem after finding this Ayende post on Cross Session Operations.
The solution was to use ISession.Merge to get the detached measurement updated in the main session:
public static OfeMeasurementBase GetExistingMeasurement(OverlordAppType appType, DateTime startDateTime, short runNumber, short revision)
{
OfeMeasurementBase measurement;
var mainSession = GetMainSession();
using (var session = _sessionFactory.OpenSession())
using (var transaction = session.BeginTransaction())
{
// Get measurement that matches params
measurement =
session.CreateCriteria(typeof(OfeMeasurementBase))
.Add(Expression.Eq("AppType", appType))
.Add(Expression.Eq("StartDateTime", startDateTime))
.Add(Expression.Eq("RunNumber", runNumber))
.Add(Expression.Eq("Revision", revision))
.UniqueResult() as OfeMeasurementBase;
transaction.Commit();
if (measurement == null) return null;
// Merge back into main session, in case it has changed since main session was
// originally loaded
var mergedMeasurement = (OfeMeasurementBase)mainSession.Merge(measurement);
return mergedMeasurement;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android SeekBar Flipped Horizontally With the Android SeekBar, you can normally drag the thumb to the left or to the right and the yellow progress color is to the left of the thumb. I want the exact opposite, essentially flipping the yellow progress color to the right of the thumb and flipping the entire SeekBar on the y-axis.
Can anyone point me in the right direction? Thanks!
A: Have you tried seekbar.setRotation( 180 )? It flips the seekbar 180 degrees and is upside down, meaning left side is max, right side is 0 with the color on the right of the thumb. No need to create a custom seekbar this way.
A: After fiddling around with some code this is what I got and it seems to work pretty well. Hopefully it will help someone else in the future.
public class ReversedSeekBar extends SeekBar {
public ReversedSeekBar(Context context) {
super(context);
}
public ReversedSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ReversedSeekBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
float px = this.getWidth() / 2.0f;
float py = this.getHeight() / 2.0f;
canvas.scale(-1, 1, px, py);
super.onDraw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
event.setLocation(this.getWidth() - event.getX(), event.getY());
return super.onTouchEvent(event);
}
}
This was thrown together with the help of these two questions:
*
*How can you display upside down text with a textview in Android?
*How can I get a working vertical SeekBar in Android?
A: You should look into making a custom progress bar. Considering what you want to do, you already have the images you need in the Android SDK. I'd extract them and edit them accordingly. Here's a tutorial to help get you started.
A: Have you tried setting this in xml
android:rotationY="180"
A: This should fix a few issues with @mhenry answer
class ReverseSeekBar : SeekBar {
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
init()
}
var first = true
override fun onTouchEvent(event: MotionEvent): Boolean {
event.setLocation(this.width - event.x, event.y)
return super.onTouchEvent(event)
}
override fun getProgress(): Int {
return max - super.getProgress() + min
}
override fun setProgress(progress: Int) {
super.setProgress(max - progress + min)
}
override fun onDraw(canvas: Canvas?) {
if (first) {
first = false
val old = progress
progress = min + max - progress
super.onDraw(canvas)
progress = old
} else
super.onDraw(canvas)
}
private fun init() {
rotation = 180f
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Interface Builder Scaling? I've noticed in two different projects over the past few days that distances aren't lining up between IB and the actual app. For example, in one application I have a MKMapView. In IB, it is aligned with the bottom of a UIImageView, however when deployed on device it overlaps by about 20pts.
What's the issue? Elements are getting pushed up and down the screen. Using a tab bar interface. The tab bar is present on the bottom of the NIB, so I don't think it's a resizing issue. Help?
A: The tab bar should be a "simulated metric", not an actual tab bar on the screen. Select the main view itself (click the border), and open the attributes inspector (Command-Option-4). Under Simulated Metrics, select Tab Bar from the popup for Bottom bar.
The other possibility is when rotating—set your structs and springs correctly. You haven't mentioned rotation though, so I think it's the first answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: GDB break on object function call I'm debugging an issue, and I want to break on every method call that has a specific object as the 'this' parameter. Is this possible in GDB?
A: It's easy. You can use command like b A::a if (this==0x28ff1e).
A: The this parameter should only be the methods that are included in the class itself. So you should just need to set breakpoints for all Of the methods of the class you are looking at. I'm not sure there is a simple way to do that though.
A:
I want to break on every method call that has a specific object as the 'this' parameter
This means that you want to break on every member function of a particular class for which the object has been instantiated.
Let's say for convenience that all the member functions are defined in a particular cpp file such as myclass_implementation.cpp
You can use gdb to apply breakpoint on every function inside myclass_implementation.cpp this way:
rbreak myclass_implementation.cpp:.
Let's say you want to break on some specific functions such as getter functions which start with Get, then you can use gdb to apply breakpoints this way:
rbreak myclass_implementation.cpp:Get*
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to write a file of ASCII bytes to a binary file as actual bytes? Trying to do an MD5 collision homework problem and I'm not sure how to write raw bytes in Python. I gave it a shot but just ended up with a .bin file with ASCII in it. Here's my code:
fileWriteObject1 = open("md5One.bin", 'wb')
fileWriteObject2 = open("md5Two.bin", 'wb')
fileReadObject1 = open('bytes1.txt', 'r')
fileReadObject2 = open('bytes2.txt', 'r')
bytes1Contents = fileReadObject1.readlines()
bytes2Contents = fileReadObject2.readlines()
fileReadObject1.close()
fileReadObject2.close()
for bytes in bytes1Contents:
toWrite = r"\x" + bytes
fileWriteObject1.write(toWrite.strip())
for bytes in bytes2Contents:
toWrite = r"\x" + bytes
fileWriteObject2.write((toWrite.strip())
fileWriteObject1.close()
fileWriteObject2.close()
sample input:
d1
31
dd
02
c5
e6
ee
c4
69
3d
9a
06
98
af
f9
5c
2f
ca
b5
I had a link to my input file but it seems a mod removed it. It's a file with a hex byte written in ASCII on each line.
EDIT: SOLVED! Thanks to Circumflex.
I had two different text files each with 128 bytes of ASCII. I converted them to binary and wrote them using struck.pack and got a MD5 collision.
A: If you want to write them as raw bytes, you can use the pack() method of the struct type.
You could write the MD5 out as 2 long long ints, but you'd have to write it in 2 8 byte sections
http://docs.python.org/library/struct.html
Edit:
An example:
import struct
bytes = "6F"
byteAsInt = int(bytes, 16)
packedString = struct.pack('B', byteAsInt)
If I've got this right, you're trying to pull in some text with hex strings written, convert them to binary format and output them? If that is the case, that code should do what you want.
It basically converts the raw hex string to an int, then packs it in binary form (as a byte) into a string.
You could loop over something like this for each byte in the input string
A: >>> import binascii
>>> binary = binascii.unhexlify("d131dd02c5")
>>> binary
'\xd11\xdd\x02\xc5'
binascii.unhexlify() is defined in binascii.c. Here's a "close to C" implementation in Python:
def binascii_unhexlify(ascii_string_with_hex):
arglen = len(ascii_string_with_hex)
if arglen % 2 != 0:
raise TypeError("Odd-length string")
retval = bytearray(arglen//2)
for j, i in enumerate(xrange(0, arglen, 2)):
top = to_int(ascii_string_with_hex[i])
bot = to_int(ascii_string_with_hex[i+1])
if top == -1 or bot == -1:
raise TypeError("Non-hexadecimal digit found")
retval[j] = (top << 4) + bot
return bytes(retval)
def to_int(c):
assert len(c) == 1
return "0123456789abcdef".find(c.lower())
If there were no binascii.unhexlify() or bytearray.fromhex() or str.decode('hex') or similar you could write it as follows:
def unhexlify(s, table={"%02x" % i: chr(i) for i in range(0x100)}):
if len(s) % 2 != 0:
raise TypeError("Odd-length string")
try:
return ''.join(table[top+bot] for top, bot in zip(*[iter(s.lower())]*2))
except KeyError, e:
raise TypeError("Non-hexadecimal digit found: %s" % e)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: MFC: Dynamically change control font size? I have a CListCtrl class that I'd like to be able to easily change the font size of. I subclassed the CListCtrl as MyListControl. I can successfully set the font using this code in the PreSubclassWindow event handler:
void MyListControl::PreSubclassWindow()
{
CListCtrl::PreSubclassWindow();
// from http://support.microsoft.com/kb/85518
LOGFONT lf; // Used to create the CFont.
memset(&lf, 0, sizeof(LOGFONT)); // Clear out structure.
lf.lfHeight = 20; // Request a 20-pixel-high font
strcpy(lf.lfFaceName, "Arial"); // with face name "Arial".
font_.CreateFontIndirect(&lf); // Create the font.
// Use the font to paint a control.
SetFont(&font_);
}
This works. However, what I'd like to do is create a method called SetFontSize(int size) which will simply change the existing font size (leaving the face and other characteristics as is). So I believe this method would need to get the existing font and then change the font size but my attempts to do this have failed (this kills my program):
void MyListControl::SetFontSize(int pixelHeight)
{
LOGFONT lf; // Used to create the CFont.
CFont *currentFont = GetFont();
currentFont->GetLogFont(&lf);
LOGFONT lfNew = lf;
lfNew.lfHeight = pixelHeight; // Request a 20-pixel-high font
font_.CreateFontIndirect(&lf); // Create the font.
// Use the font to paint a control.
SetFont(&font_);
}
How can I create this method?
A: I found a working solution. I'm open to suggestions for improvement:
void MyListControl::SetFontSize(int pixelHeight)
{
// from http://support.microsoft.com/kb/85518
LOGFONT lf; // Used to create the CFont.
CFont *currentFont = GetFont();
currentFont->GetLogFont(&lf);
lf.lfHeight = pixelHeight;
font_.DeleteObject();
font_.CreateFontIndirect(&lf); // Create the font.
// Use the font to paint a control.
SetFont(&font_);
}
The two keys to getting this to work were:
*
*Removing the copy of the LOGFONT, lfNew.
*Calling font_.DeleteObject(); before creating a new font. Apparently there can't be an existing font object already. There is some ASSERT in the MFC code that checks for an existing pointer. That ASSERT is what was causing my code to fail.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Improving Linq-XML to Object query I want to use Linq to extract data from an XML document and place it into a list
<Data>
<FlightData DTS="20110216 17:17" flight="1234" origin="CYYZ" dest="CYUL" aircraft="945">
<TLDRequest>
<Airline>ABC</Airline>
<AcReg>C-FABC</AcReg>
<CalcType>T</CalcType>
<OAT>-05</OAT>
<Wind>060/10</Wind>
<Flaps>5</Flaps>
<Switches></Switches>
<Runways>
<Rwy>6L</Rwy>
<Rwy>6R</Rwy>
</Runways>
...
</TLDRequest>
...
</FlightData>
</Data>
My Linq code in C# works - I can get attributes from the FlightData tab, but I think it could be more efficient, especially in the area of getting data from the TLDRequest tag. Can I get some insight on using best practices to get to and grab child tags?
public static List<ACARS_Phase> createAcarsPhaseObject(XDocument xDoc)
{
return (from ao in xDoc.Descendants("FlightData")
select new ACARS_Phase
{
FlightDate = DateTime.ParseExact(ao.Attribute("DTS").Value, "yyyyMMdd HH:mm", new CultureInfo("en-CA")),
FlightNumber = ao.Attribute("flight").Value,
Origin = ao.Attribute("origin").Value,
Destination = ao.Attribute("dest").Value,
InternalFinNumber = ao.Attribute("aircraft").Value,
OperatorCode = ao.Element("TLDRequest").Element("Airline").Value,
RegistrationNumber = ao.Element("TLDRequest").Element("AcReg").Value,
Wind = ao.Element("TLDRequest").Element("Wind").Value,
Flaps = ao.Element("TLDRequest").Element("Flaps").Value,
OAT = ao.Element("TLDRequest").Element("OAT").Value,
}).ToList();
}
Best regards
A: Your query is fine, generally speaking. If you want to cut down on some of the redundancy, consider using let to get the TLDRequest element once, so you repeat yourself a bit less.
return (from ao in xDoc.Descendants("FlightData")
let request = ao.Element("TLDRequest")
select new AcARS_Phase
{
// stuff
OperatorCode = request.Element("Airline").Value,
RegistrationNumber = request.Element("AcReg").Value,
// etc.
}).ToList();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is it possible to use type traits to check whether a type is a container? Can I use C++ Type Traits to check if a type is an STL-like container? I already know of GCC's builtin __is_class but I would like to be a bit more specific if possible.
A: You could build your own traits classes to check a type for the Container interface. This would involve validating that certain associated types (such as container::iterator) exist and validating that certain expressions (such as container.empty()) are valid (i.e., they compile without error). Various SFINAE techniques can be used to build traits classes which check for nested types and validate expressions.
SGI's page specifies in detail the associated types and valid expressions that types which model the Container "concept" must provide. The most recent ISO C++ standard document would probably provide a more authoritative source since the SGI page is pretty old.
Of course, traits classes can't validate the semantics of expressions like container.empty(); they can only check that the expressions are legal. Some have proposed extending the language to allow the programmer to assert the semantic properties of expressions, which would address this limitation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Passing variables to config/environments/demo.rb from the Rails app I have been struggling with a problem for the past days in a Ruby on Rails App I'm currently working on. I have different countries and for each country we use different Amazon S3 buckets. Amazon S3 key credentials are stored as constants in config/environments/environment_name.rb(ex:demo.rb) There is no way for me to determine which country we are operating from the config file. I can determine which country we are operating from the controllers,models,views,etc but not from the config file. Is there a Ruby meta programming or some other kind of magic that I'm not aware of so that I want to say if we are working on UK as a country in the app, use UK's bucket credentials or Germany as a country, use Germany's bucket credentials? I can't think of a way to pass parameters to environment files from the app itself. Thank you very much in advance for all your helps.
A: Rather than actually pass the configuration details to whichever S3 client you're using at launch, you should probably select the relevant credentials for each request. Your config file can define them all in a hash like so:
# config/s3.rb
S3_BUCKETS => {
:us => 'our-files-us',
:gb => 'our-files-gb',
:tz => 'special-case'
}
Then you can select the credentials on request like so (in maybe your AppController):
bucket_name = S3_BUCKETS[I18n.locale]
# pass this info to your S3 client
Make sense?
A: Write a little middleware if you want to keep the knowledge of the per-country configuration out of the main application.
A middleware is extremely simple. A do-nothing middleware looks like this:
class DoesNothing
def initialize(app, *args)
@app = app
end
def call(env)
@app.call(env)
end
end
Rack powers applications through chaining a series of middlewares together... each one is given a reference to @app, which is the next link in the chain, and it must invoke #call on that application. The one at the end of the chain runs the app.
So in your case, you can do some additional configuration in here.
class PerCountryConfiguration
def initialize(app)
@app = app
end
def call(env)
case env["COUNTRY"]
when "AU"
Rails.application.config.s3_buckets = { ... }
when "US"
Rails.application.config.s3_buckets = { ... }
... etc
end
@app.call(env)
end
end
There are several ways to use the middleware, but since it depends on access to the Rails environment, you'll want to do it from inside Rails. Put it in your application.rb:
config.middleware.use PerCountryConfiguration
If you want to pass additional arguments to the constructor of your middleware, just list them after the class name:
config.middleware.use PerCountryConfiguration, :some_argument
You can also mount the middleware from inside of ApplicationController, which means all of the initializers and everything will have already been executed, so it may be too far along the chain.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Display Encrypted and decrypted Message on Client Console Window I have WCF hello service. I am able to encrypt and decrypt the messages. I want to display encrypyted and decrypted message on client console window
A: Console.Write and Console.WriteLine are your friends.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IOleObject in old style I have got a code snippet that uses IOleObjects and calls the method "SetClientSite".
pIOleObject.SetClientSite(this);
Now my problem is that the button is shown in an old Windows style, it is flat and there is no Aero effect. I guess I have to call "SetColorScheme", but I do not know how to use LOGPALETTE.
I just need these IOleObjects for a webbrowser control in a trusted Security Zone.
Maybe someone can help, thanks.
A: Your OLE control is getting its style choice from its host application. You need to use an ID2 Win32 Manifest to create an activation context, assert that activation context on entry to each of your OLE methods, and ensure your control is windowed rather than windowless so that it gets your theme.
Alternatively, if the host exe is also under your control, just use an ID1 Win32 manifest to make themed controls the default process-wide.
http://msdn.microsoft.com/en-us/library/bb773175.aspx
Martyn
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is better in terms of performance, Use XPath to parse a big HTML file or use preg_match? What is better in terms of performance, Use XPath to parse a big HTML file or use preg_match to fetch the attributes and text I want on it?
Because the website has way too many requests so I need a way to make it very fast to parse the HTML and consuming very low CPU Processing.
Right now I'm using preg_match because I really want performance, Does using Regular Expression make a very big difference in processing? or I should just move to XPath because it doesn't make any difference in terms of speed ?
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Image Convolution in Frequency Domain (MATLAB) I'm writing a c++ program for a class to do convolution in the frequency domain, and I noticed the final result had error along the corner. So I tried it out in MATLAB and got the exact same results. e.g.
Using cameraman from http://engronline.ee.memphis.edu/eece7214/images/Downlodable.htm
I did
a = imread('cameraman.pgm');
h = ones(25,25)/25/25;
a(512,512) = 0;
h(512,512) = 0;
c = ifft2(fft2(a).*fft2(h))/256;
c = c(1:256, 1:256);
c = real(c);
imwrite(c,'test2.png')
I took a peek at c before extracting the top-left corner, and I found it was the same answer as imfilter(a, h) except it was translated a tad from the corner. Digital Image Processing by Gonzalez says nothing about this, and Google has left my eyes bleeding from searching with no help at all (everyone repeats the same instructions Gonzalez gives to extract the top left corner).
Unrelated to the main question, I'd also like to know why I had to divide by 256 in this MATLAB code. In my C++ code, I didn't have to scale the result, and I got the same answer as this MATLAB code.
edit:
I did a little playing around with 1-dimensional vectors (doing conv and ifft(fft*fft)), and I think the 'error' is from the output showing the 'full' convolution in the top left corner instead of the 'same' convolution. But even if that were the case, I'm not sure how to deterministically code "extract this portion only to get the 'same' instead of the top left 256x256 portion of the 'full'"
edit:
More googling has resulted in a possible solution via http://jeremy.fix.free.fr/IMG/pdf/fftconvolution.pdf. It has a lot of math symbols I've never seen before, but from what I can gather, if you are convolving an nxn and a mxm, extract m:(m+n-1) to get the 'same' convolution from the fft approximation. I'd still like to hear from someone who is more expert than I am, so don't choose not to comment based on this update!
A: MATLAB indexes arrays from 1 to N.
Canonical C usage (and most C matrix math libraries) indexes array from 0 to N-1.
That may be the source of an off-by-one difference.
To be an identity, the bare ifft(fft(x)) algorithm requires a scale factor of 1/N somewhere.
Some C libraries put that 1/N inside the fft(). Many build that scale factor into the ifft(). Some put a 1/sqrt(N) in both. Some add no built-in scale factor, requiring the user to scale as needed to get an identity.
A: You need to shift it by half of the window size.
In this case you should do:
c = c(13:256+12,13:256+12);
instead of:
c = c(1:256, 1:256);
You are padding the signal with zeros but not getting any use of that since you take the signal from 1 to 256 - you still have the thrash on the edges and the valuable signal on the right corners which you lose.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to combine javascript Souncloud player and flash visualization I have set up a nice Flash audio visualization which can load an audio file and play it and display a spectrum of flashing coloured bars in time to the music. I don't want to have to list and control the playback of songs from with in the swf though. I wold prefer to have the songs listed in the HTML of the page, preferably in a non-flash format. I am hosting my audio on Soundcloud and have found their javascript player, which suits my purposes nicely. Now how could I integrate these two things?
It seems that either I would need a way to pipe the audio that is produced by the javascript player into the swf, if that is even possible, or else mute the sound in one of the two locations (preferably the js so that the vis is optimally in sync) and pass all play/stop/seek commands from the js player to the flash vis. Is this going to be too difficult to even bother with?
Update:
Let me be more specific. Assuming that the "piping audio into the swf" approach couldn't work, I will need to pass many different messages between swf and js. I understand how to start the swf audio from js I think. Would somebody be able to demonstrate how to do the following?
*
*signal from flash back to js that the audio has started
*signal from flash to js the current time of the audio
*pause or stop the flash audio from js
You can assume the following code is present:
var url:String = "mysong.mp3";
var song:SoundChannel;
var request:URLRequest = new URLRequest(url);
var s:Sound = new Sound();
s.addEventListener(Event.COMPLETE, onLoadComplete );
s.load(request);
function onLoadComplete(event:Event):void
{
song = s.play(33000);
song.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
s.removeEventListener( Event.COMPLETE, onLoadComplete );
}
function soundCompleteHandler(event:Event):void
{
song.removeEventListener( Event.SOUND_COMPLETE, soundCompleteHandler );
}
I don't understand the strange separation between the Sound class and the SoundChannel class and why different methods seem to be scattered between them.
A: Wow! Thanks to some awesome Adobe voodoo my flash audio visualizer is actually picking up audio that is played on the same webpage automatically! I assume it has to do with the fact that I am using SoundMixer.computeSpectrum(). I didn't even understand how that works but apparently it can see outside flash itself to whatever audio is playing in the browser window. So I don't have to worry about "piping audio into flash" or passing functions between the swf and javascript at all!
Usually programming endeavors require getting all sorts of variables to just right for anything to work at all. How awesome is it when everything works without even trying!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating a pid_file while using Proc::Daemon::Init I've been following the explanation in run a perl script as a daemon. I would like to create the pid_file within the perl script. After going through the documentation I was sure that the following piece of code would do it:
use Proc::Daemon;
Proc::Daemon::Init({ pid_file => "/var/run/theprocess.pid"} );
To make a long story short. Id didn't work. I've also tried with the Proc::Daemon->new() operator and it didn't work either. What could I be missing?
A: Without knowing any details it's hard to tell, but most likely it's one of 2 things:
*
*Either pid_file doesn't support a full path. This is unlikely but possible considering that POD example involves separate work_dir argument and path-less pid_file value:
my $daemon = Proc::Daemon->new(
work_dir => '/working/daemon/directory',
pid_file => 'pid.txt',
exec_command => 'perl /home/my_script.pl',
);
Based on the current code in the module that's not the case (e.g. the example merely doesn't show a valid usage with full path, but such usage is fine); but it could be a new functionality missing from your older module version. Again, unlikely.
*Or, the file you're writing to can't be created, either because the directory is missing or due to permissioning issue. If that's the case there should be something on STDERR looking like "*Can not open pid_file xxxx*" . Just as FYI, the file is opened for read-write mode (+>).
A: Actually the problem was that the debian package that installs Proc::Daemon::Init is for version 0.3 which doesn't have the functionality to create the pid files. I ended up doing something like:
use Proc::Daemon;
use Proc::PID::File;
Proc::Daemon::Init();
if (Proc::PID::File->running()) {
exit;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is there a way to obtain the link of files stored on cloud? I am developing a cloud application for my project. I want to provide the facility of storing files on the cloud and retrieving those files after a valid log in.
I want to store the links of the actual cloud based files in a database.
Is there any way of knowing the links of the files on the cloud if the cloud that I will be using is a Microsoft Cloud?
Thank you.
A: When you create your Azure Storage account you need to givet it a name. Let's say you name it foostorage. Then if you would upload a blob using the following code.
string path = "folder"
string fileName = "file.txt";
CloudBlobContainer container = blobClient.GetContainerReference(path);
var blobContainerPermissions = new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Container
};
container.CreateIfNotExist();
container.SetPermissions(blobContainerPermissions);
CloudBlob blob = container.GetBlobReference(fileName);
blob.UploadText("Text to be saved to blob storage");
string blobUri = blob.Uri.AbsoluteUri;
Then blobUri would get the value https://foostorage.blob.core.windows.net/folder/file.txt
Please note that the access rights is set to public.
A: Here's a sample which shows how to store files in Azure blob storage.
It also retrieves the uri of the files and then shows it on a web page. You could easily do the same and store in a DB.
http://soumya.wordpress.com/2010/05/19/azure-simplified-part3-using-azure-blob-storage/
BTW, that tutorial is using local development storage called devfabric which is why you see the local address 127.0.0.1 in the url. If you have a real azure cloud account, the code will be the same.
Hope that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Disabled lazy-loading and eager-loading entity references not working as expected I've been working with WCF RIA Services and Silverlight and have had some success in exposing a service that serves data taken from an ADO.NET Entity Data Model modeled from an existing SQL Server 2008 Express database. The database defines many relationships between tables that I'm hoping to be able to use client-side for databinding.
Everything was progressing smoothly until I tried executing the following service method:
public IQueryable<Timeline> GetHighlights() {
var self = from x in Database.Timelines
where User.Id == x.UserId || User.Id == x.SenderId
select x;
var friends = from x in Database.FriendItems
where User.Id == x.UserId
from y in Database.Timelines
where x.FriendId == y.UserId || x.FriendId == y.SenderId
select y;
return self.Concat(friends).OrderByDescending(s => s.Id);
}
Note: 'User' is an internal property of the class that selects the currently authenticated user and Database merely wraps the ObjectContext property (for ease).
The 'Timeline' entity contains 2 navigation properties 'User' and 'Sender' which are associated with the 'SilverfishUser' entity. When I iterate over the results from the 'self' query I see that the previously mentioned properties have been filled with the current user (which is correct). However when I iterate the results from the 'friends' query, both the properties are null (before being serialized to the client).
I have tried setting:
this.ContextOptions.LazyLoadingEnabled = false;
//and
this.ContextOptions.ProxyCreationEnabled = false;
And I have also tried eager-loading the references using the Include query method (with lazy-loading both enabled AND disabled) to no avail.
The only way I have successfully filled the User and Sender properties of the Timeline entity was using the following statement:
friends.ForEach(s => {
if (!s.UserReference.IsLoaded) s.UserReference.Load();
if (!s.SenderReference.IsLoaded) s.SenderReference.Load();
});
From what I understand, the 'Load' operation results in a seperate query being executed on the database. As you can see, this presents a potentially inefficient situation when a user has many friends with many timeline posts. The exact situation I'm trying to avoid by disabling lazy-loading. I want to return to the client a fully loaded entity that can be bound to in the minimum amount of queries as possible.
I have already overcome one problem where relative properties were not serialized to the client by applying the [Include] attribute on the metadata property definitions generated by the Domain Service Wizard. This issue seems to be a little more complicated, the solutions I have tried have been widely stated by others and should solve my problem in theory, but they do not. Again, the only way I have been able to successfully fill the entity is to explicitly load the references using the generated EntityReference<> property created for the associated property.
Any help, experience, or information on this issue would be greatly appreciated.
[EDIT] An update on some of my research, when I perform a query like this:
var friends = Database.FriendItems
.Include("Friend.Timeline")
.Where(s => User.Id == s.UserId);
And access the navigation properties ("friends.First().Friend.Timeline.First().User") the value is not null. It's only when I select the timelines into a new collection by adding something like:
.SelectMany(s => s.Friend.Timeline);
That the navigation properties no longer have any value. Now this is only a guess but I can only assume it projects the property values into a new object instance, so it doesn't re-fill these properties in an attempt avoid cyclic references? Anyway, this is one heck of a pickle to solve. Hopefully there's somebody out there who knows more about this than I do.
A: Well I have managed to find a bit of a workaround, albeit not a very elegant one. I'll post it as an answer so people can have a look at it, but I'm going to leave the question open and credit a more appropriate solution, if possible.
Here's my fix:
public IQueryable<Timeline> GetHighlights() {
var self = from x in Database.Timelines
where User.Id == x.UserId || User.Id == x.SenderId
select x;
var friends = from x in Database.FriendItems.Include("Friend.Timeline")
where (User.Id == x.UserId)
select x.Friend.Timeline;
List<Timeline> highlights = new List<Timeline>();
highlights.AddRange(self);
friends.ForEach(x => x.ForEach(y => highlights.Add(y)));
return highlights.AsQueryable().OrderByDescending(s => s.Id);
}
I think the reason this works is by creating the new collection manually, I prevent the entities from being projected into new objects, thus preserving the loaded relational properties. Again, this is merely speculation but the assumption follows a pretty good pattern lol.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: php subtract associative arrays I have two associative arrays. I need to subtract ($price - $tax) to get $total price:
$price['lunch'] = array("food" => 10, "beer"=> 6, "wine" => 9);
$price['dinner'] = array("food" => 15, "beer"=> 10, "wine" => 10);
$tax['lunch'] = array("food" => 2, "beer"=> 3, "wine" => 2);
$tax['dinner'] = array("food" => 4, "beer"=> 6, "wine" => 4);
Desired result array:
$result['lunch'] = (['food'] => 8, ['beer'] =>3, ['wine'] => 7 )
$result['dinner'] = (['food'] => 11, ['beer'] =>4, ['wine'] => 6 )
I'm trying following function and array_map to no avail:
function minus($a, $b) {
return $a - $b;
}
foreach ($price as $value)
{
$big = $value;
foreach($tax as $v) {
$small = $v;
$e[] = array_map("minus",$big, $small);
}
}
With above i get four arrays (first and last one is correct though) so it's not correct. Thanks for any info!
A: You could compare using keys instead of array mapping. With a double foreach, you can do any number of meals and food types:
foreach(array_keys($price) as $meal)
{
foreach(array_keys($price[$meal]) as $type)
{
$e[$meal][$type] = $price[$meal][$type] - $tax[$meal][$type];
}
}
Note, this code doesn't look out for missing items in either the meals or the food types...
A: if the structure of $price and $tax are always equals, you can use the following code:
<?php
$price['lunch'] = array("food" => 10, "beer"=> 6, "wine" => 9);
$price['dinner'] = array("food" => 15, "beer"=> 10, "wine" => 10);
$tax['lunch'] = array("food" => 2, "beer"=> 3, "wine" => 2);
$tax['dinner'] = array("food" => 4, "beer"=> 6, "wine" => 4);
$result = array();
foreach( $price as $what => $value)
{
foreach( $value as $food => $foodPrice )
{
$result[$what][$food] = $foodPrice - $tax[$what][$food];
}
}
Result:
print_r($result);
Array
(
[lunch] => Array
(
[food] => 8
[beer] => 3
[wine] => 7
)
[dinner] => Array
(
[food] => 11
[beer] => 4
[wine] => 6
)
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I diagnose a Handle leak? I've got a process that is hosting a WCF ServiceHost. It leaks handles like crazy according to ProcessExplorer. I've gone over the code and can't find anything obvious that's causing leaked handles.
The closest I can come to is the listing of handles provided by ProcessExplorer, but the usefulness of that seems limited. Are there any other tools out there to help diagnose where a handle came from, like via a stack trace or something?
EDIT
I've got the Windbg installed. When I use it to list handles, it's showing me that 914 handles are of type "Event" -
If I pick a few of these, and output using !handle x f I get output similar to this on most:
Type Event
Attributes 0
GrantedAccess 0x1f0003
HandleCount 2
PointerCount 3
Object Specific Information
Event Type Manual Reset
Event is Set
Is there a way to dig in further to determine more about the event?
A: Sorry for the earlier bad answer (now deleted, it appears).
The Debugging Tools for Windows package includes WinDbg and friends. WindDbg is a full debugger like Visual Studio, but leaner and meaner, and more capable in many ways. Run WinDbg, attach to your process (F6), and type !handle in the command window. You'll get a list of all the handles and some statistics. If you scroll up and see a handle that looks like it might be one of the leaky ones, you can do !handle <handlenum> f to show more information about it. For example, attaching to iexplore.exe on my system:
0:019> !handle 1bc f
Handle 1bc
Type Key
Attributes 0
GrantedAccess 0x2001f:
ReadControl
QueryValue,SetValue,CreateSubKey,EnumSubKey,Notify
HandleCount 2
PointerCount 3
Name \REGISTRY\USER\S-1-5-21-498032705-2416727736-2837886327-1001\Software\Microsoft\Windows\CurrentVersion\Internet Settings
Object Specific Information
Key last write time: 11:04:51. 9/4/2011
Key name Internet Settings
EDIT
To find out more information, you can use the !htrace windbg command. To use it, attach to your process using windbg, and type !htrace -enable, then type g to resume the process. Exercise the process for a bit, and then break in using CTRL-Break (i.e. CTRL-Pause). Type !htrace -diff. You should see a list of stack traces showing open handles and the call stack at the time they were opened. If you don't have Windows symbols set up, the only addresses that will make sense will be your own code -- but that should be plenty to get you the clues you need.
<snip>
ModLoad: 00000000`75020000 00000000`7504d000 WINTRUST.dll
ModLoad: 00000000`75160000 00000000`7527d000 CRYPT32.dll
ModLoad: 00000000`757d0000 00000000`757dc000 MSASN1.dll
(2fd0.1ce4): Break instruction exception - code 80000003 (first chance)
ntdll!DbgBreakPoint:
00000000`77440530 cc int 3
0:019> !htrace -enable
Handle tracing enabled.
Handle tracing information snapshot successfully taken.
0:019> g
(2fd0.2c88): Break instruction exception - code 80000003 (first chance)
ntdll!DbgBreakPoint:
00000000`77440530 cc int 3
0:019> !htrace -diff
Handle tracing information snapshot successfully taken.
0x360 new stack traces since the previous snapshot.
Ignoring handles that were already closed...
Outstanding handles opened since the previous snapshot:
--------------------------------------
Handle = 0x000000000000070c - OPEN
Thread ID = 0x0000000000000c44, Process ID = 0x0000000000002fd0
0x000000007744232a: ntdll!NtOpenThread+0x000000000000000a
0x0000000074c83910: wow64!whNtOpenThread+0x00000000000000a0
0x0000000074c6cf87: wow64!Wow64SystemServiceEx+0x00000000000000d7
0x0000000074bf2776: wow64cpu!TurboDispatchJumpAddressEnd+0x000000000000002d
0x0000000074c6d07e: wow64!RunCpuSimulation+0x000000000000000a
0x0000000074c6c549: wow64!Wow64LdrpInitialize+0x0000000000000429
0x000000007746e707: ntdll! ?? ::FNODOBFM::`string'+0x0000000000029364
0x000000007741c32e: ntdll!LdrInitializeThunk+0x000000000000000e
0x00000000775f113a: ntdll_775d0000!ZwOpenThread+0x0000000000000012
0x0000000075ea2e32: KERNELBASE!OpenThread+0x0000000000000049
0x00000000755578df: iertutil!CIsoMalloc::AllocArtifact+0x0000000000000050
0x00000000755578b4: iertutil!CIntraprocessMessageQueueSite::_QueryMessageThreadAffinityHelper_UntrustedSerializedIsoMessage+0x0000000000000055
0x0000000075557754: iertutil!CIntraprocessMessageQueueSite::QueryMessageThreadAffinity+0x000000000000004b
--------------------------------------
Handle = 0x0000000000000790 - OPEN
Thread ID = 0x00000000000019d4, Process ID = 0x0000000000002fd0
0x000000007744226a: ntdll!NtOpenKeyEx+0x000000000000000a
0x0000000074c8d205: wow64!Wow64NtOpenKey+0x0000000000000091
0x0000000074c8314f: wow64!whNtOpenKeyEx+0x0000000000000073
0x0000000074c6cf87: wow64!Wow64SystemServiceEx+0x00000000000000d7
0x0000000074bf2776: wow64cpu!TurboDispatchJumpAddressEnd+0x000000000000002d
0x0000000074c6d07e: wow64!RunCpuSimulation+0x000000000000000a
0x0000000074c6c549: wow64!Wow64LdrpInitialize+0x0000000000000429
0x000000007746e707: ntdll! ?? ::FNODOBFM::`string'+0x0000000000029364
0x000000007741c32e: ntdll!LdrInitializeThunk+0x000000000000000e
0x00000000775f101a: ntdll_775d0000!ZwOpenKeyEx+0x0000000000000012
0x0000000075ad2271: KERNEL32!LocalBaseRegOpenKey+0x000000000000010c
0x0000000075ad2416: KERNEL32!RegOpenKeyExInternalW+0x0000000000000130
0x0000000075ad2302: KERNEL32!RegOpenKeyExW+0x0000000000000021
--------------------------------------
Handle = 0x0000000000000788 - OPEN
Thread ID = 0x00000000000019d4, Process ID = 0x0000000000002fd0
0x000000007744226a: ntdll!NtOpenKeyEx+0x000000000000000a
0x0000000074c8d205: wow64!Wow64NtOpenKey+0x0000000000000091
0x0000000074c8314f: wow64!whNtOpenKeyEx+0x0000000000000073
0x0000000074c6cf87: wow64!Wow64SystemServiceEx+0x00000000000000d7
0x0000000074bf2776: wow64cpu!TurboDispatchJumpAddressEnd+0x000000000000002d
0x0000000074c6d07e: wow64!RunCpuSimulation+0x000000000000000a
0x0000000074c6c549: wow64!Wow64LdrpInitialize+0x0000000000000429
0x000000007746e707: ntdll! ?? ::FNODOBFM::`string'+0x0000000000029364
0x000000007741c32e: ntdll!LdrInitializeThunk+0x000000000000000e
0x00000000775f101a: ntdll_775d0000!ZwOpenKeyEx+0x0000000000000012
0x0000000075ad2271: KERNEL32!LocalBaseRegOpenKey+0x000000000000010c
0x0000000075ad2416: KERNEL32!RegOpenKeyExInternalW+0x0000000000000130
0x0000000075ad2302: KERNEL32!RegOpenKeyExW+0x0000000000000021
<snip>
A: Use a memory profiler - they can help to find such leaks, for example:
*
*http://www.red-gate.com/products/dotnet-development/ants-memory-profiler/ (commercial)
*CLR Profiler from MS (free)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: How do I access the nth element in an ruby array? Specifically, a will_paginate collection I am using ruby on rails and will_paginate to output posts to a page like this:
<div class="posts">
<% render @posts %>
</div>
Let's say I want to change this page so that I render some posts in different divs:
<% render 'posts/post', :post => #the first element in the collection %>
<div class="second_post">
<% render 'posts/post', :post => #the second element in the collection %>
</div>
</div>
<div class ="lower_container">
<div class="posts">
#may have to run a loop for this last one, to render all the rest of posts. How?
<% render 'posts/post', :post => #all other posts %>
</div>
</div>
Specifically, I know I could use @post.first for the first element, but don't know about the second (or third, or fourth elements). Naturally, my programming background makes me want to do @post(n) where n is the index of the element I want to access. This doesn't work in ruby.
FYI: The post collection is created in the controller by:
@posts = Post.paginate(:page => params[:page])
Does anyone know how I would best accomplish this goal? I know it may seem unconventional, but for the html/UI aspects I really want to do have the divs like this..
A: Inside your partial you can call:
<%= posts_counter %>
Or <partial_name>_counter
A: You could use CSS3's nth-child selectors to target specific div's. For example, if your code looked like:
<div id="posts">
<% @posts.each do |post| %>
<div>
<%= post.content %>
</div>
<% end %>
</div>
Then you can target the first and second <div> like this:
div#posts div:nth-child(1) { }
div#posts div:nth-child(2) { }
jQuery also can select them the same way, and add the classes to them if you require it:
$('div#posts div:nth-child(1)').addClass('firstPost');
Update:
Okay, after your response I'd suggest using the each_with_index helper method when iterating through your collection, like so:
<% @posts.each_with_index do |post, index| %>
<% if index == 0 %>
<div class="specialFirstIndexClass">
<%= post.content %>
</div>
<% end %>
<% if index == 1 %>
<div class="specialSecondIndexClass">
<%= post.content %>
</div>
<% end %>
<% end %>
Or you could use a Ruby switch like so, as they're pretty:
<% @posts.each_with_index do |post, index| %>
<% case index %>
<% when 0 %>
<div class="specialFirstIndexClass">
<%= post.content %>
</div>
<% when 1 %>
#etc..
<% else %>
<div class="notSoSpecial"><%= post.content %></div>
<% end %>
<% end %>
Hope this helps :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: embedding html in php error I think I have a syntax error but I can't spot it, any ideas?
if($infozz['count'] <= $infozz['limit'])
{
mail($infozz['email'], "Your incident report copy!", $bodyz);
echo <<<EOT
<html>
<head>
<title> Summary Report </title>
<link rel="stylesheet" href="http://web.njit.edu/~swp5/assignment/style/style3.css">
</head>
<body>
<div class="header">
Summary Report
</div>
<div class="mess">
Type of incident: {$infoz['type']}<br><br>
Date upon entry: {$infoz['date']}<br><br>
Time upon entry: {$infoz['time']}<br><br>
Your account name: {$infoz['reporter']}<br><br>
Your incident ID number: {$infoz['ID']}<br><br>
Your description of the incident: {$infoz['desc']}<br><br>
An email has been sent to your account<br>
</div>
</body>
</html>
EOT;
}
A: You cannot have any whitespace before or after the close of a HEREDOC statement. Be sure there is no space before or after your EOT; on this line:
EOT;
A: Don't echo out html.
PHP and HTML should look like this.
<?
if ($something == true) {
?>
<p>HTML Goes here</p>
<?
}
?>
A: You didn't close your {}'s for your If statement. Also supply an alternate else of else if statement with your HTML in between the statements
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using DirectX Dinput8.dll directly in C# I'm coding and app that requires access to DirectX in C#. Specifically it needs access to Dinput8.dll 's DirectInput8Create function.
I'm actually doing some hooking.. and am currenty just trying to hook the call and pass it through. I am only having issues with finding the correct variable types for the DLL call.
I just had a brainwave and think I will need to use Unsafe to make it work.. but I'm not 100% sure.
A: Sorry to bump an old post, but for people who are looking for why this hook crashes, it appears as though the hooked function is being called from within the hook. This creates an overflow.
A: I'm not sure why you went straight into hooking... So I might be missing something due the vagueness of the question.
If you want to hook DirectX from c# that's one thing...
But if you just want real access to the DX,Direct Input then I'd just use SharpDX...
I've used it before, specifically with Direct Input to get direct access to an Xbox controller connected to a windows PC and the experience was perfectly friction-less.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In PHP, How do I set default PDO Fetch Class? Using PDO::setAttribute, how do I provide the class name when setting PDO::ATTR_DEFAULT_FETCH_MODE to PDO::FETCH_CLASS.
This is the code I am using.. I would like to set it so all of my rows are returned as an instance of DB_Row:
class DB_Row extends ArrayObject {}
$db = new PDO('mysql:dbname=example;host=localhost', 'user', 'pass');
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_CLASS);
$stmt = $db->query("SELECT * FROM `table` WHERE `id` = 1;");
$row = $stmt->fetch(); // I want a DB_Row by default!
The code above results in a PDOException since the DB_Row class name was not assigned.
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: No fetch class specified
How would I go about this?
Thanks in advance..
SOLUTION: I used fireeyedboy's answer. It worked the best for my situation as I was already extending PDOStatement for logging purposes...
class DB extends PDO {
public function __construct($host = null, $user = null, $pass = null, $db = null) {
try {
parent::__construct('mysql:dbname=' . $name .';host=' . $host, $user, $pass);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_CLASS);
$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DB_Query', array('DB_Row')));
} catch (PDOException $e) {
die('Database Error');
}
}
}
class DB_Query extends PDOStatement {
private $class;
protected function __construct ($class = 'DB_Row') {
$this->class = $class;
$this->setFetchMode(PDO::FETCH_CLASS, $this->class);
}
}
class DB_Row extends ArrayObject {
public function __set($name, $val) {
$this[$name] = $val;
}
public function __get($name) {
return $this[$name];
}
}
A: I think it should return a stdclass instance so this would be a bug - but would have to look it up in the code to verify. will do if there is no accepted answer till then.
What will work is to use PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE and then provide a class name as first column. While this is a hack:
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE);
$stmt = $db->query("SELECT 'classname', * FROM `table` WHERE `id` = 1;");
EDIT: As promised here the code. The relevant code is here http://lxr.php.net/xref/PHP_5_4/ext/pdo/pdo_stmt.c#940 So setting the for using fetch() is only possible with FETCH_CLASSTYPE. The alternative is using PDOStatement::fetchObject()
A: Another kind of hack would be to extend PDOStatement, override its fetch methods and let your PDO instance use that as the default statement class.
As an example I'll just demonstrate overriding fetch()1 and leave fetchAll() and what have you up to you, if you wanna go this route:
class Db_Row
{
}
class PDOStatementWithClass
extends PDOStatement
{
private $fetch_class;
// PHP complained when I tried to make this public
protected function __construct( $fetch_class = 'StdClass' )
{
// internally set the fetch class for later use
$this->fetch_class = $fetch_class;
}
// let $fetch_style default to PDO::FETCH_CLASS in stead of PDO::FETCH_BOTH
public function fetch( $fetch_style = PDO::FETCH_CLASS, $cursor_orientation = PDO::FETCH_ORI_NEXT, $cursor_offset = 0 )
{
// make sure we're really dealing with the correct fetch style
if( $fetch_style == PDO::FETCH_CLASS )
{
// then automatically set the fetch mode of this statement
parent::setFetchMode( $fetch_style, $this->fetch_class );
}
// go ahead and fetch, we should be good now
return parent::fetch( $fetch_style, $cursor_orientation, $cursor_offset );
}
}
$db = new PDO( /* etc... */ );
// set default fetch mode to FETCH_CLASS
$db->setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_CLASS );
// override what statement class to use, and provide constructor arguments (found out by trial and error)
$db->setAttribute( PDO::ATTR_STATEMENT_CLASS, array( 'PDOStatementWithClass', array( 'Db_Row' ) ) );
This has the added benefit that you'll only have to define your PDO::FETCH_CLASS once in your application, and not in every query.
1) I'm surprised PHP didn't complain about overriding the signature of the method by the way.
A: public function fetchAll($fetch_style = \PDO::FETCH_CLASS, $fetch_argument = null, $ctor_args = null) {
if ($fetch_style == \PDO::FETCH_CLASS){
parent::setFetchMode( $fetch_style, 'App\Core\DBFetch' );
}
$fetchedData = call_user_func_array(array('parent', __FUNCTION__), func_get_args());
return $fetchedData;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Print HTML on 8.5x11 paper? I would like to print sets of data on 8.5x11 sheets of paper (one set per sheet). These sets are rendered on a web page vertically one after another (in divs of size 8.5x11).
How can I print each of these divs with identical formatting on individual pieces of 8.5x11 sheets of paper?
A: You can do the following:
*
*Try to work approximately how tall a <div> you can print on one page. This is determined by the contents of the <div> and is not entirely in your control (i.e. if the data is mainly text, a user may choose to override your font size or scale the page for print). However you should be able to come up with an approximate height that fits. For 12pt font, I've found it to be around 900px in height.
*Create a .page class that uses the CSS printing page break rules in a print stylesheet. These let you suggest to the browser if a page break should occur before or after your element.
You'll end up with something like the following:
HTML
<div class="page">
/* data */
</div>
<div class="page">
/* more exciting data */
</div>
CSS
.page {
font-size: 12pt;
height: 900px; /* You'll need to play with this value */
page-break-after: always; /* Always insert page break after this element */
page-break-inside: avoid; /* Please don't break my page content up browser */
}
For more reading, this ALA article gives some excellent tips on printing your web pages.
However if you're looking for precise control over how the reports print, I would recommend generating a PDF and serving it to the user.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I write an application which utilizes Intel IPT hardware? What is involved in writing some kind of abstraction layer for Intel IPT hardware?
For those unfamiliar with Intel IPT, it is an embedded co-processor used to generate unique 6 character one-time passwords every 30 seconds starting from a secret seed.
For an example of real-world usage, check out Valve's SteamGuard which allows the user to register a PC with their steam account such that their PC now acts as a second factor of authentication, much like the RSA securid tokens, but built into your computer. Another client would be Symantec's VIP which, as far as I can tell, acts as a middle-man between your IPT hardware and websites that seek extra authentication (you can use this with ebay as of now - probably other examples out there as well).
My search for technical documentation has turned up nothing useful so far and what I've found is more marketing directed and not useful for an implementer. Do you have to become one of Intel's "Trusted partners" (Symantec is listed as one) in order to obtain the necessary resources? Is there an audit process involved?
A: I looked into this myself, and discovered that you have to partner with Intel. It's a closed project at the moment and there's no public documentation or SDK. In order to become a partner there's an auditing process that involves looking at your hardware and software scenarios, plus the training of your staff. They also told me there's fees involved.
Sorry I can't be of much help on the technological aspects of it, as I didn't pursue that avenue further.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Metadata information for the relationship could not be retrieved I am using entity framework 4.0. I also have Worker entity. Each time I am trying to insert a worker - I get an exception in the Context.SaveChanges(); command:
The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: Metadata information for the relationship 'MyModel.FK_T_TRN_WORKER_VEHICLE_T_DRIVER' could not be retrieved. If mapping attributes are used, make sure that the EdmRelationshipAttribute for the relationship has been defined in the assembly. When using convention-based mapping, metadata information for relationships between detached entities cannot be determined.
Parameter name: relationshipName
In order to solve this I delete the FK_T_TRN_WORKER_VEHICLE_T_DRIVER relationship and then update the model in order to load this relationship again.
Later when running - I get the same exception but with other FK relation..
I have to delete the relation and then load it (update the model) again in order to fix the exception, but when running again I get the same exception but with other FK relation and so on..
If I wasn't clear, this is what happens to me:
1. I get an exception.
2. I delete the foreign key.
3. I update the model to load the foreign key.
4. I run the system.
5. I get step 1 but with other exception.
What is the reason to this issue? how can I sole it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need to optimize network utilization on IOS platform. Is there any reference? Is there any Apple reference or guidelines to understand when to transmit data from application? Scenarios include : Just trigger the HTTP connection when the radio has just been active.
Also the optimal data size for a single burst would be helpful to optimize my app. I'd appreciate any references on this end.
A: Apple provides a class called "Reachability" which would probably help you. It can trigger callbacks when the network status changes, i.e. connection becomes available.
http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: display item counts per month using JSON jquery each() IF statement (for loop?) I have a JSON object of data containing items and their sales listed by month. I'd like to list the item sales/month inside a DIV alongside other info about each item.
Here's my JSON object:
var my_object= [{"item_id":"11","month":"February","sales":"7"}, {"item_id":"4","month":"February","sales":"2"},{"item_id":"11","month":"March","sales":"1"},{"item_id":"4","month":"March","sales":"2"}]
here's how i'd like the final HTML to look:
<ul><li><button value="4">item_id_4</button><div>where the item_4 sales/month (i.e., 2,2) should go</div></li>
<li><button value="11">item_id_11</button><div>where the item_11 sales/month (i.e, 7,1) should go</div></li></ul>
lastly, here's my not yet correct jquery/javascript attempt to display the item counts/month.
$(function(){
$('button').each(function(){
var my_object = [{"item_id":"11","month":"February","sales":"7"}, {"item_id":"4","month":"February","sales":"2"},{"item_id":"11","month":"March","sales":"1"},{"item_id":"4","month":"March","sales":"2"}];
var button_value=$(this).val();
$.each(my_object, function(i,item){
if(item.item_id==button_value){
$('div').append(item.sales);
}
});
});
});
As it stands, this script displays the sales for both items in EACH div, i.e., 2,2,7,1 instead of just displaying 2,2 and 7,1 in their respective item_id_4 and item_id_11 divs separately. This makes it seem like the if statement is doing at least something right in that the "my_object" item sales are listed in the order of the button value and not as they are ordered in the "my_object".
I'm not sure whether the issue is with the each() functions, the IF statement, or maybe something else not mentioned here. Any help fixing this script would be greatly appreciated!
A: Your script seems to work fine except for the append line, where you tell jQuery to select all divs on the page and append your sales figures to them. Obviously that's not quite what you wanted. :)
Using your current HTML structure, changing that line to select the next div seems to work. (I've also saved the current button in $this.)
$this.next("div").append(item.sales);
Code here http://jsfiddle.net/meloncholy/ZhrZU/
A: Try the following
$(function(){
var my_object = [{"item_id":"11","month":"February","sales":"7"}, {"item_id":"4","month":"February","sales":"2"},{"item_id":"11","month":"March","sales":"1"},{"item_id":"4","month":"March","sales":"2"}];
for (var i in my_object) {
var cur = my_object[i];
$('button[value=' + cur.item_id + ']').each(function() {
var msg = 'Sales Month: ' + cur.month + ' Number: ' + cur.sales;
$(this).parent().append('<div>' + msg + '</div>');
});
}
});
I wasn't quite sure what you wanted the staring HTML to be but I assumed the following
<ul><li><button value="4"></button></li>
<li><button value="11"></button></li></ul>
Fiddle: http://jsfiddle.net/HdgmN/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to substitute a JScrollPane child component I have a JPanel that contains a JScrollPane that contains a JTable. Inside my panel constructor it's created this way:
//inside MyPanel extends JPanel class constructor
public void MyPanel(){
TitledBorder border = BorderFactory.createTitledBorder("title");
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.scrollTable = new JScrollPane(table);
this.scrollTable.setBorder(border);
}
Now, the user should be able to load another table into application so I need to remove the previous one from the scrollpane and add a new one.
I've tried the following :
public void setNewTable(JTable t ) {
this.scrollTable.removeAll();
this.scrollTable.add(t);
this.scrollTable.validate();
}
The previous table is removed, but nothing happear inside the JScrollPane now.
What am I doing wrong?
public void
A: You can't just add to JScrollPane, since it consists of other internal components.
From the JavaDocs:
By calling scrollPane.removeAll() you essentially, remove the header, view, and scrollbars, and add a component that the scrollpane doesn't understand.
First of all, you generally shouldn't pass around tables in that manner. It would be much better to instead pass in a TableModel, and change the model on the table via JTable.setModel().
That said, if you absolutely want to pass in a table, you need to set the view on the viewport in the scrollpane:
scrollPane.getViewport().setView(table)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Submit type with image I am wanting to use input type submit rather than input type image but I want the submit type to use an image. Can this be done?
A: You can attempt to style the <input type='submit'> with a CSS background statement:
input[type="submit"] {
background-image: url("submit-img.jpg");
background-repeat: no-repeat;
border: 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SurfaceView or GLSurfaceview? Hello there please help me to decide whether to use SurfaceView or GLSurfaceView.
I will be developing a game for my thesis and I already know how play with Canvas but I'm not sure if this can handle at least 70 sprites without lag or whatsoever problem. and BTW i will only developing 2d game so please help mo to decide !! Should i study the OpenGL and use GLSurfaceView or it's okay to use Canvas for my simple 2d game thanks.
A: In android canvas can be actually hardware-accelerated trough OpenGL (because of skia).
With 70 sprites there's no big difference between Canvas and GL. OpenGL requires more configuration, but gives you more ways to optimize drawing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: If statement using templatetag How would I do the following in django:
{% if value|truncatewords > 10 %} print this {% endif %}
Thank you.
A: I'm betting you want to count the words in a string. Try this one:
{% if value|wordcount > 10 %} print this {% endif %}
A: That's an incorrect use of the truncatewords filter. You must specify the number of words you wish to truncate after:
{{ value|truncatewords:10 }}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Vertical Centering a block in IE7 I'm trying to get vertical centering a block in IE7 (IE6 if possible too), let me get one thing clear - I'm not vertically centering the actual element, but the text within the element. This is my CSS and HTML which works on IE8 and above, but not below.
a {
display: table-cell;
width: 100px;
height: 54px;
background: black;
color: white;
text-align: center;
text-decoration: none;
vertical-align: middle;
}
<a href="#">Hello superlongword</a>
Now I know IE6 is virtually dead, I'd still like to support it if possible but if not then IE7 is fine. I want to try keep it with a single element as much as possible - it's for a navigator, so I don't want elements upon elements just for one link.
EDIT
I've decided to go with sprites, it'll be much easier for a navigator - not the best solution, but I'll be happy with the outcome. If any posted solutions do work, I'll swap over to them. :)
A: Use display:inline-block with a placeholder element to vertically center the block hyperlink:
<style type="text/css">
#blockbox { width: 500px; height: 500px; border: 1px solid black;}
#container, #placeholder { height: 100%; }
#content, #placeholder { display:inline-block; vertical-align: middle; }
</style>
<div id="blockbox">
<div id="container">
<a id="content">
Vertically centered content in a block box of fixed dimensions
</a>
<span id="placeholder"></span>
</div>
</div>
References
*
*CSS Vertical Centering
*IE7-/Win img, vertical-align middle
A: If you know it will be just one line of text, use line-height.
It is far from a single element, but you could just use an actual table cell. It's ugly, but supporting IE6 is an ugly affair.
table {
border: 0;
border-collapse: collapse;
height: 54px;
width: 100px;
}
td {
vertical-align: middle;
}
a {
background: black;
color: white;
display: block;
height: 100%;
text-align: center;
text-decoration: none;
}
<table><tr><td><a href="#">Hello superlongword</a></td></td></table>
If you know the link will be a certain number of lines, you can center using one extra element and a margin. (e.g. <a><em>anchor text</em></a>, em { margin-top:12px })
If you don't know the height of the element to be centered, you need table-cell layout behavior. The only way to get this in IE6 is with an actual table cell or JavaScript. Sorry.
A: This is a known bug. The way to fix this, which may not be applicable in your situation, is to add a Float to the element and have it display as inline-block to make hasLayout work in IE. I will also supply FF2 hacks to get around issues there too.
Fixed code:
a {
display: inline-block;
display: -moz-inline-stack; /*FF2 Hack*/
zoom: 1; /*IE inline-block star hack*/
*display: inline; /*IE inline-block star hack*/
float: left;
width: 100px;
_height: 54px; /*FF2 Hack*/
background: black;
color: white;
text-align: center;
text-decoration: none;
margin: 0px auto;
}
<a href="#">Hello superlongword</a>
EDIT
I didn't add a float, because I figured with the other hacks being used, it wouldn't matter.
A: Why don't you try a padding?
a {
display: inline-block;
overflow: hidden;
padding: 20px;
background: black;
color: white;
text-align: center;
text-decoration: none;
}
<a>Hello superlongword</a>
That sure works crossbrowser atleast for IE7 (couldn't test on IE6), example
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Changing values of an array containing a struct printing I would like to access the name field from the array items and print the name but I am having trouble.
I created a pointer 'L' in callInitialize and set it to the upper struct type List which I named 'studentList'.
int callInitialize () {
/*Initialize a List*/
List studentList;
List *L;
L = &studentList;
Initialize(L);
#ifdef DEBUG
printf("L->count after function call Initialize = %d\n", L->count);
printf("L->items[0].name after function call Initialize = %s\n", studentList.items[0].name);
#endif
return 0;
}
I then called Initialize and tried to set the value to test but this is incorrect.
void Initialize (List *L) {
char test = "I like you";
L->count = 0;
L->items[0].name = test;
}
I am unsure of why L->items[0].name = test; is not appropriate. I am getting an incompatible types error but name is char and test is char?
Also, once I do change that value how would I print that? My thinking was that %s would be correct since the type of the field name is char. Print is above in callIntialize as a debug statement.
My struct declarations:
#define MAXNAMESIZE 20
typedef struct {
char name[MAXNAMESIZE];
int grade;
} Student;
typedef Student Item;
#define MAXLISTSIZE 4
typedef struct {
Item items[MAXLISTSIZE];
int count;
} List;
Thank you for any help.
A: String copying in C doesn't work like that. Strings are simply arrays of characters, with a null character as the last element used; so to copy a string you need to copy the individual characters from the source array to the corresponding elements in the destination array. There are library functions for doing this, such as strncpy().
So you would need to change:
L->items[0].name = test;
..to something like:
strncpy(L->items[0].name,test,MAXNAMESIZE);
L->items[0].name[MAXNAMESIZE - 1] = '\0';
..where the second line just makes sure there's a null character at the end, in case test was longer than MAXNAMESIZE.
If the name member of Student had been declared as a char * and allocated with malloc(), rather than declared as an array of char, the assignment would have worked, but probably not done what you wanted -- it would have changed name to point to the same string as test (not a copy of it) and just discarded the original value, leaking the malloc()ed memory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Common practices for Javascript/jQuery ajax call synchronization I am curious if this is considered good practice or what may be better. Say for instance I have to make two or more ajax calls in a row and wait for all to complete before proceeding. Also in this case I am using JSONP in order to call a service on a seperate port (same origin policy).
$(document).ready(function() {
var semaphore = 0;
var proceed = function() { ... };
goAjax('arg0', function(data) {
semaphore++;
checkStatus(semaphore, proceed);
});
goAjax('arg1', function(data) {
semaphore++;
checkStatus(semaphore, proceed);
});
}
function checkStatus(sem, callback)
{
if (sem == 2)
{
callback();
}
}
function goAjax(args, callback) {
$.ajax({
...
dataType: "jsonp",
success: function(data) {
callback(data);
},
});
}
A: I don't see a problem with what you are doing though I'd prefer to batch those two requests together. By batching, I mean consolidate it into one call and in the server that handles the request, make the two service calls that would have been otherwise called separately and then have it handled in the one callback. Having to wait for those two calls to be completed in javascript defeats the whole purpose of making them asynchronous(ajax) calls. Those two calls are probably called separately in certain cases but it doesn't hurt to add some mechanism in your javascript and service to handle multiple requests in one call, for cases like when it's applicable.
A: I use after for this functionality
$(document).ready(function() {
var proceed = function() { ... },
next = after(2, proceed);
goAjax('arg0', function(data) {
next();
});
goAjax('arg1', function(data) {
next();
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to parse in javascript all regex between one or more parentheses I'm trying to parse all of the text between one or more parentheses and return an array.
For example:
var string = "((CID:34746) OR (CID:8097)) ((CID:34277 OR CID:67300))";
var regex = /\(([^()]+)\)/g;
var results = string.match(regex);
// should result in ["CID:34746","CID:8097","CID:34277 OR CID:67300"]
// but instead is ["(CID:34746)", "(CID:8097)", "(CID:34277 OR CID:67300)"]
I've had 3 people on my team try to find a solution and nobody has. I've looked at all the ones I can find on SO and otherwise. (This one is where I posted the above regex from...)
The closest I've gotten is: /([^()]+)/g.
A: .match() will return an array of whole matches only, if you use the global modifier. Use .exec() [MDN] instead:
var match,
results = [];
while(match = regex.exec(string)) {
results.push(match[1]);
}
A: Your regex is correct you're just not using it right:
var string = "((CID:34746) OR (CID:8097)) ((CID:34277 OR CID:67300))";
var regex = /\(([^()]+)\)/g;
var desiredResults = [];
var results;
while( results = regex.exec(string) ) {
desiredResults.push( results[1] );
}
// now desiredResults is ["CID:34746","CID:8097","CID:34277 OR CID:67300"]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to dynamically create DOM element with Codeigniter's MVC I understand the code you use to generate the page would be put in the view section of the MVC pattern of CI.
I am trying to understand the logic flow of the function when
1. user provide input
2. input sent to database
3. add another DOM element to show the input.
For example, just like Facebook, when you leave a message on someone's status, your message will be 'added' to that chain of reply to the status.
So in the view.php, I would write such that when you try to reply, an Ajax call would be made to the controller.php, and routed to model.php (which would 'add' the new msg to the status in the DB), after this, where do I go from here?
A: At client side, when lets say 'add' button is pressed, message is sent back to the server via Ajax. Server processes the message, and returns result back to the client. Now you have two options:
*
*Server responds only with success or failure. In case of failure, your JavaScript displays error message, in case of success, you append a message to the list (using values you sent to server)
*Server responds with all data that should be appended (lets say message, author, date, ...). Server can returns such data as JSON, and since JSON=JavaScript Object Notation, JavaScript can easily parse it. Using that data, you construct new node and append it.
JSON response can look something like this:
{
message: 'I like the new picture!',
author : 'William',
date : '2011-10-9'
}
and you parse it with JavaScript. Reference this question for example of parsing: Parse JSON in JavaScript?
I'd suggest you to use the second option, since server side may do some message filtering/cleaning and final result displayed to user may not be the same as he entered it.
I'm not using CodeIgniter, but Zend, and it has some nice logic to change response type from HTML to JSON or XML. This question may help you a bit: codeigniter JSON
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NSWindowController never deallocated I have a NSWindowController subclass, and in the windowWillClose: notification I send autorelease to the window controller. But still dealloc is never called. I have no timers in the class, so that's not the problem. Any ideas?
A: The problem was that I was using garbage collection. I guess you shouldn't really use things when you're not 100% sure of how they work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to prevent a SUSE RPM from installing on a RedHat system We have a product that is distributed via RPMs. We create both SUSE SLES10 SP1 RPMs and RedHat 5.5 RPMs. There are differences between the two, things will not work correctly (often mysteriosly) if you install a SUSE RPM on a RedHat machine and vice versa.
Is there a way to prevent a RedHay RPM from being installed on a SUSE system and vice versa? I googled around for this and found http://www.rpm.org/max-rpm/ch-rpm-multi.html but all the constraints here seem to be based on the output from the command uname which doesn't tell you if you're running RedHat or Suse. The os is Linux, and the architecture is the same.
We have ideas to add checks in the install script that can look for 'Red Hat' or 'SUSE' in the /etc/issue file but I'm really hoping there is a better option than this.
A: Since you're specifically just looking to detect RedHat, look for the presence of a file named /etc/redhat-release. If it's there, you're installing on some version of RedHat.
A: You can place a dependency on a redhat-specific package (although SuSE may provide a version).
You could also have your %pre check /etc/redhat-release (or lsb-release etc) for supported OS.
Do any pre-install checks in %pre, not %post, because otherwise they will happen after the package is already installed (%post cannot really fail usefully)
A: Also, you can check if the %{rhel} macro is defined in the spec file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Matching two words with some characters in between in regular expression I want to do a match for a string when no abc is followed by some characters (possibly none) and ends with .com.
I tried with the following:
(?!abc).*\.com
or
(?!abc).*?\.com
or
(?<!abc).*\.com
or
(?<!abc).*?\.com
But none of these worked. Please help.
Many thanks!
Edit
Sorry if I did not make myself clear. Just give some examples. I want def.edu, abc.com, abce.com, eabc.com and abcAnYTHing.com do not match, while a.com, b.com, ab.com, ae.com etc. match.
A: It's unclear from your wording if you want to match a string ending with .com AND NOT containing abc before that; or to match a string that doesn't have "abc followed by characters followed by .com".
Meaning, in the first case, "def.edu" does NOT match (no "abc" but doesn't end with ".com") but in the second case "def.edu" matches (because it's not "abcSOMETHING.com")
In the first case, you need to use negative look-behind:
(?<!abc.+)\.com$
# Use .* instead of .+ if you want "abc.com" to fail as well
IMPORTANT: your original expression using look-behind - #3 ( (?<!abc).*\.com ) - didn't work because look-behind ONLY looks behind immediately preceding the next term. Therefore, the "something after abc" should be included in the look-behind together with abc - as my RegEx above does.
PROBLEM: my RegEx above likely won't work with your specific RegEx Engine, unless it supports general look-behinds with variable length expression (like the one above) - which ONLY .NET does these days (A good summary of what does and doesn't support what flavors of look-behind is at http://www.regular-expressions.info/lookaround.html ).
If that is indeed the case, you will have to do double match: first, check for .com; capturing everything before it; then negative match on abc. I will use Perl syntax since you didn't specify a language:
if (/^(.*)\.com$/) {
if ($1 !~ /abc/) {
# Or, you can just use a substring:
# if (index($1, "abc") < 0) {
# PROFIT!
}
}
In the second case, the EASIEST thing to do is to do a "does not match" operator - e.g. !~ in Perl (or negate a result of a match if your language doesn't support "does not match"). Example using pseudo-code:
if (NOT string.match(/abc.+\.com$/)) ...
Please note that you don't need ".+"/".*" when using negative lookbehind;
A: Condensing:
Sorry if I did not make myself clear. Just give some examples.
I want def.edu, abc.com, abce.com, eabc.com and
abcAnYTHing.com do not match,
while a.com, b.com, ab.com, ae.com etc. match.
New regex after revised OP examples:
/^(?:(?!abc.*\.com\$|^def\.edu\$).)+\.(?:com|edu)\$/s
use strict;
use warnings;
my @samples = qw/
<newline>
shouldn't_pass
def.edu abc.com abce.com eabc.com
<newline>
should_pass.com
a.com b.com ab.com ae.com
abc.edu def.com defa.edu
/;
my $regex = qr
/
^ # Begin string
(?: # Group
(?! # Lookahead ASSERTION
abc.*\.com$ # At any character position, cannot have these in front of us.
| ^def\.edu$ # (or 'def.*\.edu$')
) # End ASSERTION
. # This character passes
)+ # End group, do 1 or more times
\. # End of string check,
(?:com|edu) # must be a '.com' or '.edu' (remove if not needed)
$ # End string
/sx;
print "\nmatch using /^(?:(?!abc.*\.com\$|^def\.edu\$).)+\.(?:com|edu)\$/s \n";
for my $str ( @samples )
{
if ( $str =~ /<newline>/ ) {
print "\n"; next;
}
if ( $str =~ /$regex/ ) {
printf ("passed - $str\n");
}
else {
printf ("failed - $str\n");
}
}
Output:
match using /^(?:(?!abc.*.com$|^def.edu$).)+.(?:com|edu)$/s
failed - shouldn't_pass
failed - def.edu
failed - abc.com
failed - abce.com
failed - eabc.com
passed - should_pass.com
passed - a.com
passed - b.com
passed - ab.com
passed - ae.com
passed - abc.edu
passed - def.com
passed - defa.edu
A: This looks like an XY Problem.
DVK's answer shows you how you can tackle this problem using regular expressions, like you asked for.
My solution (in Python) demonstrates that regular expressions are not necessarily the best approach and that tackling the problem using your programming language's string-handling functionality may produce a more efficient and more maintainable solution.
#!/usr/bin/env python
import unittest
def is_valid_domain(domain):
return domain.endswith('.com') and 'abc' not in domain
class TestIsValidDomain(unittest.TestCase):
def test_edu_invalid(self):
self.assertFalse(is_valid_domain('def.edu'))
def test_abc_invalid(self):
self.assertFalse(is_valid_domain('abc.com'))
self.assertFalse(is_valid_domain('abce.com'))
self.assertFalse(is_valid_domain('abcAnYTHing.com'))
def test_dotcom_valid(self):
self.assertTrue(is_valid_domain('a.com'))
self.assertTrue(is_valid_domain('b.com'))
self.assertTrue(is_valid_domain('ab.com'))
self.assertTrue(is_valid_domain('ae.com'))
if __name__ == '__main__':
unittest.main()
See it run!
Update
Even in a language like Perl, where regular expressions are idiomatic, there's no reason to squash all of your logic into a single regex. A function like this would be far easier to maintain:
sub is_domain_valid {
my $domain = shift;
return $domain =~ /\.com$/ && $domain !~ /abc/;
}
(I'm not a Perl programmer, but this runs and gives the results that you desire)
A: Do you just want to exclude strings that start with abc? That is, would xyzabc.com be okay? If so, this regex should work:
^(?!abc).+\.com$
If you want to make sure abc doesn't appear anywhere, use this:
^(?:(?!abc).)+\.com$
In the first regex, the lookahead is applied only once, at the beginning of the string. In the second regex the lookahead is applied each time the . is about to match a character, ensuring that the character is not the beginning of an abc sequence.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Performance of querying relational data with document-based nosql (mongodb, couchdb, and riak, etc) To follow up on my question on modeling relational data with nosql, I have read several articles on the subject:
Nosql doesn't mean non-relational
Nosql Ecommerce Example
They seem to suggest that nosql can handle normalized, relational data.
So let's continue with the example I had before, a CMS system that have two types of data: article and authors, where article has an reference (by ID) to author.
Below are the operations the system needs to support:
*
*Fetch a article by id along with the author
*Fetch all articles by particular author
*Find the first 10 article(s) with the author(s) sorted by creation date
I would like to understand the performance of these operation when compare to the same operation if the same data were stored on RDBMS. In particular, please specify if the operation uses MapReduce, require multple trips to the nosql store (Links), or pre-join
I would like to limit to discussion to document-based nosql solution like mongodb, couchdb, and riak.
Edit 1:
Spring-data project is avalible on Riak and Mongodb
A: Just wanted to toss in a CouchDB answer for anyone who might be curious. :)
As mentioned in the first answer above, embedding the author document into the article document is unwise, so the examples below assume two document types: articles and authors.
CouchDB uses MapReduce queries typically written in JavaScript (but Python, Ruby, Erlang and others are availble). The results of a MapReduce query are stored in an index upon their first request and that stored index is used to for all future look-ups. Changes to the database are added to the index upon further requests.
CouchDB's API is completely HTTP-based, so all requests to the database are HTTP verbs (GET, POST, PUT, DELETE) at various URLs. I'll be listing both the MapReduce queries (written in JavaScript) along with the URL used to request related results from the index.
1. Fetch a article by id along with the author
The simplest method for doing this is two direct document lookups:
GET /db/{article_id}
GET /db/{author_id}
...where {author_id} is the value obtained from the article's author_id field.
2. Fetch all articles by particular author
MapReduce
function (doc) {
if (doc.type === 'article') {
emit(doc.author_id, doc);
}
}
GET /db/_design/cms/_view/articles_by_author?key="{author_id}"
...where {author_id} is the actual ID of the author.
3. Find the first 10 article(s) with the author(s) sorted by creation date
MapReduce
function (doc) {
function arrayDateFromTimeStamp(ts) {
var d = new Date(ts);
return [d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds()];
}
var newdoc = doc;
newdoc._id = doc.author_id;
newdoc.created_at = arrayDateFromTimeStamp(doc.created_at);
if (doc.type === 'article') {
emit(newdoc.created_at, newdoc);
}
}
It's possible to do include style "joins" in CouchDB using ?include_docs=true in a view request. If you include a "_id" key in the value side of the emit (the second argument), then adding include_docs=true to your query parameters will include the doc referenced by the specified "_id" In the case above, we're replacing the document's own "_id" (which we don't need anymore) with the referenced author's "_id" (the value of "author_id" in the article document). Requesting the top 10 articles with their related author info looks like this:
GET /db/_design/cms/_view/articles_by_date?descending=true&limit=10&include_docs=true
Requesting that URL will return a list of the most recent 10 articles in a format similar to:
{"rows":[
{ "id":"article_id",
"key":[2011, 9, 3, 12, 5, 41],
"value":{"_id":"author_id", "title":"..."},
"doc":{"_id":"author_id", "name":"Author Name"}
}
]}
Using this same index you can get a list of all the documents any any year, month, day, hour, etc granularity with or without author data.
There are also methods for using view collation to aggregate several documents together out of a single document (like a page in a CMS referencing disparate content). There's some info on how to do that in these slides I did for CouchConf in July: http://www.slideshare.net/Couchbase/couchconfsfdesigningcouchbasedocuments
If you have any other questions, please let me know.
A:
Fetch a article by id along with the author
SQL:
*
*1 query
*2 index lookups
*2 data lookups
*data returned = article + author
MongoDB:
*
*2 queries
*2 index lookups
*2 data lookups
*data returned = article + author
Fetch all articles by particular author
SQL:
*
*1 query
*1 index lookup
*N data lookups
*data returned = N articles
MongoDB:
*
*1 query
*1 index lookup
*N data lookups
*data returned = N articles
Find the first 10 article(s) with the author(s) sorted by creation date
SQL:
*
*1 query
*2 index lookups
*11 to 20 data lookups (articles then unique authors)
*data returned = 10 articles + 10 authors
MongoDB:
*
*2 queries (articles.find().sort().limit(10), authors.find({$in:[article_authors]})
*2 index lookups
*11 to 20 data lookups (articles then unique authors)
*data returned = 10 articles + 1 to 10 authors
Summary
In two cases MongoDB requires an extra query, but does most of the same total work underneath. In some cases MongoDB returns less data over the network (no repeated entries). The join queries tend to be limited by the requirement that all the data to join live on the same box. If Authors and Articles live in different places, then you end up doing two queries anyways.
MongoDB tends to get better "raw" performance because it doesn't flush to disk with every write (so it's actually a "durability" tradeoff). It also has a much smaller query parser, so there's less activity per query.
From a basic performance standpoint these things are very similar. They just make different assumptions about your data and the trade-offs you want to make.
A: For MongoDB, you wouldn't use embedded documents for the author record. So the pre-join is out, it's multiple trips to the DB. However, you can cache the author and only need to make that second trip once for each record. The queries you indicated are pretty trivial in MongoDB.
var article = db.articles.find({id: article_id}).limit(1);
var author = db.authors.find({id: article.author_id});
If you are using an ORM/ODM to manage your entities within your application, this would transparent. It would be two trips to the db though. They should be fast responses though, two hits shouldn't be noticeable at all.
Finding articles by a given author is just reverse...
var author = db.authors.find({id: author_name}).limit(1);
var articles = db.articles.find({author_id: author.id});
So again, two queries but the single author fetch should be fast and can easily be cached.
var articles = db.articles.find({}).sort({created_at: 1}).limit(10);
var author_ids = articles.map(function(a) { return a.author_id });
var authors = db.authors.find({id: { '$in': authors_ids }});
Lastly, again, two queries but just a tiny bit more complex. You can run these in a mongo shell to see what the results might be like.
I'm not sure this is worth writing a map reduce to complete. A couple quick round trips might have a little more latency but the mongo protocol is pretty fast. I wouldn't be overly worried about it.
Lastly, real performance implications of doing it this way... Since ideally you'd only be querying on indexed fields in the document, it should be pretty quick. The only additional step is a second round trip to get the other documents, depending how your application and db is structures, this is likely not a big deal at all. You can tell mongo to only profile queries that take over a given threshold (100 or 200ms by default when turned on), so you can keep an eye on what's taking time for your program as data grows.
The one befit you have here that an RDMS does not offer is much easier breaking apart of data. What happens when you expand your application beyond CMS to support other things but uses the same authentication store? It just happens to be a completely separate DB now, that's shared across many applications. It's much simpler to perform these queries across dbs - with RDMS stores it's a complex process.
I hope this helps you in your NoSQL discovery!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Alternative to PHP's associative arrays in JAVA In PHP I could use an array with strings as keys. eg
$some_array["cat"] = 123;
$some_array["dog"] = 456;
I just switched to Java and I can't find a data structure capable of doing this. Is this possible?
A: What you are describing is an associative array, also called a table, dictionary, or map.
In Java, you want the Map interface, and probably the HashMap class as the implementation.
Map<String, Integer> myMap = new HashMap<String, Integer>();
myMap.put("cat", 123);
Integer value = myMap.get("cat"); //123
A: You would use one of the Map implementations such as HashMap to do that.
A: You want to use a Map, most likely a HashMap.
A: The data structure you are after is Map. I believe its an abstract class so you'll have to use one of its concrete subclasses like HashMap<?>
A: As many people said, a Map is what you are looking for. If that was your choice, do not forget to reimplement hashcode() and equals(). Take a look because is a must: http://www.ibm.com/developerworks/java/library/j-jtp05273/index.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Limit results in jQuery UI Autocomplete I am using jQuery UI Autocomplete.
$("#task").autocomplete({
max:10,
minLength:3,
source: myarray
});
The max parameter doesn't work and I still get more than 10 results. Am I missing something?
A: I could solve this problem by adding the following content to my CSS file:
.ui-autocomplete {
max-height: 200px;
overflow-y: auto;
overflow-x: hidden;
}
A: You can set the minlength option to some big value or you can do it by css like this,
.ui-autocomplete { height: 200px; overflow-y: scroll; overflow-x: hidden;}
A: If the results come from a mysql query, it is more efficient to limit directly the mysql result:
select [...] from [...] order by [...] limit 0,10
where 10 is the max numbers of rows you want
A: Here is the proper documentation for the jQueryUI widget. There isn't a built-in parameter for limiting max results, but you can accomplish it easily:
$("#auto").autocomplete({
source: function(request, response) {
var results = $.ui.autocomplete.filter(myarray, request.term);
response(results.slice(0, 10));
}
});
You can supply a function to the source parameter and then call slice on the filtered array.
Here's a working example: http://jsfiddle.net/andrewwhitaker/vqwBP/
A: Same like "Jayantha" said using css would be the easiest approach, but this might be better,
.ui-autocomplete { max-height: 200px; overflow-y: scroll; overflow-x: hidden;}
Note the only difference is "max-height". this will allow the widget to resize to smaller height but not more than 200px
A: Adding to Andrew's answer, you can even introduce a maxResults property and use it this way:
$("#auto").autocomplete({
maxResults: 10,
source: function(request, response) {
var results = $.ui.autocomplete.filter(src, request.term);
response(results.slice(0, this.options.maxResults));
}
});
jsFiddle: http://jsfiddle.net/vqwBP/877/
This should help code readability and maintainability!
A: I did it in following way :
success: function (result) {
response($.map(result.d.slice(0,10), function (item) {
return {
// Mapping to Required columns (Employee Name and Employee No)
label: item.EmployeeName,
value: item.EmployeeNo
}
}
));
A: jQuery allows you to change the default settings when you are attaching autocomplete to an input:
$('#autocomplete-form').autocomplete({
maxHeight: 200, //you could easily change this maxHeight value
lookup: array, //the array that has all of the autocomplete items
onSelect: function(clicked_item){
//whatever that has to be done when clicked on the item
}
});
A: Plugin:
jquery-ui-autocomplete-scroll
with scroller and limit results are beautiful
$('#task').autocomplete({
maxShowItems: 5,
source: myarray
});
A: I've tried all the solutions above, but mine only worked on this way:
success: function (data) {
response($.map(data.slice (0,10), function(item) {
return {
value: item.nome
};
}));
},
A: here is what I used
.ui-autocomplete { max-height: 200px; overflow-y: auto; overflow-x: hidden;}
The overflow auto so the scroll bar will not show when it's not supposed to.
A: There is no max parameter.
http://docs.jquery.com/UI/Autocomplete
A: In my case this works fine:
source:function(request, response){
var numSumResult = 0;
response(
$.map(tblData, function(rowData) {
if (numSumResult < 10) {
numSumResult ++;
return {
label: rowData.label,
value: rowData.value,
}
}
})
);
},
A: I'm leaving this one for anyone who is using this library
JavaScript-autoComplete/1.0.4/auto-complete.js
This might be helpful as the Demo version doesn't show how to limit results. Based on Andrew response.
new autoComplete({
selector: 'input[name="name_of_searchbox"]',
minChars: 1,
source: function(term, suggest){
term = term.toLowerCase();
var choices = [];
var matches = []; //For Pushing Selected Terms to be always visible, can be adapter later on based on user searches
for (i=0; i<choices.length; i++)
if (~choices[i].toLowerCase().indexOf(term)) matches.push(choices[i]);
suggest(matches.slice(0,10));
}
});
Hope this is of use to anyone.
Cheers!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "138"
} |
Q: Why is this multibinding not working I have sending multiple parameters from my Checkbox Command. I have used a converter. The code is below. If i put a debugger and see the values here are my results :
When checkbox check is either checked or unchekcked :
In the converter it has teh values (Array of the item object and boolean). But when i come to my method, the value is a object[2] but both values are NULL
CheckBox XAML
<CheckBox x:Name="checkBox"
Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Data.Label}"
ClickMode="Release"
Command="{Binding Path=DataContext.SelectUnSelect}">
<CheckBox.CommandParameter>
<MultiBinding Converter="{StaticResource SelectedItemConverter}">
<Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Content.Data"/>
<Binding RelativeSource="{RelativeSource Self}" Path="IsChecked"/>
</MultiBinding>
</CheckBox.CommandParameter>
Convertor :
public class CheckConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return values;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
View Model Command Code :
public ICommand SelectUnSelect
{
get { return new RelayCommand<object>(parm => this.SelectAndUnSelect(parm));}
}
If i put a debugger in SelectAndUnSelect method, it shows me object[2] in parm but both of them are null.
Observation : If i bind my command parameter to any one of the bindings it works fine.
What am i missing here ?
*
*Shankar
A: I've had the same problem before, if I remember correctly then returning values.ToList() instead of just values should fix it
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values.ToList();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Vectorizing code and stuck but good Here are some sample starting values for variables in the code below.
sd <- 2
sdtheory <- 1.5
meanoftheory <- 0.6
obtained <- 0.8
tails <- 2
I'm trying to vectorize the following code. It is a component of a Bayes factor calculator that was originally written by Dienes and adapted to R by Danny Kaye & Thom Baguley. This part is for calculating the likelihood for the theory. I've got the thing massively sped up by vectorizing but I can't match output of the bit below.
area <- 0
theta <- meanoftheory - 5 * sdtheory
incr <- sdtheory / 200
for (A in -1000:1000){
theta <- theta + incr
dist_theta <- dnorm(theta, meanoftheory, sdtheory)
if(identical(tails, 1)){
if (theta <= 0){
dist_theta <- 0
} else {
dist_theta <- dist_theta * 2
}
}
height <- dist_theta * dnorm(obtained, theta, sd)
area <- area + height * incr
}
area
And below is the vectorized version.
incr <- sdtheory / 200
newLower <- meanoftheory - 5 * sdtheory + incr
theta <- seq(newLower, by = incr, length.out = 2001)
dist_theta <- dnorm(theta, meanoftheory, sdtheory)
if (tails == 1){
dist_theta <- dist_theta[theta > 0] * 2
theta <- theta[theta > 0]
}
height <- dist_theta * dnorm(obtained, theta, sd)
area <- sum(height * incr)
area
This code exactly copies the results of the original if tails <- 2. Everything I've got here so far should just copy and paste and give the exact same results. However, once tails <- 1 the second function no longer matches exactly. But as near as I can tell I'm doing the equivalent in the new if statement to what is happening in the original. Any help would be appreciated.
(I did try to create a more minimal example, stripping it down to just he loop and if statements and a tiny amount of slices and I just couldn't get the code to fail.)
A: You're dropping observations where theta==0. That's a problem because the output of dnorm is not zero when theta==0. You need those observations in your output.
Rather than drop observations, a better solution would be to set those elements to zero.
incr <- sdtheory / 200
newLower <- meanoftheory - 5 * sdtheory + incr
theta <- seq(newLower, by = incr, length.out = 2001)
dist_theta <- dnorm(theta, meanoftheory, sdtheory)
if (tails == 1){
dist_theta <- ifelse(theta < 0, 0, dist_theta) * 2
theta[theta < 0] <- 0
}
height <- dist_theta * dnorm(obtained, theta, sd)
area <- sum(height * incr)
area
A: The original calculation has an error due to floating point arithmetic; adding incr each time causes theta to actually equal 7.204654e-14 when it should equal zero. So it's not actually doing the right thing on that pass through the loop; it's not doing the <= code when it should be. Your code is (at least, it did with these starting values on my machine).
Your code isn't necessarily guaranteed to do the right thing every time either; what seq does is better than adding an increment over and over again, but it's still floating point arithmetic. You really should probably be checking to within machine tolerance of zero, perhaps using all.equal or something similar.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Public static class for sending system messages to the users - asp.net 4.0 asp.net 4.0 - C# - MSSQL 2008 r2 db
I already have a private messaging system. At certain actions i am sending them private messages. Right now i am adding them by direct insert query to the database inside code behind of asp.net page. These messages are being sent by system not user.
For sending these messages (simply adding message to the database) i am planning to prepare a public static class. Do you think this would work ?
Public static class will take this variables
userId of message receiving user, message title, message body
It won't do any select query to the database only insert query for sending message to the user.
There could be even 10 simultaneous call of class in an instant can this cause any problem ?
Thank you.
edit this is the class
using System;
using System.Data.SqlClient;
using System.Data;
public static class SendMessage
{
public static string srCommandText = "insert into mymessagestable (SenderUserId,ReceiverUserId,SentTime,Topic,Body) values(@SenderUserId,@ReceiverUserId,@SentTime,@Topic,@Body) ";
public static bool SendMessageToDb(string srReceiverUserId, string srSenderUserId, string srSentTime, string srTopic, string srBody)
{
using (SqlConnection connection = new SqlConnection(DbConnection.srConnectionString))
{
try
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(srCommandText, connection))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@SenderUserId", srSenderUserId);
cmd.Parameters.AddWithValue("@ReceiverUserId", srReceiverUserId);
cmd.Parameters.AddWithValue("@SentTime", srSentTime);
cmd.Parameters.AddWithValue("@Topic", srTopic);
cmd.Parameters.AddWithValue("@Body", srBody);
cmd.ExecuteNonQuery();
}
}
catch
{
return false;
}
return true;
}
}
}
A: The only issue would be a violation of a unique constraint/primary key during rapid concurrent inserts. As long as all inserts are unique, you will be fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery.get - can the reply be too large? jQuery.get("/url2?key=abc", function(data){eval(data);});
This working fine except when the amount of data has grown.
Is there a maximum size you can get data by this method if so how do you get large replies?
A: Not sure if there is any limit on size, but practical considerations come into play:
1) The request can take too long to return, if the server is processing large amounts of data and needs to send it over the wire.
2) Once the response is returned, it takes too long to do client side calculations.
3) You return so much data that it increases browser's memory usage too much.
There are no hard and fast rules; if the users can wait a couple minutes to load the app, and have computers with lots of ram, then maybe its ok. You could also cache via localstorage (assuming you don't need to support older browsers) large data, so you only have to retrieve it once (if it doesn't change, or it doesn't change often).
Note that jsonp is much faster at loading and processing large data sets. So you might want to switch over to it for large datasets.
A: It is 102330 bytes I think, so about 8 MB's or about 1076ish KB's
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to determine if a field is NULL or NOT NULL in mysql workbench gui? Is there any gui functionality within mysql workbench where you can view whether a field is set to NULL or NOT NULL?
For example this:
CREATE TABLE Peoples (
id INT NOT NULL AUTO_INCREMENT,
first_name VARCHAR (200) NULL,
last_name VARCHAR (100) NOT NULL,
PRIMARY KEY (id)
);
Is displayed as
Table Peoples
=============
id, first_name, last_name
-------------
id int(11) PK
first_name varchar(200)
last_name varchar(100)
In the Object Information tab. The object information tab does not specify that the first_name is NULL and the last name is NOT NULL.
A: Under "Data Modelling" use "Create EER Model From Existing Database" or open up an existing model of the desired database if you have one. Then select the desired table and the bottom window will show the table's properties. The "Columns" tab will show what columns are NULL by default.
A: It seems unfortunate that one would need to create an entire EER model just to see if a column is nullable.. another workaround i found is to right-click on the table and choose 'Alter Table' and the editor that comes up shows the NN column, checked or not (version 5.2.47).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: jme3 / Java 3d path implementations? Coming from an Android development background into a PC-gaming environment, I'm looking for something similar to Android's Path class. However, the Android path class is 2d, and I need a 3d (circular) path. Specifically, I'm preparing a space-like simulation and need to emulate an "orbit."
Does Java have a path class? If not, is there an API for 3d paths (circular or non)?
A: Take a look into GeneralPath and Java3D PathInterpolator
From the Java6SE release notes....
"For a long time the Java 2D API lacked a double version of the GeneralPath class. The Path2D class represents a path that can be iterated by the PathIterator interface and has two subclasses: Path2D.Float and Path2D.Double. In the changed hierarchy, the GeneralPath class became a subclass of the Path2D.Float class. They both can be used for single point precision, while the Path2D.Double class can be applied for double point precision. One reason to use the Path2D.Float class over the GeneralPath class is to make your code more consistence and explicit if both single and double precision types are employed in the application."
From Java3D :
http://download.java.net/media/java3d/javadoc/1.3.2/javax/media/j3d/PathInterpolator.html
These examples might not hurt either:
http://java.sun.com/products/java-media/2D/samples/suite/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Column headings keep appearing throughout Oracle output After ever 10 lines, my column headers reappear in my Oracle output. Is there something about my code or some kind of environment variable I can set to stop this? I only need the column headers to appear once at the top of my results.
BREAK ON Customer
COLUMN Customer -
FORMAT A15 -
HEADING 'Customer Name'
COLUMN "Charter Date" -
HEADING 'Charter|Date'
COLUMN Pilot -
FORMAT A20 -
HEADING 'Pilot'
SELECT DECODE (cu.cus_initial,null, cu.cus_fname||' '||cu.cus_lname,
cu.cus_fname||' '||cu.cus_initial||'. '||cu.cus_lname)
AS Customer,
ch.char_date "Charter Date",
TRIM( e.emp_fname) ||' '|| TRIM(e.emp_lname) AS "Pilot"
FROM hartmar.customer cu,
hartmar.charter ch,
hartmar.crew cr,
hartmar.pilot p,
hartmar.employee e
WHERE cu.cus_code = ch.cus_code
AND ch.char_trip = cr.char_trip
AND cr.emp_num = p.emp_num
AND p.emp_num = e.emp_num
AND cr.crew_type = 'Pilot'
ORDER BY cu.cus_lname, cu.cus_fname, cu.cus_initial, ch.char_date
;
CLEAR BREAKS
CLEAR COLUMNS
A: Assuming you're running this in SQL*Plus, you need to set your pagesize.
SET PAGESIZE 50000
will cause the columns headings to appear only once for every 50,000 rows returned. I believe 50,000 is the maximum PAGESIZE setting.
If you want to eliminate headers entirely, you can set the PAGESIZE to 0 but that will suppress even the first set of headers
SQL> set pagesize 0;
SQL> select ename, empno from emp;
PAV 7623
smith 7369
ALLEN 7499
WARD 7521
JONES 7566
MARTIN 7654
BLAKE 7698
CLARK 7782
SCOTT 7788
KING 7839
TURNER 7844
ADAMS 7876
SM0 7900
FORD 7902
MILLER 7934
BAR 1234
16 rows selected.
A: Use a 'hidden' feature that will suppress all EXCEPT the first row of headings!
set pagesize 0 embedded on
Thanks to "Bruno Ruess" via https://community.oracle.com/thread/2389479?start=0&tstart=0 for the above.
If you then also add
SET UNDERLINE off
Then you can supress the "underlining" of the header row, and get to something that looks a lot more like a CSV.
A: You can also:
SET PAGESIZE 0
To stop all column headers after the start of your report.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: how do i enable screen zoom/magnification programmatically under os x? i'm talking about the "zoom" functionality in the universal access system preference panel. normally this is accomplished with command–option–8. then the zoom controls are command–option–+ (magnify) and command–option–- (minus/minify).
my most recent attempt involved sending the keypresses for the shortcuts as events. however this approach has serious bugs. on top of that, i don't know whether the user already has zoom enabled. i'm looking for something cleaner. like, the way you're supposed to do it.
of course there is always using applescript to open the system preferences pane and toggle the radio buttons, but that is not really what i would call "clean."
even if you don't know exactly how to accomplish what i'm asking, even some pointers as to where this kind of thing (programmatic toggling of os functionality) might be documented would be helpful. the language doesn't matter. thanks.
A: it's not quite what i wanted, but UAZoomEnabled() in /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/Headers/UniversalAccess.h lets me know whether zoom is currently enabled. then i know whether to send the command-option-8 keystrokes using CGEventCreateKeyboardEvent(), CGEventSetFlags() and CGEventPost(). in order to make sure that they're zoomed in 10 ticks, i zoom out 100 ticks, then zoom in 10 ticks.
source: http://lists.apple.com/archives/accessibility-dev/2011/Mar/msg00013.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Is there a UIImagePicker for the Mac Desktop I have found Apple's example app ImagePicker that uses IKImagePicker, but it appears that in Lion it has been removed. Is there an alternative to this - or how would I prompt users to select an image to use within my app.
A: You want IKPictureTaker.
The IKPictureTaker class represents a panel that allows users to choose images by browsing the file system. The picture taker panel provides an Open Recent menu, supports image cropping, and supports taking snapshots from an iSight or other digital camera.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Discover collation of a MySQL column I previously created a MySQL table and now I want to find out what collation some of the fields are using. What SQL or MySQL commands can I use to discover this?
A: SHOW CREATE TABLE [tablename] will show you the collation of each column as well as the default collation.
A: If you want the collation for just that specific column (for possible use with a subquery)...
SELECT COLLATION_NAME
FROM information_schema.columns
WHERE TABLE_SCHEMA = 'tableschemaname'
AND TABLE_NAME = 'tablename'
AND COLUMN_NAME = 'fieldname';
A: You could use SHOW FULL COLUMNS FROM tablename which returns a column Collation, for example for a table 'accounts' with a special collation on the column 'name'
mysql> SHOW FULL COLUMNS FROM accounts;
+----------+--------------+-------------------+------+-----+---------+----------+
| Field | Type | Collation | Null | Key | Default | Extra |
+----------+--------------+-------------------+------+-----+---------+----------|
| id | int(11) | NULL | NO | PRI | NULL | auto_inc |
| name | varchar(255) | utf8_bin | YES | | NULL | |
| email | varchar(255) | latin1_swedish_ci | YES | | NULL | |
...
Or you could use SHOW CREATE TABLE tablename which will result in a statement like
mysql> SHOW CREATE TABLE accounts;
CREATE TABLE `accounts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "70"
} |
Q: Convert Console.WriteLine into text box I checked on the net and I didn't find concrete examples for my situation...
What I want, is to have these Console.WriteLine displayed in a text box .
// Show data before change
Console.WriteLine("name before change: {0}",
thisDataSet.Tables["Customers"].Rows[9]["CompanyName"]);
// Change data in Customers table, row 9, CompanyName column
thisDataSet.Tables["Customers"].Rows[9]["CompanyName"] = "Acme, Inc.";
// Call Update command to mark change in table
thisAdapter.Update(thisDataSet, "Customers");
Console.WriteLine("name after change: {0}",
thisDataSet.Tables["Customers"].Rows[9]["CompanyName"]);
I tried this;
string1=("name before change: {0}",
thisDataSet.Tables["Customers"].Rows[9]["CompanyName"]);
thisDataSet.Tables["Customers"].Rows[9]["CompanyName"] = "Acme, Inc.";
thisAdapter.Update(thisDataSet, "Customers");
string2=("name after change: {0}",
thisDataSet.Tables["Customers"].Rows[9]["CompanyName"].ToString());
thisConnection.Close();
textBox1.Text = string1() + string2();
A: string1=("name before change: {0}",
thisDataSet.Tables["Customers"].Rows[9]["CompanyName"]);
should be
string1=string.Format("name before change: {0}",
thisDataSet.Tables["Customers"].Rows[9]["CompanyName"]);
(same for string2) and
textBox1.Text = string1() + string2();
should be
textBox1.Text = string1 + string2;
A: I would use StringBuilder and then string.Format for readability:
var sb = new StringBuilder();
sb.AppendFormat("name before change: {0}",
thisDataSet.Tables["Customers"].Rows[9]["CompanyName"]);
thisDataSet.Tables["Customers"].Rows[9]["CompanyName"] = "Acme, Inc.";
thisAdapter.Update(thisDataSet, "Customers");
sb.AppendFormat("name after change: {0}",
thisDataSet.Tables["Customers"].Rows[9]["CompanyName"]);
textBox1.Text = sb.ToString();
A: Write to a StringWriter for your text box. It's a TextWriter (which the "console" is exposed as) so you can easily swap in Console.Out or a plain old StringWriter to write your messages. In your windows application, you could then put the contents of the writer into your text box.
////////////////////////////////////////
// for a console application
TextWriter writer = Console.Out;
// for a windows application
TextWriter writer = new StringWriter();
////////////////////////////////////////
// Show data before change
writer.WriteLine("name before change: {0}",
thisDataSet.Tables["Customers"].Rows[9]["CompanyName"]);
// Change data in Customers table, row 9, CompanyName column
thisDataSet.Tables["Customers"].Rows[9]["CompanyName"] = "Acme, Inc.";
// Call Update command to mark change in table
thisAdapter.Update(thisDataSet, "Customers");
writer.WriteLine("name after change: {0}",
thisDataSet.Tables["Customers"].Rows[9]["CompanyName"]);
////////////////////////////////////////
// for a windows application
textBox1.Text = writer.ToString();
////////////////////////////////////////
A: you can do it like that: textBox1.Text = string.Format("name before change: {0}", thisDataSet.Tables["Customers"].Rows[9]["CompanyName"]);
or:
textBox1.Text = "name before change: " + thisDataSet.Tables["Customers"].Rows[9]["CompanyName"];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In wxpython is there a wx.CallDuring I found wx.CallAfter and wx.CallLater in the documentation but neither solves my problem.
What I'm trying to do is update a status bar while doing a task, but both wx.CallAfter and wx.CallLater only updates after task.
Example:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Fri Sep 30 20:55:34 2011
import wx
import time
# begin wxGlade: extracode
# end wxGlade
class MyFrame1(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame1.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.frame_2_statusbar = self.CreateStatusBar(1, 0)
self.__set_properties()
self.__do_layout()
# end wxGlade
def __set_properties(self):
# begin wxGlade: MyFrame1.__set_properties
self.SetTitle("frame_2")
self.frame_2_statusbar.SetStatusWidths([-1])
# statusbar fields
frame_2_statusbar_fields = ["foo"]
for i in range(len(frame_2_statusbar_fields)):
self.frame_2_statusbar.SetStatusText(frame_2_statusbar_fields[i], i)
# end wxGlade
def __do_layout(self):
# begin wxGlade: MyFrame1.__do_layout
self.Layout()
# end wxGlade
def Test(self):
time.sleep(10)
for i in range(0,100):
time.sleep(0.1)
txt="I <3 Stack Exchange x " +str( i)
wx.CallAfter(self.frame_2_statusbar.SetStatusText,txt, 0)
wx.CallAfter(self.Update)
print txt
# end of class MyFrame1
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = MyFrame1(None, -1, "")
app.SetTopWindow(frame_1)
frame_1.Show()
wx.CallAfter(frame_1.Test)
app.MainLoop()
A: From the sound of it, "CallDuring" is nothing more than simply calling whatever function you want. It will get called exactly when you call it. Is there a reason why calling it directly doesn't solve your problem?
However, you're telling your program to sleep. No amount of "call during" will help you since you're putting the whole app to sleep. Maybe you think that sleep is a good simulation of "real" code, but it's not. You're actually telling your program "stop all processing", which includes screen updates.
The crux of your problem is that you're not allowing the event loop to process redraw events. You might try calling wx.Yield() in your loop, but having a large, long-running loop in the main thread of a GUI program is a code smell. There's almost certainly a better way to approach your problem.
The best advice I can give is to search on "wxpython long running task". Most likely the first hit will be a wxpywiki page titled "Long Running Tasks" that you might find helpful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Linked API to get all members of a group How can I get all the members belonging to a particular group or company with Linked API's.
I looked at the Groups API provided by linked it but it does not provide information to pull the member information.
A: This is not currently supported via the API.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How is a CSS "display: table-column" supposed to work? Given the following HTML and CSS, I see absolutely nothing in my browser (Chrome and IE latest at time of writing). Everything collapses down to 0x0 px. Why?
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
section { display: table; height: 100%; background-color: grey; }
#colLeft { display: table-column; height: 100%; background-color: green; }
#colRight { display: table-column; height: 100%; background-color: red; }
#row1 { display: table-row; height: 100%; }
#row2 { display: table-row; height: 100%; }
#row3 { display: table-row; height: 100%; }
#cell1 { display: table-cell; height: 100%; }
#cell2 { display: table-cell; height: 100%; }
#cell3 { display: table-cell; height: 100%; }
</style>
</head>
<body>
<section>
<div id="colLeft">
<div id="row1">
<div id="cell1">
AAA
</div>
</div>
<div id="row2">
<div id="cell2">
BBB
</div>
</div>
</div>
<div id="colRight">
<div id="row3">
<div id="cell3">
CCC
</div>
</div>
</div>
</section>
</body>
</html>
A: The "table-column" display type means it acts like the <col> tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.
See the W3C standard for more information about the CSS table model.
* And a few other properties like borders, backgrounds.
A: The CSS table model is based on the HTML table model
http://www.w3.org/TR/CSS21/tables.html
A table is divided into ROWS, and each row contains one or more cells. Cells are children of ROWS, they are NEVER children of columns.
"display: table-column" does NOT provide a mechanism for making columnar layouts (e.g. newspaper pages with multiple columns, where content can flow from one column to the next).
Rather, "table-column" ONLY sets attributes that apply to corresponding cells within the rows of a table. E.g. "The background color of the first cell in each row is green" can be described.
The table itself is always structured the same way it is in HTML.
In HTML (observe that "td"s are inside "tr"s, NOT inside "col"s):
<table ..>
<col .. />
<col .. />
<tr ..>
<td ..></td>
<td ..></td>
</tr>
<tr ..>
<td ..></td>
<td ..></td>
</tr>
</table>
Corresponding HTML using CSS table properties (Note that the "column" divs do not contain any contents -- the standard does not allow for contents directly in columns):
.mytable {
display: table;
}
.myrow {
display: table-row;
}
.mycell {
display: table-cell;
}
.column1 {
display: table-column;
background-color: green;
}
.column2 {
display: table-column;
}
<div class="mytable">
<div class="column1"></div>
<div class="column2"></div>
<div class="myrow">
<div class="mycell">contents of first cell in row 1</div>
<div class="mycell">contents of second cell in row 1</div>
</div>
<div class="myrow">
<div class="mycell">contents of first cell in row 2</div>
<div class="mycell">contents of second cell in row 2</div>
</div>
</div>
OPTIONAL: both "rows" and "columns" can be styled by assigning multiple classes to each row and cell as follows. This approach gives maximum flexibility in specifying various sets of cells, or individual cells, to be styled:
//Useful css declarations, depending on what you want to affect, include:
/* all cells (that have "class=mycell") */
.mycell {
}
/* class row1, wherever it is used */
.row1 {
}
/* all the cells of row1 (if you've put "class=mycell" on each cell) */
.row1 .mycell {
}
/* cell1 of row1 */
.row1 .cell1 {
}
/* cell1 of all rows */
.cell1 {
}
/* row1 inside class mytable (so can have different tables with different styles) */
.mytable .row1 {
}
/* all the cells of row1 of a mytable */
.mytable .row1 .mycell {
}
/* cell1 of row1 of a mytable */
.mytable .row1 .cell1 {
}
/* cell1 of all rows of a mytable */
.mytable .cell1 {
}
<div class="mytable">
<div class="column1"></div>
<div class="column2"></div>
<div class="myrow row1">
<div class="mycell cell1">contents of first cell in row 1</div>
<div class="mycell cell2">contents of second cell in row 1</div>
</div>
<div class="myrow row2">
<div class="mycell cell1">contents of first cell in row 2</div>
<div class="mycell cell2">contents of second cell in row 2</div>
</div>
</div>
In today's flexible designs, which use <div> for multiple purposes, it is wise to put some class on each div, to help refer to it. Here, what used to be <tr> in HTML became class myrow, and <td> became class mycell. This convention is what makes the above CSS selectors useful.
PERFORMANCE NOTE: putting class names on each cell, and using the above multi-class selectors, is better performance than using selectors ending with *, such as .row1 * or even .row1 > *. The reason is that selectors are matched last first, so when matching elements are being sought, .row1 * first does *, which matches all elements, and then checks all the ancestors of each element, to find if any ancestor has class row1. This might be slow in a complex document on a slow device. .row1 > * is better, because only the immediate parent is examined. But it is much better still to immediately eliminate most elements, via .row1 .cell1. (.row1 > .cell1 is an even tighter spec, but it is the first step of the search that makes the biggest difference, so it usually isn't worth the clutter, and the extra thought process as to whether it will always be a direct child, of adding the child selector >.)
The key point to take away re performance is that the last item in a selector should be as specific as possible, and should never be *.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "92"
} |
Q: Request for member which is of non-class I've got a C++ class I want to use which has all the code in the header file, rather than the CPP file. I'm trying to call it from an objective-C file which inherits a UIViewController class. I've renamed the file to .mm and imported the header file for the C++ file. When I compile, I keep getting a compile-time error when I try and access a method from the C++ class saying Request for member '<method>' in '<objectName>' which is of non-class type '<C++ class name>'. I did a search and it seemed that the header was usually the issue, but I've included the header in my file. What else could it be? (I can include generic code if required, but the I'm not sure if I'm allowed to show the actual code since it belongs to a third party).
A: The problem is likely in the declaration of the object that gives you the error, not in the header file. Sometimes the problem is hard to spot, you'll have to share some code if you can't figure it out by yourself.
A: I'm not a C++ coder, so this was probably an obvious mistake, but if anyone else comes across a similar problem, I simply changed my code from:
myObject.method();
to
myObject->method();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: User attributes not clearing? I'm have some trouble with my user model so I added this to it:
logout: () ->
console.log @toJSON()
@clear()
console.log @toJSON()
if @id?
alert @id
1st: console.log @toJSON()
Object
id: "4e862dc6e69aad002"
#other attributes
__proto__: Object
2nd: console.log @toJSON()
Object
__proto__: Object
But it still alerts the id.. why could this be?
A: so i dont have experience with backbone models but here is whats
happening
http://jsfiddle.net/
var Model = Backbone.Model.extend({
});
var x = new Model();
x.set({ "id": "hello world" });
alert(x.get("id"));
alert(x.id);
x.clear();
alert(x.id);
alert(x.get("id"));
Only the last one is returning undefined
so i asume that .get is the api witch it intends you to use.
I read the source code of backbone and it seams that id is special and thats the only "field"
that it actually puts directly on the object.. and the clear method dos not remove the old value from this.
This seams like a design flaw ... but an id should not change any way right????
I hope this helps Boom
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.