text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Embarrassing Inheritance Question Situation:
- I have a third party control that inherits from System.Windows.Controls.ItemsControl
- I have an instance of this control called foo
- foo has a ListCollectionView datasource with 5 items and no filter.
- foo.Items.Count gives a result of 0
- (System.Windows.Controls.ItemsControl)(foo)).Items.Count of 5
Where this happens:
- A XAML.cs file's constructor
When this happens:
- In the xaml.cs file's constructor
- After InitializeComponent
Unverified claims:
- The owner of the third party control claims that it does not override Items in any way.
Question:
- Why does foo.Items.Count return a different value than (System.Windows.Controls.ItemsControl)(foo)).Items.Count
A: It sounds like they have re-declared the property, i.e.
public new SomeContainer Items { get { ... } }
which is sometimes done to make the type of .Items (etc) more specific; it does, however, break inheritance, unless care is taken to override the underlying implementation. Re their claim - if the above is correct then indeed they aren't overriding it in any way; they are re-declaring it (it depends on how literal you are being with "override", perhaps).
But: you can check this in any reflection tool or IL inspection tool, simply by looking at how the property is declared. Does it have a new or newslot, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to add something to the index, commit it, then push the master branch to a named remote with dulwich? How can I add something to the index, as in
git add .
then
git commit -m "message"
then
git push origin master
using dulwich?
So far I've found this http://www.samba.org/~jelmer/dulwich/apidocs/dulwich.index.Index.html but it doesn't say much, does it?
Thanks
A: This is not a tested answer but it is closer on the push part:
# set wants to master
def wantmaster(haves, wants):
global repo
return { "refs/heads/master": repo.refs["HEAD"] }
client, src = dulwich.client.get_transport_and_path(origin_uri)
client.send_pack(src, wantmaster, repo.object_store.generate_pack_contents)
A variation on this is working in my code.
A: In this case, you don't want the index but the repo (of which the index is a part). http://www.samba.org/~jelmer/dulwich/apidocs/dulwich.repo.Repo.html
Something like this should work:
>>> from dulwich.repo import Repo
>>> x = Repo('.')
>>> x.stage(['a'])
>>> x.do_commit(message="foo")
'151915d47467696d2f9d18de6f61be7168682aeb'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Custom service contract attribute I'm looking to implement something similar to the way JSONP callbacks work with WCF in .NET 4. If you pass a callback parameter it wraps the response without callback needing to be in your method signature. What I want to do is have an attribute that switches the response format if a parameter named format is passed. I want it to not require the format parameter in the method signature.
Anyone have a starting point suggestion, doubts of possibility, tips?
A: You'll need a couple of components to implement the response wrapping. JSONP support was added to WCF on .NET Framework 4.0, before that there was a sample which showed how it can be implemented, so you can look at that to see what you need to do. You can find the sample at http://msdn.microsoft.com/en-us/library/cc716898.aspx.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AVPlayer, notification for play/pause state? I'm searching for a way to get notified the exact moment when AVPlayer starts playing. There's the "rate" property, but currently I am checking it periodically with an NSTimer to get updates.
I tried KVO, but apparently it's not KVO compliant.
I know that there are events when the player ENDED. But i'm talking about pause here.
I also KVO subscribed to AVPlayerItem's "status", but it's showing me when the HTTP asset has finished caching, no play/pause. I also started collecting all calls of play/pause, requesting an instant UI update afterwards, but it takes some more runloops before AVPlayer really starts playing. I'd just love to update my button instantly.
A: AVPalyer as default observer to track the current duration of the video ,when you pause or resume the video you can get paused time by using one global variable (inside observer update that variable)
CMTime interval = CMTimeMake(1, 1);
//The capture of self here is coming in with your implicit property access of self.currentduration - you can't refer to self or properties on self from within a block that will be strongly retained by self.
//You can get around this by creating a weak reference to self before accessing timerDisp inside your block
__weak typeof(self) weakSelf = self;
self.timeObserverToken = [_player addPeriodicTimeObserverForInterval:interval queue:NULL usingBlock: ^(CMTime time)
{
_currentDuration = (int)CMTimeGetSeconds (_player.currentTime);
if(!_isPlaying)
{
_pausedDuration = _currentDuration;
}
}
A: Why do you say that "rate" is not KVO complaint?
It works for me.
Here is what I did:
- (void)viewDidLoad
{
...
[self.player addObserver:self forKeyPath:@"rate" options:0 context:nil];
}
And then:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"rate"]) {
if ([self.player rate]) {
[self changeToPause]; // This changes the button to Pause
}
else {
[self changeToPlay]; // This changes the button to Play
}
}
}
A: If you're targeting iOS 13 and up, you can pull this off elegantly using Combine:
cancellable = myAVPlayerInstance.publisher(for: \.timeControlStatus)
.sink { [unowned self] status in
...
}
where status is any case of AVPlayer.TimeControlStatus
A: player = AVPlayer(url: URL(fileURLWithPath: path))
player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "rate" {
if player.rate > 0 {
print("video started")
}
}
}
in swift
A: For iOS 10 onwards You can check new property of AVPlayer timeControlStatus.
if(avPlayerObject.timeControlStatus==AVPlayerTimeControlStatusPaused)
{
//Paused mode
}
else if(avPlayerObject.timeControlStatus==AVPlayerTimeControlStatusPlaying)
{
//Play mode
}
A: Add an observer to your AVPlayer object's rate value:
player.addObserver(self, forKeyPath: "rate", options: [], context: nil)
And override the method that will be called when the rate changes:
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "rate", let player = object as? AVPlayer {
if player.rate == 1 {
print("Playing")
} else {
print("Paused")
}
}
}
A: Need to add an observer to AVPlayer object's rate value:
player?.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)
Override below method to observe changes in rate property
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "rate" {
if let status = player?.timeControlStatus {
switch status{
case .paused:
//Paused mode
print("paused")
case .waitingToPlayAtSpecifiedRate:
//Resumed
print("resumed")
case .playing:
//Video Ended
print("ended")
@unknown default:
print("For future versions")
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
}
|
Q: 000webhost, PHP, and LoadVars AS2 I am using AS2 to download and upload data from an HTTP server using some PHP on the other end. The upload works great, but I ran into a little issue with the download, since the webhost that I am using appends a little HTML comment to the end of every file. My PHP works great, but this little HTML comment destroys the whole LoadVars variable string. For example:
&coins=211108&xp=751029&credits=5&blah=p
<!-- www.000webhost.com Analytics Code -->
<script type="text/javascript" src="http://analytics.hosting24.com/count.php"></script>
<noscript><a href="http://www.hosting24.com/"><img src="http://analytics.hosting24.com/count.php" alt="web hosting" /></a></noscript>
<!-- End Of Analytics Code -->
I was wondering if anyone could think of a workaround since I personally have been trying to brainstorm and search for one for a while and couldn't. If worst comes to worst, I guess I can always either get a new webhost or host it myself.
A: You can disable analytics for 000webhost, read here:
http://www.000webhost.com/forum/announcements/2160-disabling-analytics-code.html
A: You could talk to them and ask them not to add it to such requests.
Or you could make your Actionscript ignore everything after a line break (but AFAIK, you'd have to write your own LoadVars() for that.
Other than that, I think you're out of luck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: FTP XML file using FileZilla = malformed tag on receiving end? When sending an XML file to our FTP via FileZilla it appears somewhere in the transfer 1 or 2 of the XML tags are being malformed.
Our client has confirmed on their end that prior to the upload the file is solid and does not have any malformed tags.
Yet on the receiving end when we review the file there are malformed tags. Not missing tags, but tags that have been broken into two lines. The tags (only 1 or 2 total for each file) are random and I'm not seeing any similarities in where the malformations occur.
For example:
<customerNumber>blah blah blah</custome
erNumber>
I'm just looking for any guidance or suggestions seeing that my google searches are coming up empty.
Thanks for your help.
A: I would recommend making sure that you know whether or not your transferring in Binary mode or ASCII mode. Also, is Filezilla using z-mode compression or not? Also, are you sure that the format of your XML is as you would expect: for example, does your XML have a BOM and is it UTF-8 or UTF-16 or ANSI?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android - how to position this custom balloon view with RelativeLayout Im stuck in getting this to work.
Look at the picture below, i want the bubble to be placed under the image.
And of course would like to be able to place the view wherever i like.
I think the problem is in the parent view so i add parent xml to .
Maybe i need to change RelativeLayout to something else,
I have tried many things but nothing works
.
Here is my xml for the bubble
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:id="@+id/frameLayout_balloon_gallery_activity_send"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView android:id="@+id/imv_balloon_gallery_activity_send"
android:src="@drawable/balloon_gallery"
android:scaleType="fitCenter"
android:layout_height="fill_parent"
android:layout_width="fill_parent"/>
</FrameLayout >
here is the parent that i insert the bubble into
.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/relativelayout_main_activity_back"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gallery_activity_back"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:spacing="2dip"
android:gravity="top"
android:paddingTop="20dip"
/>
<RelativeLayout
android:id="@+id/relativeLayoutinner_activity_back"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<EditText
android:id="@+id/etx_addtext_activity_back"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="false"
android:text="@string/string_enter_text_here"
/>
</RelativeLayout>
</RelativeLayout>
A: You will want to create a RelativeLayout that contains both the ImageView and the bubble inside it. Position the bubble below the ImageView using the position below attribute. From there you can move the RelativeLayout around wherever and the bubble will remain under the image.
A: Check out how the Quick Actions were implemented here http://www.londatiga.net/it/how-to-create-quickaction-dialog-in-android/. The functionality is similar to what you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Unable to sort datagridview Hello i cannot sort alphabetical my datagridview
this is how i fill my grid :
bs = new BindingSource();
bs.DataSource = db.GetProducts.ToList();
dgvInventory.DataSource = bs;
and this is how i try to sort my grid :
private void toolStripButton3_Click_1(object sender, EventArgs e)
{
bs.Sort = "ID DESC, Name ASC";
dgvInventory.DataSource = bs;
}
And when i pressing button nothing happens
This two columns is exsist in data grid
and this is screen :
A: Quoting from: http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.sort.aspx
To support sorting, the underlying list must implement the
IBindingList or IBindingListView interfaces. This capability can be
queried through the SupportsSorting property. Multicolumn sorting is
available when the SupportsAdvancedSorting property is true.
You're calling the ToList() extension method which is going to return you a List<Product> which is not going to support either of those interfaces and hence won't be sortable.
A: When You have custom objects, You have to implement SortableBindingList. Do a search on the Internet for this. The reason for such behaviour is that underlying source is responsible for sorting, not DataGridView.
Also, the same question here: DataGridView Sort does not work
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Keeping COM Interop in mind, are there any pitfalls in returning objects vs value types in .Net? This question comes to mind when I consider using C++ to subscribe to a Library. I don't have enough of an understanding of COM to make an educated guess at this point. But if I wanted to keep my code open for COM in the future (which is look more and more the case), I feel it would be safer to return value types than to return objects. The downside is a would have to write a method/property for field item I want to expose. Is this an unsubstantiated fear of mine? If not, what do I need to consider to keeping my code COM frienldy in .Net when mingling with C++. Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Detecting iOS Version on a Web Page Is there any way (using Javascript, PHP, etc) to detect the version of an iOS page, when the page is visited on MobileSafari?
A: Here's a bit of JS to determine iOS and Android OS version.
Tested with actual user agent strings for iOS 4.3 to 6.0.1, and Android 2.3.4 to 4.2
var userOS; // will either be iOS, Android or unknown
var userOSver; // this is a string, use Number(userOSver) to convert
function getOS( )
{
var ua = navigator.userAgent;
var uaindex;
// determine OS
if ( ua.match(/iPad/i) || ua.match(/iPhone/i) )
{
userOS = 'iOS';
uaindex = ua.indexOf( 'OS ' );
}
else if ( ua.match(/Android/i) )
{
userOS = 'Android';
uaindex = ua.indexOf( 'Android ' );
}
else
{
userOS = 'unknown';
}
// determine version
if ( userOS === 'iOS' && uaindex > -1 )
{
userOSver = ua.substr( uaindex + 3, 3 ).replace( '_', '.' );
}
else if ( userOS === 'Android' && uaindex > -1 )
{
userOSver = ua.substr( uaindex + 8, 3 );
}
else
{
userOSver = 'unknown';
}
}
Then to detect a specific version and higher, try:
if ( userOS === 'iOS' && Number( userOSver.charAt(0) ) >= 5 ) { ... }
A: You should be able to parse the UserAgent String for it.
Here's an example User Agent String that declares the OS to be 4.3.1
Mozilla/5.0 (iPad; U; CPU OS 4_3_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8G4 Safari/6533.18.5
A: PHP
function ismobilesafari() {
if( preg_match( '/(iPod|iPhone|iPad)/', $_SERVER[ 'HTTP_USER_AGENT' ] ) ) {
return true;
} else {
return false;
}
}
JS
function ismobilesafari() {
if( navigator.userAgent.match( /(iPod|iPhone|iPad)/ ) ) {
return true
} else {
return false
}
}
Referenced by: http://alan.edward.es/posts/detecting-the-awesomeness-that-is-mobile-safari/
A: You really would be checking the version of the browser which can tell you what is supported or not. There's an article here that gives some decent information on how to detect this and determine what it supports.
http://www.mobilexweb.com/blog/iphone4-ios4-detection-safari-viewport
A: You'll have to interrogate the $_SERVER['HTTP_USER_AGENT'] value in PHP (or its equivalent in JavaScript) and parse it. I would build a helper method that parses and decodes the user agent and returns the iOS device and version that is visiting your site/app.
The reference material you need is online over at Apple. Take a look at the "Using the Safari User Agent String" section.
A: You should not only detect if its an iOS device but also if the device runs on at least iOS 2.0. Because since 2.0 mulittouch and other important features are supported. A reference of features is on wikipedia.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Mechanize you different ip I'm playing around with mechanize on a website that appears differently based on your ip.
Is there a way to change you ip in mechanize?
I've tried:
br.set_proxies({"http": '127.0.0.1:80'})
but that timesout. Is there something else I'm supposed to do to make this work?
A: no, I do not believe this is possible. IP address is set on outgoing packets by your network stack, outside of mechanize's control.
A: You can use tor with menchanize it will allowed you tu use different IP and anonymous.
import socks
import socket
def create_connection(address, timeout=None, source_address=None):
sock = socks.socksocket()
sock.connect(address)
return sock
And This code before create the browser of mechanize
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
socket.create_connection = create_connection
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Can Java be run without a Java Virtual Machine? Sorry for the stupid question, I'm just beginning to learn Java. Can it be compiled into a .exe to be run on another computer, or is it only for computers with a JVM?
A: Not exactly. You can bundle a JRE with your executable, which is kind of like the same thing. Embedding a JRE is one approach offered by launch4j.
There are third party projects that will allow you to do this. A free one is http://gcc.gnu.org/java/ . I don't believe it's officially supported by Java though, but it's also gnu, who happen to know a thing or two about compilers.
There is also http://www.excelsior-usa.com/jet.html which is a paid product, but supports up to Java 6.
A: Can you make candy without sugar?
Yes, you need to have a JVM (just the executing for compiling) to run and to compile.
Although, it is not necessary when trying to write just the code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: webviewglue nativedestroy view I am opening the browser at a page from my app, the code for opening the browser is one I have used many times, but in this particular case, the browser never opens.
I keep getting the following messages at the end in logcat:
09-27 15:41:16.624: INFO/ActivityManager(1644): Starting: Intent { act=android.intent.action.VIEW dat=http://www.nyt.com cmp=com.android.browser/.BrowserActivity } from pid 9332
09-27 15:41:16.634: WARN/ActivityManager(1644): Duplicate finish request for HistoryRecord{4097ec10 com.test/com.test.MainScreen}
09-27 15:41:16.684: VERBOSE/http(4606): 15326478 main RequestQueue.resetWifiProxy, wifiProxy is null
09-27 15:41:16.684: ERROR/http(4606): RequestQueue.setProxyConfig, wifiProxy is null
09-27 15:41:16.784: DEBUG/webviewglue(4606): nativeDestroy view: 0x562af8
This is a part of a huge app with a native library.
This is the snippet that opens the browser:
String afterSubmitAction = "http://www.nyt.com";
Uri uri = Uri.parse(afterSubmitAction);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
finish();
A: Your code is working fine at my side.So please check your internet connection.Please run your code on Edge if you are using wifi to check what cause this problem.
A: I don't know how to add a comment to your post..
What happens if you comment out the finish(); ?
If the Browser doesn't close, then it's was because you finished the parent activity.
Try this?
String afterSubmitAction = "http://www.nyt.com";
Uri uri = Uri.parse(afterSubmitAction);
Intent i = new Intent(Intent.ACTION_VIEW, uri);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
}
|
Q: batch html file editing I have a collection of one thousand HTML files and need to somewhat trim them. I need to delete all the tags inside <body></body> area of those except for one, <div.pg>, to make them clean to be printed. the excess are navigation links which make the prints messy and make the pages occupy more paper. the contents are not the same so I can't find and replace the code excerpt but the tags are the same foe example there are 3 <table> tags to be deleted each with specific class. manipulate specific tags inside batch HTML files?
Any batch processing technique or software to do this job?
What an easy solution on windows?
A: I would use an xslt transform on each html page you have. Batch is not the tool to manipulate html files. You can use batch as a "manager" to pass the required file to the xsl transform. Also windows have a rudimentary msxml utility which you can download and install to your machine : http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=21714
That's how I would do it. I am sure there are more options.
A: If it is XHTML you could use XSLT to transform your HTML to "another" format. Look for example here: http://www.w3schools.com/xsl/ or here: http://help.hannonhill.com/discussions/how-do-i/269-strip-specific-html-tag-in-xslt
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Which Cocoa control to use to display drill-down table? Any idea which Cocoa control to use to display the drill-down table as in attached screenshot? On the left panel is a list of items. When an item is selected, the detail of the item is displayed on the right panel. Is it NSOutlineView or NSBrowser? Thanks!
Screenshot http://s1.proxy03.twitpic.com/photos/large/409079140.png
Link to twitpic page
A: It's an NSTableView on the left, and most likely an NSTextView on the right. The NSTableView on the left most likely has an NSDateFormatter set for the cell in the third column, which handles converting an NSDate object into the NSString value that's shown.
See Table View Programming Guide for more general info on NSTableViews. There is also NSOutlineView, which is a subclass of NSTableView, for when you need to display a data tree. Implementing a table view is much easier than an outline view or NSBrowser, so only go with an outline view if you really need to.
A: NSOutlineView will produce something like the left panel, but is probably overkill judging by your screenshot.
NSBrowser would give you a Finder-style drill down.
I would personally use two views - an NSTableView on the left and an NSTextView on the right.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iOS rotating MKAnnotationView in response of MKMapView rotation In my application I have a MKMapView where several annotations are shown. The map rotates based on the heading of the device. To rotate the map the following statement is performed (called by the method locationManager: didUpdateHeading:)
self.navigationMapView.mapView.transform = CGAffineTransformMakeRotation(-heading);
where the heading (magnetic) is expressed in radians. What I noticed it's that even the annotations in the map rotate and I don't want it. I tried to fix it in the following method:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
static NSString *identifier = @"AnnotationViewIdentifier";
MKAnnotationView *av = [mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if (av == nil) {
av = [[[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:identifier] autorelease];
}
else{
av.annotation = annotation;
}
av.transform = CGAffineTransformMakeRotation(degreesToRadians(self.arController.currentHeading.magneticHeading));
av.canShowCallout = YES;
return av;
}
and I want to call this method from "didUpdateHeading:" but I really don't know how to do it. The TableView class has the reloadData function that calls the delegate method but here the things seem different. Any suggestions?!
Another question, my annotations on the map show the distance from the user, I would like to update them (distance label) as soon as the user change location. Any suggestions?!
A: So with a MKMapView having that be called properly is a little bit annoying. Essentially you have one of two options. Option 1: Create an array of the annotation on the screen and remove that from the map_view and then re-add them to the map_view. Essentially creating your own reload data function. Option 2: Do something simple such as
CGLocationCoordinate2D coordinate = map_view.center;
map_view.center = coordinate;
-- Essentially the point is to reset a property of the map causing it to redraw. However this option is not always going to work. Option 1 has a higher chance of working however that one can also fail, so if simply taking the annotations off and re-adding them causes nothing to happen then simply decreate the map and then recreate the map at the end of your map refresh function something like.
[my_map_view removeFromSuperView];
[my_map_view release];
my_map_view = nil;
my_map_view = [[MKMapView alloc] initWithFrame:CGRectMake(0,0,320,480)];
one of these options should work. I had to do option one for my solution however I know some people are lucky and option 2 works just as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to run javascript during ajax call? While developing a web app where I'm making great use of javascript php and ajax.
I want to call
display_terminal('feedback_viewer','logs/init-raid-log.txt','Init-Raid');
to build my terminal and call feed_terminal() which has its own setTimeout() recursion call
var url='../edit_initRaid.php';
status_text('Initializing raid-array. Please wait a moment...');
var xmldoc=ajaxPHP2(url,2);
a php file that does nothing more that
exec("sudo /usr/bin/./init-raid-drives-web.sh");
and this is where I fail. This next line is not executed until after the exec() in the php file returns to the php file and the php file returns to the javascript. Not that it matters, but I am pretty sure it did not used to be this way, as originally the bash script would execute over a time period of 2 minutes and the javascript would successfully be updating the html with feed_terminal. this is not the case anymore.
alert("javascript has returned from ajax call");
if (xmldoc) {
status_text('Raid-array initialized successfully. System will now restart.You must re-login to FDAS-Web.');
Below is a bunch of code for your questions
Ultimately my question is, how can I run javascript DURING the ajax call?
Or maybe my question should be, how can I have edit_initRaid return an xmldoc, without waiting for the exec() to return, or how can i have the exec() return even without the script completing?
function initRaidArray(){
if (document.getElementById('initRaid_doubleCheck')){
if (document.getElementById('initRaidHideButtonSpot'))
document.getElementById('initRaidHideButtonSpot').innerHTML = '';
var spot=document.getElementById('initRaid_doubleCheck');
spot.innerHTML='';
spot.innerHTML='This may take a few moments. Please wait.';
}
display_terminal('feedback_viewer','logs/init-raid-log.txt','Init-Raid');
var url='../edit_initRaid.php';
status_text('Initializing raid-array. Please wait a moment...');
var xmldoc=ajaxPHP2(url,2);
alert("javascript has returned from ajax call");
if (xmldoc) {
status_text('Raid-array initialized successfully. System will now restart. You must re-login to FDAS-Web.');
}
}
where display_terminal() does two things, builds a table and appends it to the page, and calls feed_terminal(logfile,bigDiv,0)
function feed_terminal(logFile,bigD,lap){
// AJAX
bigD.innerHTML = '';
var url='../view_xml_text.php';
/*
* lap(0)=clear file , lap(1)=do not clear file
*/
url+='?logFile='+logFile+'&lap='+lap;
var XMLdoc=ajaxPHP2(url,2);
var xmlrows = XMLdoc.getElementsByTagName("line");
alert("xmlrows.length=="+xmlrows.length);
// empty file
if (xmlrows.length==0){
var d = document.createElement('div');
var s = document.createElement('span');
s.innerHTML='...';
d.appendChild(s);
bigD.appendChild(d);
} else {
// Parse XML
for (var i=0;i<xmlrows.length;i++){
if (xmlrows[i].childNodes[0]){
if (xmlrows[i].childNodes[0].nodeValue){
var d = document.createElement('div');
var s = document.createElement('span');
s.innerHTML=xmlrows[i].childNodes[0].nodeValue;
d.appendChild(s);
bigD.appendChild(d);
}
}
}
}
setTimeout(function(){feed_terminal(logFile,bigD,1)},2000);
}
where the most important item is the setTimeout() call to continue reaching out to the php file which returns xml of the lines in the file, simply.
function ajaxPHP2(url,key)
{
if (window.XMLHttpRequest) {
xml_HTTP=new XMLHttpRequest();
if (xml_HTTP.overrideMimeType) {xml_HTTP.overrideMimeType('text/xml');}
} else { xml_HTTP=new ActiveXObject("Microsoft.xml_HTTP"); }
xml_HTTP.open("GET",url,false);
xml_HTTP.send(null);
if (key){return xml_HTTP.responseXML;}
}
A: You need to tell Javascript to do your XHR call asynchronously.
Change
xml_HTTP.open("GET",url,false);
to
xml_HTTP.open("GET",url,true);
But first, you'll need to tell it to do something when the request completes (a callback):
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
One recommendation: XHR is a pain. It would be a lot easier to use something like jQuery's $.ajax()
A: You need to set your ajax call to be asynchronous. In the ajaxPHP2 function, the line xml_HTTP.open("GET", url, false); is what is causing the page to pause. The false parameter is telling the ajax call to make everything else wait for it. Change the false to true so it looks like this:
xml_HTTP.open("GET", url, true);
You may also need to attach a function to the onreadystatechange property so that when the ajax call returns it knows what to do. See these links for more information.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Video blacked out in screenshot of UIWebView I am having trouble capturing a screenshot of a UIWebView while it plays a video file.
I can capture when the video file is not playing and it is perfect but when the video file is playing in UIWebView, if I take a screenshot the video area is black and shows a QuickTime logo.
Can any body help me on this? I am totally frustrated. Any kind of help or suggestion is highly appreciated.
Thanks in Advance.
A: Sorry, I don't think this is possible. It's a form of copyright protection either in the codec or the video library.
A: So I did a little researching and maybe this is the way you are doing it however I would suggest maybe
UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
And maybe this is causing your video to go black, I am not a hundred percent sure however I would suggest maybe refreshing the web page if you take a screen shot inside of your application? It might look junker though depending on why the screen shot is being taken. Anyways hope this helps:)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to determine if the relationships in an entity collection have been saved to the database I have a situation where I'm adding existing entities to an entity collection. Before calling "context.SaveChanges()", I need to know which entities in the entity collection have not had their relationship saved in the database. There's no point in checking the "EntityState" property of each entity in the collection because they are all "Unchanged" (remember, the entities already exist in the database). I should mention that the type of relationship is "many-to-many"...basically, I want to know if a row has been added to the "many-to-many" relationship table.
A: I'm not aware of a way to accomplish just that what you ask, but it may be of help - you can see which entities have been changed by inspecting contents of DBContext.ChangeTracker.Entries(), where every entry has reference to the changed entity object.
This collection should contain all new/modified/deleted records in any, including your many-to-many relationship table.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is there a way to create a null value for .NET outside C#? I am using the .NET support in a 3rd party imaging application where it allows one to use .NET assemblies. The only catch is you have to call/create things using the fully qualified name, for instance:
NewDotNetObject "System.Object";
NewDotNetObject "System.Drawing.Color" 1 2 3;
(NewDotNetMethodCall "System.Math").Abs -45;
...
I am trying to use a method where I need to pass a null value. But I don't know the fully qualified name for null.
Can a null value be created this way?
A: Don't know if that is the right for you, but there is System.DBNull which represents no data.
Or can you use null pointers?
System.IntPtr.Zero
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: php make post request with header Using php, i need to call a webservice, passing in specific data in the HTTP header, and specific data in the actual POST string. However, when ever i access this page, the page attempts to download. If I open the downloaded file, it contains only my two !'s. From what I understand, a response should be sent back.
Am I correctly "sending" the headers to the url defined below, or should i be doing it differently?
Thanks!
<?php
header("Content-Type: application/x-www-form-urlencoded");
header("Content-Length: ---");
header("Authorization: Basic -------");
try{
$xml = "------";
$url = 'https://---.com/---/---?site_id=---&service_name=---';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo "!" . $response . "!";
} catch (Exception $e) {
print_r($e);
}
?>
A: No. The PHP header() call will issue headers that affect the connection between the web server and YOUR browser. it does not in any way affect the connection the server is creating with curl.
By default, curl will automatically fill in the appropriate content-type headers when you tell it to do a POST, and is smart enough to change the content type if you're doing a file upload as well. To specify the login credentials, use CURLOPT_USERPWD (see http://php.net/curl_setopt for details).
A: It looks like it's a https issue which might be solved through:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
Cheers!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Speed up DISTINCT query in MySQL I have a InnoDB MYSQL table that stores a multi select name ( or 'code' as the table calls it), a parent object's id (parent_id) and the name of the option selected in the multi select (name_id):
CREATE TABLE IF NOT EXISTS `v2_CA_venue_option_map` (
`map_id` int(11) NOT NULL auto_increment,
`code` varchar(30) NOT NULL,
`parent_id` int(11) NOT NULL,
`name_id` int(11) NOT NULL,
PRIMARY KEY (`map_id`),
UNIQUE KEY `3way_unique` (`code`,`parent_id`,`name_id`),
KEY `name_id` (`name_id`),
KEY `filter` (`code`,`name_id`),
KEY `parent_id` (`parent_id`),
KEY `code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=875156 ;
and a simple table to store the names (i figured i would show this because its used in the query):
CREATE TABLE IF NOT EXISTS `v2_CA_venue_option_name` (
`name_id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`name_id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Venue Option Names' AUTO_INCREMENT=60 ;
That I would like to optimize for the following query:
SELECT DISTINCT name_id, name
FROM `v2_CA_venue_option_map`
JOIN `v2_CA_venue_option_name`
USING (name_id)
WHERE code = "a_event_types"
This query takes about 600ms to execute and I was wondering:
*
*If I could place an index on the table to speed up this distinct query.
*How could I get the same result with better performance.
Here is an explain of the above query.
UPDATE, I removed my second question.
UPDATE, It seems that the best way to speed this up would be to store the output in a separate table once and make the calls to that table from then on, as this table just can't perform the query quick enough for my needs and indexes don't seem to help for this DISTINCT query.
A: Try a lazy group by instead of distinct, it's one less column mysql has to worry about.
SELECT name_id, name
FROM `v2_CA_venue_option_map`
JOIN `v2_CA_venue_option_name`
USING (name_id)
WHERE code = "a_event_types"
GROUP BY name_id
A: You can try changing the query from a join to a semi-join, using EXISTS. No need for DISTINCT:
SELECT name_id
, name
FROM v2_CA_venue_option_name AS n
WHERE EXISTS
( SELECT *
FROM v2_CA_venue_option_map AS m
WHERE m.name_id = n.name_id
AND m.code = 'a_event_types'
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: When to use Nhibernate ? I was looking at ayende blog http://ayende.com/blog/3946/nhibernate-mapping-concurrency about NHibernate concurrency and i still not very clear when to use . It seems like it is a solution to solve StaleObjectException.
Can anyone explain to me in what scenario you will use a and why ?
Thanks.
A: NHibernate Version is used when you want to implement Optimistic concurrency control. Without enabling Optimistic concurrency control and locking your application will use "Last commit wins" strategy. Your users may experience lost updates if two transactions are modifying the same object at roughly the same time. The more appropriate strategy is called "First commit wins". In this scenario second transaction will fail with an error that would say something like: Somebody already committed
modifications to the data you’re about to commit. You’ve been working with stale
data. Please restart the conversation with fresh data.
From Java Persistence with Hibernate:
Hibernate provides automatic versioning. Each entity instance has a
version, which can be a number or a timestamp. Hibernate increments an
object’s version when it’s modified, compares versions automatically,
and throws an exception if a conflict is detected. Consequently, you
add this version property to all your persistent entity classes to
enable optimistic locking. ... The version number is just a counter value—it doesn’t have any useful semantic
value. The additional column on the entity table is used by your Hibernate application.
Keep in mind that all other applications that access the same database can
(and probably should) also implement optimistic versioning and utilize the same
version column.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: how do I iterate through internal properties in c# public class TestClass
{
public string property1 { get; set; }
public string property2 { get; set; }
internal string property3 { get; set; }
internal string property4 { get; set; }
internal string property5 { get; set; }
}
I can iterate through the properties with the following loop, but it only shows public properties. I need all the properties.
foreach (PropertyInfo property in typeof(TestClass).GetProperties())
{
//do something
}
A: You need to specify that you don't just need the public properties, using the overload accepting BindingFlags:
foreach (PropertyInfo property in typeof(TestClass)
.GetProperties(BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public))
{
//do something
}
Add BindingFlags.Static if you want to include static properties.
The parameterless overload only returns public properties.
A: According to MSDN, private and internal are not recognized in Reflection API.
To identify an internal method using Reflection, use the IsAssembly
property. To identify a protected internal method, use the
IsFamilyOrAssembly.
If You are writing some test units You might want to take a look at InternalsVisibleTo attribute. It allows you to specify which assembly can see internal properties.
And finally, do You really need to have internal properties...
A: Use BindingFlags
foreach (PropertyInfo property in typeof(TestClass)
.GetProperties(
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance))
{
//do something
}
A: by specifying what bindingflags in GetProperties:
foreach (PropertyInfo property in typeof(TestClass).GetProperties(
BindingFlags.Instance|
BindingFlags.Public|
BindingFlags.NonPublic))
A: You get the internal properties of a type by querying the NonPublic properties and then filtering the Get methods of these by "IsAssembly".
"internal protected" properties have their getters marked as "IsFamilyOrAssembly", "protected" properties as "IsFamily", and
"private" properties as marked with "IsPrivate":
public class TestClass
{
public string Property1 { get; set; }
private string Property2 { get; set; }
public string Property9 { get; set; }
private string Property10 { get; set; }
protected internal string Property3 { get; set; }
protected string Property4 { get; set; }
internal string Property5 { get; set; }
protected internal int Property6 { get; set; }
protected int Property7 { get; set; }
internal int Property8 { get; set; }
internal static void ShowPropertyAccessScope(Type t)
{
foreach (var prop in t.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
Console.WriteLine("{0,-28} {1,15}", "Public property:", prop.Name);
}
var nonPublic = t.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic);
foreach (var prop in nonPublic.Where(p => p.GetGetMethod(true)?.IsAssembly == true))
{
Console.WriteLine("{0,-28} {1,15}", "Internal property:", prop.Name);
}
foreach (var prop in nonPublic.Where(p => p.GetGetMethod(true)?.IsFamilyOrAssembly == true))
{
Console.WriteLine("{0,-28} {1,15}", "Internal protected property:", prop.Name);
}
foreach (var prop in nonPublic.Where(p => p.GetGetMethod(true)?.IsFamily == true))
{
Console.WriteLine("{0,-28} {1,15}", "Protected property:", prop.Name);
}
foreach (var prop in nonPublic.Where(p => p.GetGetMethod(true)?.IsPrivate == true))
{
Console.WriteLine("{0,-28} {1,15}", "Private property:", prop.Name);
}
}
static void Main()
{
ShowPropertyAccessScope(typeof(TestClass));
}
}
A: You need to change the BindingFlags on your call to Type.GetProperties
Try:
var instanceProperties = typeof(TestClass).GetProperties(
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance
);
foreach(var instanceProperty in instanceProperties) {
// a little something something for the instanceProperty
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
}
|
Q: How does JavaScript handle AJAX responses in the background? Since JavaScript runs in a single thread, after an AJAX request is made, what actually happens in the background? I would like to get a deeper insight into this, can anyone shed some light?
A: Below the covers, javascript has an event queue. Each time a javascript thread of execution finishes, it checks to see if there is another event in the queue to process. If there is, it pulls it off the queue and triggers that event (like a mouse click, for example).
The native code networking that lies under the ajax call will know when the ajax response is done and an event will get added to the javascript event queue. How the native code knows when the ajax call is done depends upon the implementation. It may be implemented with threads or it may also be event driven itself (it doesn't really matter). The point of the implementation is that when the ajax response is done, some native code will know it's done and put an event into the JS queue.
If no Javascript is running at the time, the event will be immediately triggered which will run the ajax response handler. If something is running at the time, then the event will get processed when the current javascript thread of execution finishes. There doesn't need to be any polling by the javascript engine. When a piece of Javascript finishes executing, the JS engine just checks the event queue to see if there is anything else that needs to run. If so, it pops the next event off the queue and executes it (calling one or more callback functions that are registered for that event). If nothing is in the event queue, then the JS interpreter has free time (garbage collection or idle) until some external agent puts something else in the event queue and wakes it up again.
Because all outside events go through the event queue and no event is ever triggered while javascript is actually running something else, it stays single threaded.
Here are some articles on the details:
*
*How Javascript Timers Work - written by John Resig
*Events and Timing in Depth
*W3 spec: HTML5 event loops
*MDN article on Event Loop
*Presentation on JS event queue
*The JavaScript Event Loop: Explained
*Five Patterns to Help Tame Asynchronous Javascript
*Javascript Event Loop Presentation
*Video Discussing How Javascript Works (including event loop at 10:27)
A: I want to elaborate a bit, regarding the ajax Implementation mentioned in answers.
Although (regular) Javascript execution is not multi-threaded - as noted well in the above answers - however,
the real handling of the AJAX responses (as well as the request handling) is not Javascript, and it - usually - is multi-threaded. (see chromium source implementation of XMLHttpRequest which we'll discus above)
and I'll explain, let's take the following code:
var xhr = new XMLHttpRequest();
var t = Date.now;
xhr.open( "GET", "https://swx.cdn.skype.com/shared/v/1.2.15/SkypeBootstrap.min.js?v="+t(), true );
xhr.onload = function( e ) {
console.log(t() + ': step 3');
alert(this.response.substr(0,20));
};
console.log(t() + ': step 1');
xhr.send();
console.log(t() + ': step 2');
after an AJAX request is made (- after step 1),
then while your js code proceeds executing (step 2 and after), the browser starts the real work of: 1. formatting a tcp request 2. opening a socket 3. sending headers 4. handshaking 5. sending body 6. waiting response 7. reading headers 8. reading body etc. all of this implementation is usually run's in a different thread in parallel to your js code execution. for an example, chromium implementation mentioned uses ThreadableLoader go digg-into , (you can also get some impression by looking at network tab of a page load, you'll see some simultaneous requests).
in conclusion, I would say that - at least - most of your I/O operations can be made simultaneously/async (and you can take advantage of this using an await for example). but all interaction with those operations (the issuing, the js callback execution) are all synchronous.
A: You can find here a very complete documentation on events handling in javascript.
It is written by a guy working on the javascript implementation in the Opera Browser.
More precisely, look at the titles: "Event Flow", "Event Queuing" and "Non-user Events": you'll learn that:
*
*Javascript runs in a single thread for each browser tab or window.
*Events are queued and executed sequentially.
*XMLHttpRequest are run by the implementation and callbacks are run using the event queue.
Note: Original link was: link, but is now dead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "147"
}
|
Q: Problem implementing a 2 levels association using rails3-amf I'm using https://github.com/warhammerkid/rails3-amf , and can't implement a two level association as follows:
@posts = Post.where(:category_id => params[:id]).includes(:author => :phones)
respond_with(@posts) do |format|
format.amf { render :amf => @posts.to_amf( :include => ???? ) }
end
Any sugestions?
A: rails3-amf is deprecated. Look here:
https://github.com/rubyamf/rubyamf
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Custom Chart in SSRS Report I am currently working on a peiece of report which has a graph/chart. The interval of X-axis needs to be increasing. That means we need to have dynamic intervals. I am just wondering whether there is a solution to it. The report needs to be ran at dynamic CRM, so it needs to be a SSRS report. I feel like it is quite a big challenge for me and I think it is beyond my knowledge. Is it achievable? I knew there is custom code section in the report that I can use. Can I draw charts using visual basic, then print it out in the report?
As I am new here, I won't be able to
Thank you very much
A: I may be missing something, but this is pretty easy: create your chart, and then right click on the X axis labels and select "Horizontal Axis Properties..." In the resulting dialog you can specify the "Interval" Click on the function button ("fx") and you can enter a formula using data from your datasets or parameters.
A valid formula might be:
=IIF(Parameters!View.Value = "By Day", 24 , 168)
On rereading your question, I think you might be asking if the groupings of data can be dynamic. Yes, certainly, but I think I would probably do that in the query, with appropriate SQL aggregates.
A: I had to use custom assembly to draw the whole graph/chart in the end. Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Are there any document window focus events? This one has been a bit of a pain due to a similarly named feature in Visual Studio (which I won't mention here for the sake of people searching).
What I'd like to do is to listen to events regarding which document window has focus
I wish my extension to behave differently depending which SolutionItem is open and has focus. I'd assume there is an event somewhere which will inform me when this focus changes.
I've found where I can listen to when a document opens and closes, but not when a document window has focus.
A: It depends on if you're interested in window events or hierarchy/project selection events.
For Window events (i.e. document/tool window changes in focus), use IVsWindowFrameNotify3.
For Hierarchy/Project item selection change events, check out IVsMonitorSelection.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Call hidden div with onclick I have a div for a button which I want to click and replace the contents on the page with a hidden div. Keep in mind this works without the onclick function (flashes the first div, then goes straight to 2nd) but when I add onclick it doesn't work.
<div id="next" class="button" name="somename"></div>
<script>
$("next").click(function () {
$('#div1').fadeOut('medium',function(){$('#div2').fadeIn('medium');}
});
</script>
The button class has some css properties and an image to be used as a button.
A: What you're doing is just adding a onclick handler to the div in question. You're not actually triggering that click. For that, you'd need a simple $('#next').click();, or $('#next').trigger('click');
A: If "next" is an ID then you need $("#next").click
You also need a second div (assumed you have it)
The onclick should not be necessary.
A: You are not referencing the div correctly in jQuery- you forgot the # to reference the id.
$("next").click(function () { ... }
should be
$("#next").click(function () { ... }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: xcdatamodel Contents Disappears I've had this happen a few times.
The contents of proj.xcdatamodeld/proj.xcdatamodel/ randomly disappear off my hard drive. However, Xcode will open the model file just fine.
Sometimes all three files disappear (elements, layout, contents). Other times only a subset of the files disappear.
I've done a filesystem check with Disk Utility which detected no problems.
I've checked that all the build settings etc. for the xcdatamodel are correct.
A: Are you perhaps confusing *.xcdatamodel and *.xcdatamodeld?
What's the problem if everything works?
A: I believe I've figured out what the problem is.
The core data file is incompatible across Snow Leopard Xcode 4.0 and Lion Xcode 4.1.
Edit: You can fix this problem by clicking on .xcdatamodel, and in the right-hand panel under "Tools Version" minimum set it to "Xcode 3.2".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: can you host a private repository for your organization to use with npm? Npm sounds like a great platform to use within an organization, curious if a private repo is possible, like with Nexus/Maven. Nothing comes up on Google :(
A: There is an easy to use npm package to do this.
https://www.npmjs.org/package/sinopia
In a nutshell, Sinopia is a private/caching npm repository server that you can setup with zero configuration.
Sinopia can be used to :
*
*publish own private packages without exposing it to the public
*cache only public packages that are used (there is no need to have to replicate the whole public registery)
*override public packages with a modified version that have been produced internally.
A: Forgive me if I don't understand your question well, but here's my answer:
You can create a private npm module and use npm's normal commands to install it. Most node.js users use git as their repository, but you can use whatever repository works for you.
*
*In your project, you'll want the skeleton of an NPM package. Most
node modules have git repositories where you can look at how they
integrate with NPM (the package.json file, I believe is part of
this and NPM's website shows you how to make a npm package)
*Use something akin to Make to make and tarball your package to be
available from the internet or your network to stage it for npm
install downloads.
*Once your package is made, then use
npm install *tarball_url*
A: This is the easiest way I know - host it in the cloud with the Gemfury private npm registry.
It's free and you can log in with your Github account. It should save you a lot of time, compared to setting up your own database.
A: we are using the Sonatype Nexus, version is Nexus Repository ManagerOSS 3.6.1-02. And I am sure that it supports NPM private repository and cached the package.
A: Verdaccio is what I was looking for and it deserves it's own answer ;) It is an actively maintained fork of Sinopia (highly upvoted answer here). It is a npm registry as a npm package, and can be found
here: https://github.com/verdaccio/verdaccio,
here: https://www.verdaccio.org,
and on port number: 4873
Run using PM2
npm i -g verdaccio pm2
pm2 start --name verdaccio `which verdaccio`
pm2 save
Run using docker
docker run -it --rm --detach --name verdaccio -p 4873:4873 verdaccio/verdaccio
Run using Helm
helm repo add verdaccio https://charts.verdaccio.org
helm repo update
helm install verdaccio/verdaccio
A: A little late to the party, but NodeJS (as of ~Nov 14 I guess) supports corporate NPM repositories - you can find out more on their official site.
From a cursory glance it would appear that npmE allows fall-through mirroring of the NPM repository - that is, it will look up packages in the real NPM repository if it can't find one on your internal one. Seems very useful!
npm Enterprise is an on-premises solution for securely sharing and distributing JavaScript modules within your organization, from the team that maintains npm and the public npm registry. It's designed for teams that need:
easy internal sharing of private modules better control of development
and deployment workflow stricter security around deploying open-source
modules compliance with legal requirements to host code on-premises
npmE is private npm
npmE is an npm registry that works with the same standard npm client
you already use, but provides the features needed by larger
organizations who are now enthusiastically adopting node. It's built
by npm, Inc., the sponsor of the npm open source project and the host
of the public npm registry.
Unfortunately, it's not free. You can get a trial, but it is commerical software. This is the not so great bit for solo developers, but if you're a solo developer, you have GitHub :-)
A: This post talks about how to setup a private registry
*
*make sure couchdb is installed in your system
*Replicating npmjs.org use the following command
curl -X POST http://127.0.0.1:5984/_replicate -d '{"source":"http://isaacs.iriscouch.com/registry/", "target":"registry", "continuous":true, "create_target":true}' -H "Content-Type: application/json"
Note there is "continuous":true in the command, this utilises CouchDB’s _changes API and will pull any new changes when this API is notified.
If you ever want to stop these replications, you can easily add "cancel":true. Then the script would be
curl -X POST http://127.0.0.1:5984/_replicate -d '{"source":"http://isaacs.iriscouch.com/registry/", "target":"registry", "continuous":true, "create_target":true, "cancel":true}' -H "Content-Type: application/json"
Then go to npmjs.org readme to install npm (make sure nodejs and git is installed). Blow is all the steps
git clone git://github.com/isaacs/npmjs.org.git
cd npmjs.org
sudo npm install -g couchapp
npm install couchapp
npm install semver
couchapp push registry/app.js http://localhost:5984/registry
couchapp push www/app.js http://localhost:5984/registry
A: On 14th of April (2015), npm private modules were introduced.
When you pay for private modules, you can:
*
*Host as many private packages as you want
*Give read access or read-write access for those packages to any other paid user
*Install and use any packages that other paid users have given you read access to
*Collaborate on any packages that other paid users have given you write access to
Of course it's not free - currently 7$ a month, per user.
And it's still a pretty new service. For example support for organization accounts is missing (as of June 2015):
Currently, private packages are only available for individual users, but support for organization accounts is coming soon. Feel free to create a user for your organization in the meantime, and we can upgrade it to an organization when support is here.
So while not perfect, it's the official npm solution to maintaining private packages, and that itself makes it worth mentioning.
UPDATE
Npm Private Packages are now available, with plans for both individual users and organizations:
*
*Unlimited number of public & private packages
*$7/month/developer
*Includes one scope name, based on organization name
*Publish and control access to @org-name/foo
(disclaimer: not even remotely affiliated in any way with npm, Inc.)
A: Repository managers with support for private npm registries:
*
*Sonatype Nexus 2.10
*Artifactory 3.2
A: https://github.com/isaacs/npmjs.org/ :
In npm version v1.0.26 you can specify private git repositories urls as a dependency in your package.json files. I have not used it but would love feedback. Here is what you need to do:
{
"name": "my-app",
"dependencies": {
"private-repo": "git+ssh://git@yourgitserver.com:my-app.git#v0.0.1",
}
}
The following post talks about this: Debuggable: Private npm modules
A: I might be a little late to the party but any of these two might work for you:
*
*http://www.jfrog.com/confluence/display/RTF/Npm+Repositories
*https://github.com/krakenjs/kappa
A: I don't think there is an easy way to do this.
A look at the npm documentation tells us, that it is possible:
Can I run my own private registry?
Yes!
The easiest way is to replicate the couch database, and use the same (or similar) design doc to implement the APIs.
If you set up continuous replication from the official CouchDB, and then set your internal CouchDB as the registry config, then you'll be able to read any published packages, in addition to your private ones, and by default will only publish internally. If you then want to publish a package for the whole world to see, you can simply override the --registry config for that command.
There's also an excellent tutorial on how to create a private npm repository in the clock blog.
EDIT (2017-02-26):
Not really new, but there are now paid plans to host private packages on npm.
Over the years, npm has become a factor for many non-Node.js companies, too, through the huge frontend ecosystem that's built upon npm. If your company is already running Sonatype Nexus for hosting Java projects internally, you can also use it for hosting internal npm packages.
Other options include JFrog Artifactory and Inedo ProGet, but I haven't used those.
A: I guess this thread needs an update. If you look at any of the npm registries which are available, they are extremely heavy and they need couchdb. Gemfurry and others need you to fork off from public repos. Some of the npm's like shadow-npm have no recent commits.
Then, we found Reggie. Its got a good commit activity, extremely easy to install and use and has pretty good community support. Its extremely light-weight and you don't have to deal with couchdb, etc.
A: You can also use Aragon Package Manager if you prefer a decentralized approach:
*
*Using APM: http://blog.aragon.one/using-apm-to-replace-npm-and-other-centralized-package-managers/
*Deploying APM: https://github.com/aragon/aragonOS#apm
A: I would like to add to the list the AWS Code Artifact service, looks like a nice approach if your organization is also using AWS git repos.
https://aws.amazon.com/blogs/devops/publishing-private-npm-packages-aws-codeartifact/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "248"
}
|
Q: Private and public variables to a backbone view In a backbone view where would you put your private variables and your public.
Right now I have something like this:
myView = Backbone.View.extend({
initialize: function(options){
this.myPublic = "I'm public";
}
});
I tried adding a var myPrivate before the initialize method but it threw an error. Where would private variables that are only used within the view go?
A: I suggest you use the initialize method as a closure around all other methods. I think this will give you behaviour more consistent with what we get in classical inheritance languages like C++ and Java:
myView = Backbone.View.extend({
initialize: function(options){
var myPrivate = "I'm private";
this.myPublic = "I'm public";
this.getPrivate = function () {
return myPrivate;
};
this.setPrivate = function (value) {
if (typeof(value) === 'string') {
myPrivate = value;
return true;
} else {
return false;
}
};
}
});
A: Wrap it all up in a self-invoking anonymous function:
(function() {
var myPrivate = 1;
myView = Backbone.View.extend({
initialize: function(options){
this.myPublic = "I'm public";
myPrivate++;
},
render: function() {
alert(myPrivate);
}
});
})();
Edit: As pointed out in kaustubh's comment below, the above example creates a private variable that is shared among the instances. You could create a sort of protected variable, that is, an instance level variable that could be read by other instances of the View. Give each instance a unique public id and store instance variables in a "private static" variable. Then access the variables by instance id:
(function() {
var data = [];
myView = Backbone.View.extend({
initialize: function(options){
this.myPublic = "I'm public";
this.Id = data.length;
data.push({});
data[this.Id].myProtected = "abc";
},
render: function() {
alert(data[this.Id].myProtected)
}
});
})();
Or, you can do it without using a public id, but it becomes a bit more convoluted:
(function() {
var data = (function () {
var dataValues = [];
return function (instance) {
for (var i = 0; i < dataValues.length; i++) {
if (dataValues[i].instance === instance) {
return dataValues[i].data;
}
}
var dataObject = { instance: instance, data: {} };
dataValues.push(dataObject);
return dataObject.data;
};
})();
myView = Backbone.View.extend({
initialize: function(options){
this.myPublic = "I'm public";
data(this).myProtected = "abc";
},
render: function() {
alert(data(this).myProtected)
}
});
})();
I'm struggling to come up with a way of storing truly private variables. I'll post back if inspiration strikes.
A: Instead of inserting the object directly into the extend function, how about creating a closure and from that closure return an object to the extend function?
var myView = Backbone.View.extend(function () {
var _myPrivateOne = 0;
function _myPrivateStrangeSquareFunction(a) {
return a * a + 1;
}
return {
initialize: function (options) {
_myPrivateOne = options.privateOne;
this.myPublicOne = options.publicOne;
},
setPrivateOne: function (value) {
_myPrivateOne = value;
return _myPrivateOne;
},
getPrivateOne: function () {
return _myPrivateOne;
},
getPrivateOneStrangelySquared: function () {
return _myPrivateStrangeSquareFunction(_myPrivateOne);
}
};
} ());
I haven't tried this, because I have no Backbone install available right now.
A: gilly3's solution may be the best answer, although it is not technically creating/using a private variable because other instances of the same closure will have access to it (you probably are not as concerned about other members of your development team misusing that privilege, but it could happen).
If you want to use private variables without using gilly3's approach, Near Privman's answer appears to be the only true solution as Douglas Crockford explains how to create private variables here: http://javascript.crockford.com/private.html
This will add additional javascript processing time since it will not be able to make use of prototypal inheritance and will be using resources to recreate the function each time.
However, this may not be a very noticeable issue if the closure you create each time is very small or if the number of times a new instance is created is minimal. In an effort to try and get the best of both worlds, you can delegate the bulk of your method that uses the private variable (via delegation pattern) to a static function that won't get recreated each time. This will leave your publicMethodThatUsesPrivateVariable method shown below smaller, which means that it should take less time to recreate each time.
var _privateStaticMethod = function(privateVariableValue, methodParameter) {
var result;
// Execute the lengthy javascript logic here ...
result = Math.ceil(privateVariableValue / 108);
result += 4815162342;
return result;
};
Backbone.View.extend({
initialize: function() {
var _privateVariable = 303;
this.publicMethodThatUsesPrivateVariable = function(methodParameter) {
// Only place as little logic as you can here outside of the private static method being used below
_privateVariable += 1;
return _privateStaticMethod(_privateVariable, methodParameter);
};
},
// ...
});
Note that the code above should be wrapped in some kind of function as well so that _privateStaticMethod is not a global variable/function.
A: I was liking Near Privman's answer until I ran into a problem with overriding a "super" method. As initialize() isn't called until some way through the construction of a Backbone object, overriding may not have happened by the time it needs to (if it needs to before initialize() is called).
In particular, this can be a problem with parse(). (Not an issue for Views, but definitely for Collections and Models.) Given this setup:
MyModel = Backbone.Model.extend({
initialize: function (options) {
this.parse = function (response, xhr) {
// parsing logic
};
// public & private vars/methods here
// and also initialize code
}
});
MySubModel = MyModel.extend({
initialize: function (options) {
this.parse = function (response, xhr) {
// override MyModel with my own parsing logic
}
// public & private vars/methods here
// and initialize code here
}
});
MySubModel.parse() will never be called.
Instead, I've found that using an IIFE instead of initialize() both clears up this problem and reads cleaner than making a function that already has a specified purpose (initialize()) do double duty as a closure for defining the rest of the class.
var MyModel = {};
(function () {
this.initialize = function (attributes, options) {
// initialize me
}
this.parse = function (response, xhr) {
// override at will
}
// other public & private vars/methods here
}).call(MyModel);
Backbone.Model.extend(MyModel);
Unfortunately, this has the same problem with "private" variables being shared across all instances of the class as do both gilly3 and Near Privman's answers. Would love to hear a non-awkward way to make private variables possible, but maybe I should just give it up and recognize I'm writing JavaScript now, not Java/AS3/C++.
A: You can try this:
var Thing = Backbone.Model.extend(
{
constructor : function ()
{
var _value = "Private data!";
this.getValue = function ()
{
console.log(_value);
};
this.setValue = function (value)
{
_value = value;
};
}
});
A: The standard Backbone way of adding "private" variables is to declare them as attributes with an underscore "_" before them. They are not really private, but developers will realize that they are not meant to be publicly used.
This, in fact, is how Backbone stores its own private variables.
A: In the context of using Broserify.js with Backbone (and really any above medium project) I found the following way to have private vars and functions:
myView.js
'use strict';
var config = require('../config.js'),
private_var = 'private variable',
my_private_fn = function() {
...
};
module.exports = Backbone.Model.extend({
initialize: function() {
this.my_public = 'public variable');
console.log('This is my' + this.my_public);
console.log('This is my' + my_private);
},
});
A: Using "this"?
initialize:function () {
this.viewpointers = {}
},
render:function () {
var self = this
_.each(this.viewpointers, function(item){
self.$el.find(".assigned-items").append(item.render().el)
});
}
adding them. Then these are protected atleast.
this.viewpointers[model.id] = new view({model:model})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: iPhone - do not receive significant location changes in iphone 3gs with iOS 4.2 I am trying to execute the following code on my iPhone 3gs, with the OS version as iOS 4.2.1
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
[m_coreLocationMan startMonitoringSignificantLocationChanges];
#endif
It somehow does not work for me. It works on my iPhone 4, but not on iPhone 3gs with iOS4. Does anyone have any insight into the problem?
A: Check the return value of +[CLLocationManager significantLocationChangeMonitoringAvailable]. If that says YES on the problem device but you're still not getting any messages, then you have a problem; otherwise, it's the expected behavior.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: DataGrid tab navigation skip column I have a datagrid with template columns in WPF. Couple of columns in the grid are readonly, others on focus become editable (instead of labels, textboxes, checkboxes and such appear).
What I would like to achieve is that the readonly columns are skipped when I am tabbing through the grid's columns.
Anyone know how to achieve this?
Thanks!
Vladan
Nope, not working :(
Here is the complete cell...tried it with KeyboardNavigation.IsTabStop and IsTabStop alone...didn't work
<DataGridTemplateColumn Header="{x:Static local:MainWindowResources.gasNameLabel}" Width="*" MinWidth="150" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ContentControl Content="{Binding Path=Name}" ContentTemplate="{StaticResource DataGridTextBoxView}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<Trigger Property="IsReadOnly" Value="true">
<Setter Property="KeyboardNavigation.IsTabStop" Value="False"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGridTemplateColumn.CellStyle>
</DataGridTemplateColumn>
A: Something like this would work:
<DataGrid.Resources>
<Style TargetType="DataGridCell">
<Style.Triggers>
<Trigger Property="IsReadOnly" Value="True">
<Setter Property="IsTabStop" Value="False"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to use Umlauts from PHP in Javascript I have a MySQL database that contains German Umlauts (ä, ü, ö, etc). The database fields are all encoded latin1_german1_c (if that matters).
From that database I create a json object that I use with javascript. However each value that contains one of those Umlauts gets set to null right from the get go via:
var json = <?php echo json_encode($results);?>;
then:
>>> console.log(json[0].name)
null
Do I need to encode my document somehow differently? Do I need to walk through the $results array and encode each value somehow? Or something completely different?
A: json_encodeDocs expects strings to be utf-8 encoded, not latin-1 encoded - that's why the values get reset to NULL (unset).
You need to re-encode the strings from latin-1 to utf-8 before you use them with json_encode. Look for iconvDocs or the mb_string library, both can do that:
$utf8 = iconv($in = 'LATIN-1', $out = 'UTF-8', $latin1);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can you generate complex PDF files with Flex 4? I'm trying to understand if it is possible to generate complex PDF files with Flex.
By complex I mean add images, styled text (font-family, weight, columns) layout elements with large degree of control and so on.
I was looking at AlivePDF library but cannot understand if it can handle more complicated PDF generation than plain text.
Thank you.
A: AlivePDF is your best bet. It's also open source, so you can add more features on it if it doesn't do everything you want for your 'complex' pdf.
Other than that, you'll have to look into server side PDF generation. I know Adobe Livecycle has a pdf generator and I'm sure there's other solutions out there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What happens when you cast from short to byte in C#? I have the following code:
short myShort = 23948;
byte myByte = (byte)myShort;
Now I wasn't expecting myByte to contain the value 23948. I would have guessed that it would contain 255 (I believe the largest value for a byte).
However, it contains 140, and it made me wonder why; what is actually going on behind the scenes?
Please note that I am not looking for someone to solve the problem that 23948 cannot fit into a byte, I am merely wondering about the underlying implementation
A: Basically it just takes the last 8 bits... but in general, when you find some behaviour which surprises you, the next step should be to consult the spec. From section 6.2.1, with the extra emphasis mine, for the situation which is relevant in this case.
For a conversion from an integral type to another integral type, the processing depends on the overflow checking context (§7.6.12) in which the conversion takes place:
*
*In a checked context, the conversion succeeds if the value of the source operand is within the range of the destination type, but throws a System.OverflowException if the value of the source operand is outside the range of the destination type.
*In an unchecked context, the conversion always succeeds, and proceeds as follows.
*
*If the source type is larger than the destination type, then the source value is truncated by discarding its “extra” most significant bits. The result is then treated as a value of the destination type.
*If the source type is smaller than the destination type, then the source value is either sign-extended or zero-extended so that it is the same size as the destination type. Sign-extension is used if the source type is signed; zero-extension is used if the source type is unsigned. The result is then treated as a value of the destination type.
*If the source type is the same size as the destination type, then the source value is treated as a value of the destination type.
A: It depends; in a checked context, you'll get a big fat exception; in an unchecked context (the default) you get to keep the data from the last byte, the same as if you did:
byte b = (byte)(value & 255);
A: In your specific case, the behavior is pretty cut and dry when you look at the bits for the value:
short myShort = 0x5D8C; // 23948
byte myByte = (byte)myShort; // myShort & 0xFF
Console.WriteLine("0x{0:X}", myByte); // 0x8C or 140
A: Short is a 2-byte type and a byte is, well, a single byte. When you cast from two bytes to one you're forcing the system to make things fit and one of the original bytes (the most significant) gets dropped and data is lost. What is left from the value of 23948 (binary: 0101 1101 1000 1100) is 140 which in binary translates to 1000 1100. So you are going from:
0101 1101 1000 1100 (2 byte decimal value 23948)
to:
1000 1100 (1 byte decimal value 140)
You can only do this with an explicit cast. If you tried assigning a short to a byte without a cast the compiler would throw an error because of the potential for loss of data:
Cannot implicitly convert type 'short' to 'byte'. An explicit
conversion exists (are you missing a cast?)
If you cast from a byte to a short on the other hand you could do it implicitly since no data would be getting lost.
using System;
public class MyClass
{
public static void Main()
{
short myShort = 23948;
byte myByte = (byte)myShort; // ok
myByte = myShort; // error:
Console.WriteLine("Short: " + myShort);
Console.WriteLine("Byte: " + myByte);
myShort = myByte; // ok
Console.WriteLine("Short: " + myShort);
}
}
With arithmetic overflow and unchecked context:
using System;
public class MyClass {
public static void Main() {
unchecked {
short myShort = 23948;
byte myByte = (byte)myShort; // ok
myByte = myShort; // still an error
int x = 2147483647 * 2; // ok since unchecked
}
}
}
A: Only the last 8 bits are kept. 23948 in binary is 101110110001100b. The last 8 bits of that is 10001100b, which equals 140.
A: When you cast an integer type to a "smaller" integer type, only the lesser weight bits are considered. Mathematically, it's as if you used the modulo operation. So you get the value 140 because 23948 modulo 256 is 140.
Casting a long to an int would use the same mechanism.
A: The result is the same when you do:
byte myByte = (byte)(myShort & 0xFF);
Everything above the eight bit is simply thrown away. The lower eight bits of 23948 (0x5D8C) is 140 (0x8C).
A: Uhm...because when you cast short (2 bytes) to byte (1 byte) it gets only the first byte, and, the first byte of 23948 represents 140.
A: 23948 % 256 = 140, most significant bytes was lost after conversion, so the output is 140
A: It's like when you have a two digit number, "97", and convert it to a one digit number, you lose the 9 and only keep the "7"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Problems including PDB files in Visual Studio 2010 Installer project I am having a hard time tracking down how to include the debug symbol files in an install project for the debug build (only). If I Project -> Add -> Output -> Debug Symbols (for each project), it will include them when running the release build of the installer.
I want the installer project to only include debug files for the projects I specified when installing the debug build of the installer and not for the release.
Any suggestions...
A: This is not supported by Visual Studio setup projects. Other setup authoring tools offer this feature as builds or releases. Basically, multiple builds with different content.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Can't start WinForms project because Form is a type I have a very small VS2008 Winforms project that will not start.
When I attempt to start debugging the project, I get the message:
'<form>' is a type in '<project>' and cannot be used in an expression.
From the file .Designer.vb.
The problem is that is indeed a form. If I create a new WinForm and set the startup object to the new form, I get the same message.
When I attempt to check the "Enable application framework" checkbox in the Project properties, I get the message "Startup object must be a form when 'Enable application framework' is checked.
I've tried creating a new project and moving all the code and designer objects to a new form file in the new project, and same result.
Other projects on the same computer run fine.
Any suggestions?
Thanks!
A: Turns out that the problem was that I didn't have a New() function with no parameters. This is required for VS to see the class as a form.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: firefox add-on vs. extensions vs. plugins I want to write scripts for firefox. It seems that firefox has different terms, like add-on, extensions, plugins. and I have a feeling they're not all the same. Can you sum up the difference between in a few words?
A: Augmenting the useful answer above, I found this high-level summary helpful:
Extensions differ slightly from plug-ins. Plug-ins usually have a narrow set of abilities. [..] Since plug-ins and extensions both increase the utility of the original application, Mozilla uses the term "add-on" as an inclusive category of augmentation modules that consists of plug-ins, themes, and search engines.
(from http://en.wikipedia.org/wiki/Plug-in_(computing))
A: Add-on: essentially anything that can be installed into the browser. This includes for example extensions, themes, plugins, dictionaries, language packs, search engines.
Extension: a package extending browser functionality, the extension format used by Firefox works in Gecko-based browsers only. Extensions typically use XUL and CSS for their user interface as well as JavaScript for dynamic actions. They have full access to XPCOM and can provide their own XPCOM components as well. Recently the Add-on SDK has been added as an alternative way to generate simple extensions, it uses HTML instead of XUL but limits the ways in which the browser's user interface can be extended significantly. As of Firefox 57, all extensions have to be based on the WebExtensions API.
Plugin: means NPAPI plugins that are supported by all browsers but Internet Explorer (the latter uses the proprietary ActiveX technology instead). Such plugins are binary libraries that are invoked if a website uses an <embed> or <object> tag with a type that is handled by the plugin. The plugin can either draw some content for the tag (windowed plugins) or stay in background and simply provide an API for the webpage's JavaScript code to use (windowless plugins). Typical examples are Flash or Silverlight. Support for plugins is being phased out, as of 2018 Flash is the only plugin still supported to some degree.
A: According to Firefox:
Extensions
Extensions add new features to Firefox or modify existing ones. There are extensions that allow you to block advertisements, download videos from websites, integrate Firefox with websites like Facebook or Twitter and add features included in other browsers, such as translator.
Plugins
Plugins add support for all kinds of Internet content. These usually include patented formats like Flash that are used for video, audio, online games, presentations and more. Plugins are created and distributed by other companies.
add-ons
They are - Extensions, Plugnis, Themes, Search engines and Dictionaries & Language Packs.
Source: Firefox - https://support.mozilla.org/en-US/kb/find-and-install-add-ons-add-features-to-firefox
A: Extending the Augmentation above
Extension(s) is ment to extend the functionality of software
where a plug-in is ment to solve a problem of the software (to be able to do something it wasent designed to do already).
both types extends the program abilitys,
... and i guess this is why it can be so comfusing.
An Extension can be (and often are) a(n) option from the company that made the software (Usually cost money),
a plug-in can be from the company that made the software or a third party to add abilities to the software.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
}
|
Q: Node.js - Connecting to MongoDB using MongoHQ on Heroku I have a Node.js app using Express that stores data in a mongoDB (locally).
It's now pushed to heroku successfully on a cedar stack and the server is running. I added the mongohq addon through the terminal.
Now... how do I connect that mongoDB through mongohq to my application to start using it??? I don't see a tutorial for this anywhere online. If you can point me to one or get me started on where to add the configuration, I would greatly appreciate!
Thanks much.
Update:
I've tried the following (with real values for MYPASSWORD and MYDBNUMBER:
in routes.js
var db = mongoose.connect('mongodb://heroku:<MYPASSWORD>@staff.mongohq.com:10049/<MYDBNUMBER>');
in my schema.js (also tried using the heroku
var mongoose = require('mongoose');
mongoose.connect('mongodb://heroku:<MYPASSWORD>@staff.mongohq.com:10049/<MYDBNUMBER>');
my package.json
{
"name": "NAME"
, "version": "0.0.1"
, "dependencies": {
"express": "2.4.6"
, "connect": "1.7.1"
, "stylus": ">= 0.0.1"
, "mongodb": ">= 0.9.6-7"
, "mongoose": ">= 2.0.0"
, "ejs": ">=0.4.3"
}
}
Right now, only the root '/' GET is successful. Actually, if I try /page/ANYTHING I can successfully get a rendered 500 Error page that I made to handle attempts to get 'pages' that haven't been created... That seems kind of weird to me. Everything else gives me an Internal Server Error.
ALSO, if i go to mongohq and open my database there, a collection for my model pages has been created and the indexes for uniqueness have been created, even tho I haven't been able to access the pages to create or view the model in my app...
happy to provide any other info... so stuck.
A: We are using heroku against MongoHQ but in our case we created the MongoHQ account on our own so our solution is a bit different.
Now, we are using the Redis plugin and in that case we connect to Redis using the heroku env variables.
When you create a new plugin, Heroku adds a bunch of env variables that you can access from your node.js app easily doing this:
process.env.NAME_OF_VAR
In the case of Redis to go the name of the var is REDISTOGO_URL so our code looks like
process.env.REDISTOGO_URL
For MongoHQ the env variable seems to be MONGOHQ_URL
You may need to do some parsing. Heroku have some documentation for Ruby here http://devcenter.heroku.com/articles/mongohq#using_the_mongo_ruby_driver that should help you to get it going.
With respect to where to do this in an express app. We are doing all the setup on app.js that is our entry point in the app.
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Merging two multidimensional associative arrays I'm chasing my tail trying to combine the results of two different queries to output in a template.
I'm trying to merge the corresponding sub-arrays in model_data and entry_data to get desired_result. I will then iterate over desired_result and print values into the template.
Any assistance is greatly appreciated.
model_data
array(2) {
[0]=>
array(2) {
["entry_id"]=> string(3) "192"
["field_id_49"]=> string(10) "Model Name"
}
[1]=>
array(2) {
["entry_id"]=> string(3) "193"
["field_id_49"]=> string(5) "MN123"
}
}
entry_data
array(2) {
[0]=>
array(2) {
["uri"]=> string(24) "/products/product-title/"
["title"]=> string(13) "Product Title"
}
[1]=>
array(2) {
["uri"]=> string(22) "/products/lorem-ipsum/"
["title"]=> string(11) "Lorem Ipsum"
}
}
desired_result
array(2) {
[0]=>
array(4) {
["entry_id"]=> string(3) "192"
["field_id_49"]=> string(10) "Model Name"
["uri"]=> string(24) "/products/product-title/"
["title"]=> string(13) "Product Title"
}
[1]=>
array(4) {
["entry_id"]=> string(3) "193"
["field_id_49"]=> string(5) "MN123"
["uri"]=> string(22) "/products/lorem-ipsum/"
["title"]=> string(11) "Lorem Ipsum"
}
}
A: foreach($model_data as $key => $value){
$result[$key] = array_merge($entry_data[$key], $model_data[$key]);
}
A: You can use array_replace_recursive function to merge these arrays.
Below is a example:
$desired_result = array_replace_recursive($model_data, $entry_data);
var_dump($desired_result);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Why might my AudioQueueOutputCallback not be called? I'm using the Audio Queue Services API to play audio streamed from a server over a TCP socket connection on an iPhone. I can play the buffers that were filled from the socket connection, I just cannot seem to make my AudioQueue call my AudioQueueOutputCallback function, and I'm out of ideas.
High level design
*
*Data is passed to the player from the socket connection, and written
immediately into circular buffers in memory.
*As AudioQueueBuffers become available, data is copied from the circular buffers into the
available AudioQueueBuffer, which is immediately re-queued. (Or would be, if my callback happened)
What happens
The buffers are all filled and enqueued successfully, and I hear the audio stream clearly. For testing, I use a large number of buffers (15) and all of them play through seamlessly, but the AudioQueueOutputCallback is never called, so I never re-queue any of those buffers, despite the fact that everything seems to be working perfectly. If I don't wait for my callback, assuming it will never be called, and instead drive the enqueueing of buffers based on the data as it is written, I can play the audio stream indefinitely, reusing and re-enqueueing buffers as if they had been explicitly returned to me by the callback. It is that fact: that I can play the stream perfectly while reusing buffers as needed, that confuses me the most. Why isn't the callback being called?
Possibly Relevant Code
The format of the stream is 16 bit linear PCM, 8 kHz, Mono:
_streamDescription.mSampleRate = 8000.0f;
_streamDescription.mFormatID = kAudioFormatLinearPCM;
_streamDescription.mBytesPerPacket = 2;
_streamDescription.mFramesPerPacket = 1;
_streamDescription.mBytesPerFrame = sizeof(AudioSampleType);
_streamDescription.mChannelsPerFrame = 1;
_streamDescription.mBitsPerChannel = 8 * sizeof(AudioSampleType)
_streamDescription.mReserved = 0;
_streamDescription.mFormatFlags = (kLinearPCMFormatFlagIsBigEndian |
kLinearPCMFormatFlagIsPacked);
My prototype and implementation of the callback are as follows. Nothing fancy, and pretty much identical to every example I've seen so far:
// Prototype, declared above the class's @implementation
void AQBufferCallback(void* inUserData, AudioQueueRef inAudioQueue, AudioQueueBufferRef inAudioQueueBuffer);
// Definition at the bottom of the file.
void AQBufferCallback(void* inUserData, AudioQueueRef inAudioQueue, AudioQueueBufferRef inAudioQueueBuffer) {
printf("callback\n");
[(MyAudioPlayer *)inUserData audioQueue:inAudioQueue didAquireBufferForReuse:inAudioQueueBuffer];
}
I create the AudioQueue like this:
OSStatus status = 0;
status = AudioQueueNewOutput(&_streamDescription,
AQBufferCallback, // <-- Doesn't work...
self,
CFRunLoopGetCurrent(),
kCFRunLoopCommonModes,
0,
&_audioQueue);
if (status) {
// This is not called...
NSLog(@"Error creating new audio output queue: %@", [MyAudioPlayer stringForOSStatus:status]);
return;
}
And I enqueue buffers like this. At this point, it is known that the local buffer contains the correct amount of data for copying:
memcpy(aqBuffer->mAudioData, localBuffer, kAQBufferSize);
aqBuffer->mAudioDataByteSize = kAQBufferSize;
OSStatus status = AudioQueueEnqueueBuffer(_audioQueue, aqBuffer, 0, NULL);
if (status) {
// This is also not called.
NSLog(@"Error enqueueing buffer %@", [MyAudioPlayer stringForOSStatus:status]);
}
Please save me.
A: Is this executed on the main thread or a background thread? probably not good if CFRunLoopGetCurrent() returns a run loop of a thread that could disappear (thread pool etc) or is a run loop that don't care about kCFRunLoopCommonModes.
Try to change CFRunLoopGetCurrent() to CFRunLoopGetMain() or make sure AudioQueueNewOutput() and CFRunLoopGetCurrent() is executed on the main thread or a thread that you have control over and has a proper run loop.
A: Try changing self for (void*)self. Like this:
status = AudioQueueNewOutput(&_streamDescription,
AQBufferCallback,
(void*)self,
CFRunLoopGetCurrent(),
kCFRunLoopCommonModes,
0,
&_audioQueue);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Confusion over generating custom JSON response in Rails Model description:
User, Widget, Purchase
User
has_many :purchases
has_many :widgets, :through => :purchases
Widget
has_many :purchases
has_many :users, :through => :purchases
Purchase
belongs_to :user
belongs_to :widget
Hope that makes sense and is correct for the below.
Right, in my controller, I have current_user.
I wish to render a nested JSON response for use eventually with jquery templates.
Like this would be ideal:
{
"purchases": [
{
"quantity": 200,
"price": "1.0",
"widget": {
"name": "Fantastic Widget",
"size": "Large"
}
},
{
"quantity": 300,
"price": "3.0",
"widget": {
"name": "Awesome Widget",
"size": "Medium"
}
}
]
}
This:
render :json => current_user.to_json(:include => [:purchases, :widgets])
Will render some current_user details (not really relevant) and then purchases and widgets at the same level.
This works (outputs some current user details but thats not my main gripe at the moment):
render :json => current_user.to_json({:include => :purchases })
But obviously only outputs purchase data. I cannot get a nested include to work (should it work?) even after looking at this sample:
konata.to_json(:include => { :posts => {
:include => { :comments => {
:only => :body } },
:only => :title } })
From here and this existing stackoverflow question.
So I've just got myself thoroughly confused. Help appreciated.
A: I would look into utilizing the as_json method in your models to get the desired output. Adding the following to your models should get you going in the right direction.
#users model
def as_json(options={})
{:purchases => self.purchases}
end
#purchases model
def as_json(options={})
{:quantity: self.quantity,
:price: self.price,
:widget: self.widget}
end
#widgets model
def as_json(options={})
{:name:self.name,
:size: self.size}
end
Once you've added these you'd simply user to_json on your user instance and it should output correctly.
A: RABL lets you craft JSON views similar to the HTML ERB views.
This blog post, "If you’re using to_json, you’re doing it wrong", explains a bit of background and the shortcomings of using to_json.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Retrieving contact info in Android fails with exception ALL,
I am trying to execute following piece of code:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query( ContactContract.Contacts.CONTENT_URI, null, "ContactsContract.Contacts.DISPLAY_NAME LIKE '" + name + "'", null, null );
However when running this code, I am getting SQLite exception: "Don't know such file ContactsContract.Contacts.DISPLAY_NAME:, while compiling "....."".
The problem is that I don't know in advance what will "name" contain, hence using "LIKE" clause.
Is there a better way to perform such operation? Or I am just doing it incorrectly?
Thank you in advance for any help.
A:
Or I am just doing it incorrectly?
ContactsContract.Contacts.DISPLAY_NAME is a Java construct. Use:
Cursor cur = cr.query( ContactContract.Contacts.CONTENT_URI, null, ContactsContract.Contacts.DISPLAY_NAME + " LIKE '" + name + "'", null, null );
Or, use positional parameters:
Cursor cur = cr.query( ContactContract.Contacts.CONTENT_URI, null, ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?", args, null );
where args is a one-element string array containing your name.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to initialize a vector in MATLAB as per a pattern? I am completely new to MATLAB.This may be a rather basic question.
Given numerical values for size, extras and max, I need to initialize a 1 X N vector such that the first size elements are 1, the next size are 2, the next size are 3 and so on till the last size elements are set to max. So I need to initialize size number of elements successively to x such that x increments from 1 to max. The extras are the number of leftover cells which are initialized to 0. To illustrate:
size = 3; %# (is same as the quotient of N/max)
extras = 1; %# (is same as remainder of N/max)
max = 3;
N = 10;
original_vector = [0 0 0 0 0 0 0 0 0 0];
The desired output is
Required_vector = [1 1 1 2 2 2 3 3 3 0]
A: Maybe something using the Kronecker product:
N = 10;
max = 3;
extras = rem(N, max);
size = floor(N/max);
v = [kron([1 : max], ones(1,size)) zeros(1, extras)];
I took a guess about how extras and size are calculated. You said size is N % max and extras is N rem max, but those are the same thing(?).
A: Some reshaping acrobatics should do it:
>> size = 3;
>> max = 3;
>> N = 10;
>> v = zeros(1, N);
>> v(1:size*max) = reshape(cumsum(ones(max, size))', size*max, 1)
v =
1 1 1 2 2 2 3 3 3 0
Another example:
>> size = 4;
>> max = 5;
>> N = 23;
>> v(1:size*max) = reshape(cumsum(ones(max, size))', size*max, 1)
v =
Columns 1 through 18
1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5
Columns 19 through 23
5 5 0 0 0
A: This is a quite dirty implementation, but as you say you are very new to MATLAB, it might be better for you to see how you can more or less brute force a solution out. The trick here is the index reference done on Vec to place the numbers in. I have ignored the parameter extras and instead fill the vector up as best can be with the elements
N = 23;
max = 3;
size = 4;
Vec = zeros(N,1);
for i=1:max
for j=1:size
Vec((i-1)*size +1 + (j-1)) = i;
end
end
Vec'
extra = sum(Vec==0)
Output:
ans =
1 1 1 1 2 2 2 2 3 3 3 3 0 0 0 0 0 0 0 0 0 0 0
extra =
11
A: A slight modification of @b3's solution:
N = 10;
mx = 3;
sz = floor(N/mx);
v = zeros(1,N);
v(1:mx*sz) = repmat(1:mx,sz,1)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Are Microsoft's IE Images 64-bit or 32-bit? Are Microsoft's Internet Explorer Application Compatibility VPC Images 64-bit or 32-bit? For example, if I were to download the Windows Vista with IE7 image and then install IE9, would it be IE9 64-bit and 32-bit or just 32-bit by itself? You would think this information would be shown somewhere on Microsoft's site, but I'm not seeing it.
A: Since they are built for Microsoft Virtual PC as stated in the article, these would all be 32 bit only as Virtual PC only supports 32 bit guests.
A: I believe it's a universal binary that contains both, but will install only the 32bit version if you're on a 32bit host. By default, Vista/Win7 will both start the 32bit version anyways, since most plugins (especially Flash, until v11 is actually released) have not made the jump to 64bit yet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: CSS question with cake.generic.css: Can't decrease the width of a table inside a division I have two division with float: left;
div#loadwhat {
float: left;
width: 78%;
padding-right: 5px;
}
div#id_div_rightside {
float: left;
width: 20%;
height: 100%;
border-left:solid thin #ff9900;
}
But the table inside loadwhat division is much wider than the loadwhat division. Why is that ?
I want to decrease the width of table. I tried to set width: xx for table but it didn't work.
In cake.generic.css
table {
background: #fff;
border-right:0;
clear: both;
color: #333;
margin-bottom: 10px;
width: 100%;
}
How can i solve this problem ?
A: Perhaps try removing the table width and add table-layout:fixed;. This may even out the rows in many browsers. Here is more detail: http://reference.sitepoint.com/css/table-layout
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get request being aborted in Internet Explorer 9 If you'll visit the site lab.buffspec.com SPECIFICALLY using Internet Explorer 9 and select a gildan 6.1, a hanes 6.1 or a gildan hood and then click on the get pricing button you will see that despite updating the quantity the total price isn't shown. This happens in Internet Explorer 9 only for these 3 shirts, the others work fine. And this behavior occurs only in IE9, the site works fine in firefox and chrome. When I select Developer tools in IE9 and go the network tab and start capturing, I find that the request shows '(Aborted)' and the initiator tab shows '(Pending)'.
Does anyone know what is happening here? I haven't checked with other versions of internet explorer.
Also, the response and request are in XML.
public static function getPricingXml(event:NumericStepperEvent = null):XML
{
for each (var side:String in ['front', 'back']) {
var workspace:Canvas = mx.core.Application.application[side + 'Workspace'];
var colors:Array = new Array();
for each (var e:* in workspace.getChildren()) {
if (e is Image && e.includeInLayout) {
for each (var color:String in e.colors) {
if (color) {
color = color.toLowerCase();
if (color && colors.indexOf(color) == -1) {
colors.push(color);
}
}
}
}
}
mx.core.Application.application[side + "TotalColors"].text = colors.length > 4 ? 4 : colors.length;
}
var xml:XML = <products>
<product requiresUndercoat={mx.core.Application.application.color.type !== 'white'}>
<color hexValue={mx.core.Application.application.color.hex_color} />
<sides>
<front totalColors={mx.core.Application.application.frontTotalColors.text} />
<back totalColors={mx.core.Application.application.backTotalColors.text} />
</sides>
<sizes />
{mx.core.Application.application.names.getXml()}
</product>
</products>;
var i:int = 0;
for each (var size:Object in mx.core.Application.application.color.sizes) {
xml.product.sizes.appendChild(<size name={size.name} abbreviation={size.abbreviation} quantity={mx.core.Application.application.priceSteppers[i++].value} price={size.price} />);
}
return xml;
}
This is the flex function that builds the XML request when the 'Get Pricing' button is clicked.
<mx:GridItem horizontalAlign="right" width="100%" fontWeight="normal" verticalAlign="middle">
<mx:NumericStepper id="priceSteppers" value="0" maximum="599" fontSize="12" change="getPrices.send({ data: com.buffspec.Lab.getPricingXml(event) });" />
</mx:GridItem>
This is the code for the stepper that increases the quantity and is supposed to call the get pricing button.
<mx:HTTPService id="getPrices" url="http://www.buffspec.com/store/lab/getPricing.php" resultFormat="e4x" />
Finally, getPrices is an httpservice that gets the corresponding result from http://www.buffspec.com/store/lab/getPricing.php as an XML file.
I noticed that the content type is 'text/plain' for both request and response if that means anything. Also the response is HTTP/200, so I don't know WHY it's getting aborted.
A: Well, I finally figured it out. The URL that's being sent via the GET method which is the default for e4x is more than 2083 characters, which is Internet Explorer's upper limit. The moment a URL of this size is recieved by Internet Explorer it just abortd the GET method's execution. Hope this helps anyone with a similar issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Updating MS Access Linked Table from VBS file I am currently working on moving 100s of access databases from a variety of folders to another set of folders and need to update any references to linked tables that will be broken during the move. I have identified how to update the location of the linked database table by adding a macro to the access database itself by doing something like the following:
Dim tdf As TableDef, db As Database
Set db = CurrentDb
db.TableDefs.Refresh
For Each tdf In db.TableDefs
' My Logic for checking to see if it is is a linked
' table and then updating it appropriately
Next
Set collTables = Nothing
Set tdf = Nothing
Set db = Nothing
However, I do not want to have to add the code to each of the access databases so I was wondering if there was a way to create a VBS file which would execute the same type of logic. I tried the following code, but I am getting the following error when the line with the for each logic is executed: "Arguments are of the wrong type, are out of acceptable range or are in conflict with one another"
Set MyConn = CreateObject("ADODB.Connection")
MyConn.Open "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = MyFile.mdb"
for each tblLoop in db.TableDefs
' business logic
next
set tblLoop = nothing
MyConn.close
set MyConn = nothing
I'm hoping that someone more familiar with doing this type of coding will be able to point me in the right direction. Is there a way to utilize the TableDefs table from outside of Access through a VBS file and if so, what would that code look like.
Thanks,
Jeremy
A: You cannot use tabledefs with ADO, but you can open the database in VBScript:
Dim db ''As DAO.Database
Dim ac ''As Access Application
''As noted by wmajors81, OpenDatabase is not a method of the application object
''OpenDatabase works with DBEngine: http://support.microsoft.com/kb/152400
Set ac = CreateObject("Access.Application")
ac.OpenCurrentDatabase("c:\test.mdb")
Set db = ac.CurrentDatabase
For Each tdf In db.TableDefs
Etc.
If you have start up code or forms, or database passwords, you will run into some problems, but these can be overcome, for the most part, by simulating the shift key press. This would be easier, I think, in VBA than VBScript, but AFAIK it is possible in VBScript. database passwords can be supplied in the OpenDatabase action.
A: I was able to expand upon the answer by @Remou to come up with some code that worked. Part of his answer included the following statement which threw an error "Set db = ac.OpenDatabase". As far as I can tell "OpenDatabase" is not a valid method, but OPenCurrentDatabase is. Also, I was getting an error when trying to set db equal to the value returned by OpenCurrentDatabase so I'm assuming that it is a sub and not a function. However, I was able to get access to the Current Database by utilizing ac.CurrentDB once I had established the connection to the the database utilizing OpenCurrentDatabase
Dim db ''As DAO.Database
Dim ac ''As Access Application
Set ac = CreateObject("Access.Application")
ac.OpenCurrentDatabase("D:\delete\UpdatingLinkedTableInAccess\GrpLfRsvs201108.mdb")
set db = ac.CurrentDB
For Each tdf In db.TableDefs
With tdf
If Len(.Connect) > 0 Then
If Left(.Connect, 4) = "ODBC" Then
' ignore these are connected via ODBC and are out of scope
Else
' biz logic
End If
End If
End With
next
set db = nothing
ac.Quit
set ac = nothing
Thanks again @Remou for your assistance.
A: You don't need to create an Access application instance. Use DBEngine and DAO.Workspace instead.
Option Explicit
Dim db
Dim dbe
Dim strDbPath
Dim tdf
Dim wrkJet
strDbPath = "C:\Access\webforums\whiteboard2003.mdb"
Set dbe = CreateObject("DAO.DBEngine.36")
Set wrkJet = dbe.CreateWorkspace("", "admin", "", 2) ' dbUseJet = 2
' exclusive = True and read-only = False '
Set db = wrkJet.OpenDatabase(strDbPath, True, False)
For Each tdf In db.TableDefs
If Left(tdf.Connect, 10) = ";DATABASE=" Then
WScript.Echo tdf.Connect
End If
Next
db.Close
Set db = Nothing
Set wrkJet = Nothing
Set dbe = Nothing
You would need "DAO.DBEngine.120" for ACCDB format database.
If you're using a database password, include it in OpenDatabase.
Set db = wrkJet.OpenDatabase(strDbPath, True, False, ";pwd=password")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: llvm exceptions; catch handler not handling, cleanup not called I i'm trying to create a exception handler inside JIT llvm code. the current documentation regarding exception handling in LLVM is very handwavy at the moment, so i've been trying to reuse most of the snippets i get from http://llvm.org/demo in order to get a working example, but i'm not sure if those are up to date with llvm 2.9 (the version i am using).
This is what the module looks after Module::dump();
; ModuleID = 'testModule'
declare i32 @myfunc()
define i32 @test_function_that_invokes_another() {
entryBlock:
%0 = alloca i8*
%1 = alloca i32
%someName = invoke i32 @myfunc()
to label %exitBlock unwind label %unwindBlock
exitBlock: ; preds = %entryBlock
ret i32 1
unwindBlock: ; preds = %entryBlock
%2 = call i8* @llvm.eh.exception()
store i8* %2, i8** %0
%3 = call i32 (i8*, i8*, ...)* @llvm.eh.selector(i8* %2, i8* bitcast (i32 (...)* @__gxx_personality_v0 to i8*), i8* null)
store i32 1, i32* %1
%4 = load i8** %0
%5 = call i32 (...)* @__cxa_begin_catch(i8* %4) nounwind
%cleanup_call = call i32 @myCleanup()
%6 = call i32 (...)* @__cxa_end_catch()
ret i32 1
}
declare i32 @__gxx_personality_v0(...)
declare i32 @__cxa_begin_catch(...)
declare i32 @__cxa_end_catch(...)
declare i8* @llvm.eh.exception() nounwind readonly
declare i32 @llvm.eh.selector(i8*, i8*, ...) nounwind
declare i32 @myCleanup()
and this is what happens when i try to execute the function:
inside JIT calling C/C++ call
terminate called after throwing an instance of 'int'
Aborted
this shows that the function that throws gets called, it throws, but i never land in the cleanup call. (my cleanup call should have said 'inside JIT calling C/C++ Cleanup')
The function that invokes and (attempts) to catch a thrown exception is:
const inline llvm::FunctionType* getTestFunctionSignature(llvm::LLVMContext& context) {
return llvm::TypeBuilder< unsigned int(), false > ::get(context);
}
llvm::Function* createFunctionThatInvokesAnother( llvm::LLVMContext& ctx, llvm::Module* mod , llvm::Function* another ) {
llvm::Function* result = llvm::Function::Create(getTestFunctionSignature(ctx),
llvm::GlobalValue::ExternalLinkage,
"test_function_that_invokes_another",
mod);
llvm::BasicBlock* entry_block = llvm::BasicBlock::Create(ctx, "entryBlock", result);
llvm::BasicBlock* exit_block = llvm::BasicBlock::Create(ctx, "exitBlock", result);
llvm::BasicBlock* unwind_block = llvm::BasicBlock::Create(ctx, "unwindBlock", result);
llvm::IRBuilder<> builder(entry_block);
llvm::ConstantInt* ci = llvm::ConstantInt::get( mod->getContext() , llvm::APInt( 32 , llvm::StringRef("1"), 10));
llvm::PointerType* pty3 = llvm::PointerType::get(llvm::IntegerType::get(mod->getContext(), 8), 0);
llvm::AllocaInst* ptr_24 = new llvm::AllocaInst(pty3, "", entry_block);
llvm::AllocaInst* ptr_25 = new llvm::AllocaInst(llvm::IntegerType::get(mod->getContext(), 32), "", entry_block);
llvm::Twine name("someName");
builder.CreateInvoke( another , exit_block , unwind_block , "someName" );
builder.SetInsertPoint( exit_block );
builder.CreateRet(ci);
builder.SetInsertPoint( unwind_block );
llvm::Function* func___gxx_personality_v0 = func__gxx_personality_v0(mod);
llvm::Function* func___cxa_begin_catch = func__cxa_begin_catch(mod);
llvm::Function* func___cxa_end_catch = func__cxa_end_catch(mod);
llvm::Function* func_eh_ex = func_llvm_eh_exception(mod);
llvm::Function* func_eh_sel = func__llvm_eh_selector(mod);
llvm::Constant* const_ptr_17 = llvm::ConstantExpr::getCast(llvm::Instruction::BitCast, func___gxx_personality_v0, pty3);
llvm::ConstantPointerNull* const_ptr_18 = llvm::ConstantPointerNull::get(pty3);
llvm::CallInst* get_ex = llvm::CallInst::Create(func_eh_ex, "", unwind_block);
get_ex->setCallingConv(llvm::CallingConv::C);
get_ex->setTailCall(false);
new llvm::StoreInst(get_ex, ptr_24, false, unwind_block);
std::vector<llvm::Value*> int32_37_params;
int32_37_params.push_back(get_ex);
int32_37_params.push_back(const_ptr_17);
int32_37_params.push_back(const_ptr_18);
llvm::CallInst* eh_sel = llvm::CallInst::Create(func_eh_sel, int32_37_params.begin(), int32_37_params.end(), "", unwind_block);
eh_sel->setCallingConv(llvm::CallingConv::C);
eh_sel->setTailCall(false);
new llvm::StoreInst(ci, ptr_25, false, unwind_block);
llvm::LoadInst* ptr_29 = new llvm::LoadInst(ptr_24, "", false, unwind_block);
llvm::CallInst* ptr_30 = llvm::CallInst::Create(func___cxa_begin_catch, ptr_29, "", unwind_block);
ptr_30->setCallingConv(llvm::CallingConv::C);
ptr_30->setTailCall(false);
llvm::AttrListPtr ptr_30_PAL;
{
llvm::SmallVector<llvm::AttributeWithIndex, 4 > Attrs;
llvm::AttributeWithIndex PAWI;
PAWI.Index = 4294967295U;
PAWI.Attrs = 0 | llvm::Attribute::NoUnwind;
Attrs.push_back(PAWI);
ptr_30_PAL = llvm::AttrListPtr::get(Attrs.begin(), Attrs.end());
}
ptr_30->setAttributes(ptr_30_PAL);
llvm::Function* cleanup = call_myCleanup( mod );
builder.CreateCall( cleanup , "cleanup_call");
llvm::CallInst* end_catch = llvm::CallInst::Create(func___cxa_end_catch, "", unwind_block);
builder.CreateRet(ci);
//createCatchHandler( mod , unwind_block );
return result;
}
This gets called like the usual business:
testMain() {
llvm::LLVMContext ctx;
llvm::InitializeNativeTarget();
llvm::StringRef idRef("testModule");
llvm::Module* module = new llvm::Module(idRef, ctx);
std::string jitErrorString;
llvm::ExecutionEngine* execEngine = executionEngine( module , jitErrorString );
llvm::FunctionPassManager* OurFPM = new llvm::FunctionPassManager(module);
llvm::Function *thr = call_my_func_that_throws( module );
llvm::Function* result = createFunctionThatInvokesAnother(ctx, module ,thr);
std::string errorInfo;
llvm::verifyModule(* module, llvm::PrintMessageAction, & errorInfo);
module->dump();
void *fptr = execEngine->getPointerToFunction(result);
unsigned int (*fp)() = (unsigned int (*)())fptr;
try {
unsigned int value = fp();
} catch (...) {
std::cout << " handled a throw from JIT function" << std::endl;
}
}
where my function that throws is:
int myfunc() {
std::cout << " inside JIT calling C/C++ call" << std::endl;
throw 0;
};
llvm::Function* call_my_func_that_throws (llvm::Module* mod) {
std::vector< const llvm::Type* > FuncTy_ex_args;
llvm::FunctionType* FuncTy_ex = llvm::FunctionType::get( llvm::IntegerType::get( mod->getContext() , 32) , FuncTy_ex_args , false);
llvm::Function* result = llvm::Function::Create(FuncTy_ex, llvm::GlobalValue::ExternalLinkage, "myfunc", mod);
result->setCallingConv( llvm::CallingConv::C );
llvm::AttrListPtr PAL;
result->setAttributes( PAL );
llvm::sys::DynamicLibrary::AddSymbol( "myfunc" , (void*) &myfunc );
return result;
}
and my cleanup function is defined in a similar way:
int myCleanup() {
std::cout << " inside JIT calling C/C++ Cleanup" << std::endl;
return 18;
};
llvm::Function* call_myCleanup (llvm::Module* mod) {
std::vector< const llvm::Type* > FuncTy_ex_args;
llvm::FunctionType* FuncTy_ex = llvm::FunctionType::get( llvm::IntegerType::get( mod->getContext() , 32) , FuncTy_ex_args , false);
llvm::Function* result = llvm::Function::Create(FuncTy_ex, llvm::GlobalValue::ExternalLinkage, "myCleanup", mod);
result->setCallingConv( llvm::CallingConv::C );
llvm::AttrListPtr PAL;
result->setAttributes( PAL );
llvm::sys::DynamicLibrary::AddSymbol( "myCleanup" , (void*) &myCleanup );
return result;
}
I've also read this document regarding recent exception handling changes in LLVM, but is not clear how those changes translate to actual, you know, code
A: Right now the EH code is undergoing a large amount of revision. The demo, if I recall correctly, is not version 2.9, but current development sources - meaning trying to do something with 2.9 is going to be a world of hurt if you try that way.
That said, the EH representation is much better now and numerous patches have gone in to improve the documentation just this week. If you are trying to write a language that uses exceptions via llvm I highly suggest you migrate your code to current development sources.
All of that said, I'm not sure how well exception handling works in the JIT at all right now. It's nominally supported, but you may need to debug the unwind tables that are put into memory to make sure they're correct.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Concise way to initialize a block of memory with magic numbers A few examples of what I'm referring to:
typedef struct SOME_STRUCT {
unsigned int x1;
unsigned int x2;
unsigned int x3;
unsigned int x4;
// What I expected would work, but doesn't; the 2nd parameter gets
// turned into an 8-bit quantity at some point within memset
SOME_STRUCT() { memset( this, 0xFEEDFACE, sizeof( *this ) ); }
// Something that worked, but seems hokey/hackish
SOME_STRUCT() {
unsigned int *me = (unsigned int *)this;
for( int ii = 0; ii < sizeof(*this)/sizeof(*me); ++ii ) {
me[ii] = 0xFEEDFACE;
}
}
// The far-more-verbose-but-C++-way-of-doing-it
// This works, but doesn't lend itself very well
// to being a drop-in way to pull this off on
// any struct.
SOME_STRUCT() : x1( 0xFEEDFACE )
, x2( 0XFEEDFACE )
, x3( 0XFEEDFACE )
, x4( 0XFEEDFACE ) {}
// This would work, but I figured there would be a standard
// function that would alleviate the need to do it myself
SOME_STRUCT() { my_memset( this, 0xFEEDFACE, sizeof(*this) ); }
}
I can't use valgrind here, and my options are limited as far as various debugging libraries I have access to -- which is why I'm doing it myself for this one-off case.
A: Here’s a partial example of using std::generate() safely:
#include <algorithm>
struct Wizard {
size_t i;
static unsigned char magic[4];
Wizard() : i(0) {}
unsigned char operator()() {
size_t j = i++;
i %= sizeof(magic); // Not strictly necessary due to wrapping.
return magic[j];
}
};
unsigned char Wizard::magic[4] = {0xDE,0xAD,0xBE,0xEF};
std::generate(reinterpret_cast<unsigned char*>(this),
reinterpret_cast<unsigned char*>(this) + sizeof(*this),
Wizard());
(Of course, the endianness may or may not be right, depending on how you’re looking and what you’re expecting to see when you do!)
A: I would declare this constructor:
SOME_STRUCT( unsigned int magic) : x1 (magic), x2 (magic), x3 (magic), x4 (magic) {}
This is very similar to your third option, and seems to be the natural C++ way of doing it.
A: A point not made by others is this:
I think it is unsafe to do this for Non-POD types. Ironically, adding the initialization into a constructor makes it non-pod. Therefore I propose a freestanding function that checks for POD-ness statically (sample uses c++0x type_traits but you could use Boost as well)
#include <iostream>
#include <type_traits>
template <typename T>
typename std::enable_if<std::is_pod<T>::value>::type* FeedFace(T& v)
{
static const unsigned char MAGIC[] = { 0xFE, 0xED, 0xFA, 0xCE };
unsigned char *me = reinterpret_cast<unsigned char *>(&v);
for( size_t ii = 0; ii < sizeof(T)/sizeof(unsigned char); ++ii )
me[ii] = MAGIC[ii % sizeof(MAGIC)/sizeof(unsigned char)];
}
struct Pod { char data[37]; };
struct NonPod : Pod { virtual ~NonPod() { } };
int main()
{
Pod pod;
FeedFace(pod);
NonPod nonpod;
// FeedFace(nonpod); // fails to compile (no matching function call)
return 0;
}
A: I assume this allows for nasty hacky stuff, like this:
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
int main(void)
{
struct SOME_STRUCT {
unsigned int x1;
unsigned int x2;
unsigned int x3;
unsigned int x4;
} foo;
fill(reinterpret_cast<unsigned int *>(&foo),
reinterpret_cast<unsigned int *>(&foo) + sizeof(foo) / sizeof(unsigned int),
(unsigned int)0xDEADBEEF);
cout << foo.x1 << endl;
cout << foo.x2 << endl;
cout << foo.x3 << endl;
cout << foo.x4 << endl;
return (0);
}
Basically abusing std::fill() with pointer casts.
A: You could reinterpret_cast this as a char* and then use std::generate with a predicate that rotates through the values you care about. If I get time later I'll try to sketch the code.
Also have you considered for example an LD_PRELOAD memory checking malloc library?
A: Here's another hacky method.
SOME_STRUCT() {
x1 = 0xFEEDFACE;
memmove(&(this->x2), this, sizeof(*this)-sizeof(x1));
}
A: Even if your memset() attempt did work, it makes an assumption about the structure packing and is therefore not guaranteed to be correct. There is no programmatic way to iterate through the members of a struct and assign them in C or C++. You will therefore need to be content with assigning the members individually. Having said that, if you feel that you are comfortable with the memory layout of the structure and don't need to worry about portable code, you can just as easily initialize it with a for loop.
unsigned int i, *ar = (unsigned int *)&my_struct;
for (i = 0; i < sizeof(my_struct) / sizeof(unsigned int); i++) {
ar[i] = 0xdeadbeef;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Newly Added Files Getting Permissions Error I'm running a local WAMP server and have just batch-processed a bunch of images in Photoshop, automatically saving them to a directory. When I try to access these images from my browser, I get a 403 error.
This has not yet happened to me on this server, though I have not yet done any batch processing.
I'm running Windows 7 Professional, and I've tried giving full-access to all users across-the-board for these images, but I'm still getting this same Apache error. Here's what my logs look like:
[Tue Sep 27 15:02:37 2011] [error] [client 127.0.0.1] (OS 5)Access is denied. : file permissions deny server access: C:/wamp/www/site/img/4142.jpg, referer: http://site.local/index.html
What am I doing wrong?
A: Turns out Windows was encrypting these files for some reason. This is what helped me solve this:
I noticed that all my file-names in Explorer were written in Green.
After a bit of digging around, it turns out they were encrypted, so I
turned encryption off on them and everything's good now!
In order to disable decryption, select your files, right-click and go
to properties, and under "General" go to "Advanced" and remove the
tick that says "Encrypt File Contents". The file-names will then turn
back to black, and everything was fine
Source: http://www.wampserver.com/phorum/read.php?2,43642
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C++ Windows add option to menu In windows, when you click the small icon in the upper left of the window, you get a menu with Move, Minimize, Maximize, and Close options.
Is there anyway I can add my own options to that menu?
A: Absolutely.
GetSystemMenu(hWindow, FALSE) gets you menu handle and you are free to modify it.
A nice way is to add a separator and append your additional items like "About...". ATL code snippet is here: http://www.assembla.com/code/roatl-utilities/subversion/nodes/trunk/FilterGraphSpy/GraphBuilderCallbackPropertySheet.h#ln1392 lines 1392-1396.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Getting the background color of a table row into a variable before changing it jQuery I have a code to change the color of a row of a table when I hover over it. I want to grab the background color of a row before it changes and then have it change back to its original color using that background color variable.
For some reason, even though I get the background color into the variable before the background color changes, the variable ends up being the new background color set by a CSS modifier.
$(document).ready(function() {
$(function() {
$('.rowHover tbody tr').hover(function() {
// Get color of row to replace it later
bgColor = $(this).css("background-color");
$(this).contents('td').css({'border-bottom': '1px solid #888'});
$(this).children().css('background-color', '#f1f1f1');
},
function() {
$(this).children().css('background-color', 'bgColor');
$(this).contents('td').css({'border-bottom': '1px solid #ccc'});
});
});
});
Do you guys have any idea how I can accomplish this? The table that I am having this hover effect on has different color rows and I don't want the background color information to be lost once the user takes their mouse off the row.
Thanks!
Chris
A: For one thing:
$(this).children().css('background-color', 'bgColor');
should be
$(this).children().css('background-color', bgColor);
You probably also want to move the declaration of bgColor out of the hover function and declare it with var.
A: Why not just use .toggleClass?
http://api.jquery.com/toggleClass/
You could accomplish everything your trying to do here with a couple specific style elements and to toggle on and off.
A: var bg=$(this).css("background-color"); //here you get the color
$(this).css("background-color","#FFFFF");// here you set the color
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: database design for user/reviewer in django database model i am kinda new to database design, but i would like to create three tables "User" and "Review" and "Topic" for a database in django.
I will try to explain it in detail here:
For example, I have User, Topic and Review models in models.py. one user can only write one review for one topic from other users.
let's say: Mike, John, Peter are the three Users.
Mike posted "Hello World" topic. John can only write one review for the topic "Hello World", Peter can also write one review for the same. John and Peter can not post another review for the same topic(they can only modify it). If Mike post another topic, John and Peter can post another review for the new topic. the same rule apply to other users.
please if you could, could you please provide some sample code for this issue? thanks a lot.
A: If you are trying to figure out how to set up your models.py, visit the django documentation, and look at Writing your first app (https://docs.djangoproject.com/en/dev/intro/tutorial01/). It goes from start to finish writing your first application and you will learn how the system works.
If you wanted more specifics for the paradigm of your case, here's what I would do. I would probably handle this in the view/template and submit/edit the review with Dajaxice calls to the database. If a review by the current user exists, it will show the data, if it doesn't it will be a blank entry that will use Dajax to submit the content. In the python method that the Dajax calls, you would try to find a review, and if one exists while attempting to add a new one, something went wrong and you can handle the error, otherwise it is saved for all to see.
For example, in models.py:
class User(models.Model):
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
class Review(models.Model):
title = models.CharField(max_length=64)
message = models.TextField()
topic = models.ForeignKey(Topic)
user = models.ForeignKey(User)
def __unicode__(self):
return self.title
class Topic
title = models.CharField(max_length=64)
message = models.TextField()
user = models.ForeignKey()
def __unicode__(self):
return self.title
in views.py:
class Post(models.Model): # This is defined a model, but not part of the data layer, it really is view code.
topic = None
your_review = None
other_reviews = None
def __unicode__(self):
return ''
def GetDetails(request):
posts = () # to be returned to and looped by the Template.
topics = Topic.objects.all().order_by('-posting_date') # posting_date descending.
for t in topics:
post = Post()
post.topic = t
post.your_review = Review.objects.filter(topic__id=t.id, user__id=<current_user_id>)
post.other_reviews = Review.objects.filter(topic__id=t.id, ~Q(user__id=<current_user_id>)
# Append to the posts array.
posts.append(post)
return render_to_response('index.htm', {'posts': posts}, context_instance=RequestContext(request))
in your index.htm:
{% if posts %}
{% for p in posts %}
<div>
<div class="title">{{ p.topic.title }}</div>
<div class="message">{{ p.topic.message }}</div>
<div class="other_reviews">
{% if p.other_reviews %}
{% for r in p.other_reviews %}
<div class="review_title">{{ r.title }}</div>
<div class="review_message">{{ r.message }}</div>
{% endfor %}
{% endif %}
<div>
<input type="text" value="{% if p.your_review %}{{ p.your_review.title }}{% endif %}">
</div>
<div>
<textarea>{% if p.your_review %}{{ p.your_review.message }}{% endif %}</textarea>
</div>
</div>
</div>
{% endfor %}
{% endif %}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C++ Windows remove maximize box I'm using these window styles when calling CreateWindow
WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX
This disables the maximize box, but is there any way I can completely remove it?
A: No easy way, but if you are going to draw the title bar yourself - in this case you can do it.
To give you an idea, this article Adding a 'Minimize to tray'-button to a Form's caption bar explains how to add a button. Removing standard button is about the same - customization of non-client area.
A: This will remove the close, minimize and maximize buttons from a Windows 7 panel I realize this is very (very) late in coming, but posted it here as it may help someone else with same problem.
void ClearButtons(void)
{
int index = WS_BORDER;
unsigned int a = (unsigned int)((WS_BORDER | WS_CAPTION) & (~WS_ICONIC));
LONG_PTR lPtr;
HWND hWnd = GetActiveWindow();
lPtr = GetWindowLongPtr(hWnd, index);
SetWindowLongPtr(hWnd, GWL_STYLE, a);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: jQuery $(this) Problem, wrong object i using this code to show a title
$(".line").mopTip({
'w':150,
'style':"overOut",
'get': $(this).attr("title")
});
but as title I get the title of page... what do I wrong?
A: You are using this inside the document window scope, that is why it returns the document title. To get the title of each line you have to loop over each one of them.
$(".line").each(function(){
//inside the each the scope of this refers to the current line
$(this).mopTip({
'w':150,
'style':"overOut",
'get': $(this).attr("title")
});
});
A: $(this).attr("title")
This gets the attribute "title" of the page, it always does when called in the document.
If the class "line" is the target, replace $("this") with $(".line")
A: For set content 'mopTip' use construction
... = $( setting.get ).html();
'get' - init in params.
And you code convert to
$( "Title of page" ).html();
In other words, in params 'get' must be selector... or function which return selector. Correct architecture of HTML-page. Or correct code of jQuery-plugin. Or wrap init to each().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OpenEJB alternate descriptors fail to work when using a jUnit test suite I have managed to get alternate descriptors to work with my unit-tests running on OpenEJB using stubs for dependant EJB components, when each test is executed on their own. But once I introduce a test suite, it seems that deployment descriptor is taken from the first test added to the suite.
Some code to explain it better. Beans under test are something like
@Stateless
@Local(A.class)
public class ABean implements A {
// Bean implementation, no dependencies
}
@Stateless
@Local(B.class)
public class BBean implements B {
@EJB
A aBean; // Dependency to ABean
// Rest of the implementation
}
And testcase for B (testcase for A is similar, except it does not set the property for using alternate descriptor)
public class BBeanTest {
private B bean;
@Before
public void bootContainer() throws Exception {
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.openejb.client.LocalInitialContextFactory");
props.put("openejb.altdd.prefix", "test"); // Use stubs
System.out.println("boot B: " + props);
context = new InitialContext(props);
bean = (B) context.lookup("BBeanLocal");
}
}
And as said, this all works just fine when executed alone. The alternate descriptor injects a stub implementation of A interface.
When using the following test suite, things start to fall apart.
@RunWith(Suite.class)
@Suite.SuiteClasses({
ABeanTest.class,
BBeanTest.class
})
public class MySuite {
// Empty on purpose, annotations do the trick
}
When running this suite, the alternate descriptor for testing B is not taken into use. Although, the output shows that at least the property is set before each test
boot A: {java.naming.factory.initial=org.apache.openejb.client.LocalInitialContextFactory}
boot A: {java.naming.factory.initial=org.apache.openejb.client.LocalInitialContextFactory}
boot A: {java.naming.factory.initial=org.apache.openejb.client.LocalInitialContextFactory}
boot B: {java.naming.factory.initial=org.apache.openejb.client.LocalInitialContextFactory, openejb.altdd.prefix=test}
boot B: {java.naming.factory.initial=org.apache.openejb.client.LocalInitialContextFactory, openejb.altdd.prefix=test}
If I reverse the order of loading tests to suite, i.e. add BBeanTest.class before ABeanTest.class, it'll use the alternate descriptor. As the ABean has no dependencies, this'll work fine in this case, but probably causes problems with bigger setups with multiple alternate descriptors.
Any pointers?
Thanks in advance.
EDIT Based on the log output, the container is actually booted only once for the first test as it takes approx. 2,5 seconds to execute while the others take around 0,001 seconds.
EDIT2 OpenEJB version is Apache OpenEJB 3.1.4 build: 20101112-03:32
A:
Based on the log output, the container is actually booted only once for the first test as it takes approx. 2,5 seconds to execute while the others take around 0,001 seconds.
As you rightly noticed, the initialization happens only once.
@RunWith(Suite.class)
@Suite.SuiteClasses({
ABeanTest.class,
BBeanTest.class
})
Hence in this case, both ABeanTest and BBeanTest ran within the same container instance, with the same initial context properties as set by ABeanTest.
In your case, since you need different settings for the two test classes, I think dumping the container instance at ABeanTest @AfterClass and using a new one in BBeanTest should do it.
This blog post shows how
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using int index where double is expected in C++ AMP retrict(direct3d) code Googling didn’t help much, has anyone used AMP?
In the code snippet below the cast from integer to double (double v = idx.x) leads to a “Failed to create shader” run time error.
I thought the restrict(direct3d) would have alerted me of things the GPU won’t be able to handle during compile time.
Is there an alternative to pow() – or will I have to write a loop to do that?
concurrency::array_view<double,1> prices = …
concurrency::parallel_for_each(
prices.grid, [=](index<1> idx) mutable restrict(direct3d) {
double v = idx.x;
prices[idx] = concurrency::pow(u, v);
…
A: please see our explanation of double support for GPUs on Windows, and also the C++ AMP math library
http://blogs.msdn.com/b/nativeconcurrency/archive/2012/02/08/math-library-for-c-amp.aspx
http://blogs.msdn.com/b/nativeconcurrency/archive/2012/02/07/double-precision-support-in-c-amp.aspx
If you still have a question, feel free to post back. Also please tag your questions with c++amp so we have a better chance of finding them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: join versus explicit in condition are there some valid reasons, in a Oracle db, to preferring in a generic query, a filter condition expressed by a join table , instead of a filter with an IN condition with a large number of elements (some hundreds). I mean if you can write something like
SELECT .... FROM t1
WHERE t1. IN (......) with 100-200 items
or if it is better to change it with
SELECT .... FROM t1
JOIN t2 ON t1. = T2.
where the t2 table contains the values needed for the filter
many thanks
Thanks for the answers
I try to explain the situation and my doubt
I have an user interface where the user can choose in a control many items (for example one or more people a list of professionals).
I can use directly this list adding this in a IN condition, that is
SELECT .... FROM t1 WHERE t1. IN (p1... p200)
but this solution, could raise some problems:
- if the selected items are a lot, then the string can exceed a limit of sql string (I remember in Oracle existed a limit of 4000 bytes)
- an IN condition with many valuesmay be inefficient
So an alternative solution can be
1. create a temporary table with the selected item
2. using a join between the temparary table and the main table
Usually the filling of a temporary table is fast and my question is if this second solution is more efficient of the first
A: The two queries are not functionally equivalent, so the question is somewhat odd--I can't imagine this comes up very often (if ever).
That said, if you have a table that contains exactly the rows that need to be filtered, a JOIN would be a more natural/standard way to handle it.
Is the idea in the first example is to query t2 to get all the values, then add them to a collection and generate an IN clause? If so, I would say this would be a very bad practice.
A: From what I see, there are two different questions.
a) Using a Static List/table.
If the (100-200) item list is a list of static values, for eg.Let's say a list of Countries or currencies, I think it would be better to add this to a static table/parameter table and change the query to use the table instead. If you need to track a new code/country etc. later, all you need to do later is insert a new code in the look up table.
Also, if there are other queries that use the same conditions (and there usually are), this look up table will promote re-use.
select * from t1 where id in (select id from t2);
and
select * from t1,t2
where t1.id = t2.id
are both equivalent and better than
select * from t1 where
id in ('USD','EUR'..... ); -- 100 to 200 items to track.
b) The choice of Join vs IN:
It really does not matter a lot. The final query that oracle executes will be the transformed version of your query which might evaluate to the same query in both cases.
You should see which of the two queries are more easier to read and convey the intentions correctly.
Useful Link : http://explainextended.com/2009/09/30/in-vs-join-vs-exists-oracle/
A: http://explainextended.com/2009/09/30/in-vs-join-vs-exists-oracle/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: watir-webdriver with firefox 6.0 see following error Errno::ECONNREFUSED Currently run 150 plus scenarios nightly approximately 5000 steps. I see the following error occur around 10 times in the 5000 steps. Not a lot, nor on the same step, however don't know what to do to fix. Currently wrapping in a rescue block and retrying to work around error.
Any suggestions would be great.
Thanks,
Jim
Environment:
Windows 2003 Server 32 bit
FireFox 6.0.2
Ruby 1.8.7
watir-webdriver 0.3.4
selenium-webdriver 2.7.0
watir-page-helper 0.3.0
Errno::ECONNREFUSED: No connection could be made because the target machine actively refused it. - connect(2)
Stack trace:
G:/Ruby187/lib/ruby/1.8/net/http.rb:560:in `initialize'
G:/Ruby187/lib/ruby/1.8/net/http.rb:560:in `open'
G:/Ruby187/lib/ruby/1.8/net/http.rb:560:in `connect'
G:/Ruby187/lib/ruby/1.8/timeout.rb:53:in `timeout'
G:/Ruby187/lib/ruby/1.8/timeout.rb:101:in `timeout'
G:/Ruby187/lib/ruby/1.8/net/http.rb:560:in `connect'
G:/Ruby187/lib/ruby/1.8/net/http.rb:553:in `do_start'
G:/Ruby187/lib/ruby/1.8/net/http.rb:542:in `start'
G:/Ruby187/lib/ruby/1.8/net/http.rb:1035:in `request'
./features/support/../../lib/pages/base_page_class.rb:37:in `initialize'
./features/support/env.rb:147:in `new'
./features/support/env.rb:147:in `on'
./features/support/env.rb:143:in `visit'
./features/step_definitions/login_steps.rb:32:in `/^A user logs into Connect using (new|existing) rid using correct environment dictated by environment variable$/'
features\ReservationDailyView.feature:6:in `And A user logs into Connect using existing rid using correct environment dictated by environment variable'
One thing to note, I am closing the browser after each scenario and opening it up again at start of the next scenario.
If I leave the browser open instead I get this error and my firefox instance is totally running out of memory 600,000+ K VM Size 700,000+ K
Timeout::Error: execution expired
Stack trace:
G:/Ruby187/lib/ruby/1.8/timeout.rb:64:in `rbuf_fill'
G:/Ruby187/lib/ruby/1.8/net/protocol.rb:134:in `rbuf_fill'
G:/Ruby187/lib/ruby/1.8/net/protocol.rb:116:in `readuntil'
G:/Ruby187/lib/ruby/1.8/net/protocol.rb:126:in `readline'
G:/Ruby187/lib/ruby/1.8/net/http.rb:2028:in `read_status_line'
G:/Ruby187/lib/ruby/1.8/net/http.rb:2017:in `read_new'
G:/Ruby187/lib/ruby/1.8/net/http.rb:1051:in `request'
G:/Ruby187/lib/ruby/1.8/net/http.rb:1037:in `request'
G:/Ruby187/lib/ruby/1.8/net/http.rb:543:in `start'
G:/Ruby187/lib/ruby/1.8/net/http.rb:1035:in `request'
./features/support/env.rb:148:in `call'
./features/support/env.rb:148:in `on'
A: Looks like you are running out of ephemeral ports. You might want to change settings in the registry to use more ports. Refer below
http://msdn.microsoft.com/en-us/library/aa560610(v=bts.20).aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: write formatted file I want to to write np.double to formatted file:
import numpy as np
a='12 45 87 34 65';
s=np.double(a.split())
fid=open('qqq.txt','wt')
fid.write('%5.1f %5.1f %5.1f %5.1f %5.1f ' %(s[0],s[1],s[2],s[3],s[4]))
fid.close()
Can this "write" row be written in a shorter way?
fid.write('%5.1f %5.1f %5.1f %5.1f %5.1f ' %(s[0],s[1],s[2],s[3],s[4]))
A: One way is this
In [48]: ''.join('%5.1f ' % n for n in s)
Out[48]: ' 12.0 45.0 87.0 34.0 65.0 '
Another way is
In [49]: ('%5.1f ' * len(s)) % tuple(s)
Out[49]: ' 12.0 45.0 87.0 34.0 65.0 '
A: fid.write(''.join(map('{:5.1f} '.format, s)))
A: This is the fastest way:
fid.write(''.join(map(lambda x: '%5.1f'%x , s.tolist())))
It's also worth noting that your method for reading the values in can be made much faster by doing this:
>>> import numpy as np
>>> a = '12 45 87 34 65'
>>> np.fromstring(a, sep=' ')
array([ 12., 45., 87., 34., 65.])
A: How about casting the doubles to strings first using a list comprehension, then creating the output row.
For example:
double_strs = ["%5.1f" % number for number in s]
fid.write( " ".join(double_strs) )
A: Quick and easy, my friend:
fid.write('%5.1f ' * len(s) % tuple(s))
A: Shortest I could come up with was:
"%5.1f"*len(s)%s
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I ask MySQL Workbench to submit queries asynchronously, when performing long operations (e.g. table alterations)? Albeit all its greatness, it is very annoying that MySQL Workbench 5.2 freezes each time it submits a query, instead of allowing it to be performed asynchronously.
It is not even possible to launch a second instance to do other tasks in the mean time.
Do you know if there is a setting somewhere to adjust this behaviour, or is it a "feature"?
A: Pretty sure it's a feature. You can run more than one query in a script. There are a lot of cases where you would want/need queries to run sequentially. I don't know of any query editor tools that allow for what you want.
If you're using php you could fire off several AJAX requests to pages that each ran one of the queries you need ran, but unless you are doing something like this often; it wouldn't be worth the time to set up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Call one constructor from the body of another in C# I need to call one constructor from the body of another one. How can I do that?
Basically
class foo {
public foo (int x, int y)
{
}
public foo (string s)
{
// ... do something
// Call another constructor
this (x, y); // Doesn't work
foo (x, y); // neither
}
}
A: You can't.
You'll have to find a way to chain the constructors, as in:
public foo (int x, int y) { }
public foo (string s) : this(XFromString(s), YFromString(s)) { ... }
or move your construction code into a common setup method, like this:
public foo (int x, int y) { Setup(x, y); }
public foo (string s)
{
// do stuff
int x = XFromString(s);
int y = YFromString(s);
Setup(x, y);
}
public void Setup(int x, int y) { ... }
A: To call both base and this class constructor explicitly you need to use syntax given below (note, that in C# you can not use it to initialize fields like in C++):
class foo
{
public foo (int x, int y)
{
}
public foo (string s) : this(5, 6)
{
// ... do something
}
}
//EDIT: Noticed, that you've used x,y in your sample. Of course, values given when invoking ctor such way can't rely on parameters of other constructor, they must be resolved other way (they do not need to be constants though as in edited code sample above). If x and y is computed from s, you can do it this way:
public foo (string s) : this(GetX(s), GetY(s))
A: this(x, y) is right, but it has to be before the start of the constructor body:
public Foo(int x, int y)
{
...
}
public Foo(string s) : this(5, 10)
{
}
Note that:
*
*You can only chain to one constructor, either this or base - that constructor can chain to another one, of course.
*The constructor body executes after the chained constructor call. There is no way to execute the constructor body first.
*You can't use this within the arguments to the other constructor, including calling instance methods - but you can call static methods.
*Any instance variable initializers are executed before the chained call.
I have a bit more information in my article about constructor chaining.
A: This is not supported - see Constructors in C#.
However, you can implement a common (private) method which you call from the different constructors...
A: I've ran into this problem a time or two myself... I ended up having to extract whatever logic I needed in that other constructor into a private void method and calling it in both places.
class foo
{
private void Initialize(int x, int y)
{
//... do stuff
}
public foo(int x, int y)
{
Initialize(x, y);
}
public foo(string s_
{
// ... do stuff
Initialize(x, y)
// ... more stuff
}
}
A: There is a note in description of MethodBase.Invoke in MSDN
If this method overload is used to invoke an instance constructor, the
object supplied for obj is reinitialized; that is, all instance
initializers are executed. The return value is null. If a class
constructor is invoked, the class is reinitialized; that is, all class
initializers are executed. The return value is null.
I.e. you can get Constructor's method by reflection and call it through Invoke in your new constructor's body. But I haven't try it. And, of course, this solution have a lot of drawbacks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "64"
}
|
Q: How to get filenames and line numbers in stack traces from embedded Mono? I'm embedding Mono into a C application, and it works fine, but debugging is more difficult than it should be because when I print a stack trace in the Mono code (for example, in response to an exception) all of the lines of the stack trace say they are located in ":0". I'd like to have filenames and line numbers appear correctly in the Mono stack traces.
I'm building the Mono components of the application with xbuild, and I'm using a debug build. mdb files are being generated, and I've placed them in the same directory as the Mono assemblies that I'm loading. When I'm initialized the Mono domain on the C side, I've tried calling mono_debug_init(MONO_DEBUG_FORMAT_MONO), and registering the domain with mono_debug_domain_create(), but it doesn't seem to have any effect. Has anyone gotten this to work?
A: Do you need stack traces for your c program or the mono program ?
For C: If your using gcc, have you enabled debug info '-g'.
You should check that your compilers LINE and FILE defines are
compatible with your current compiler.
For Mono: Did you compile with debug flags set '-debug'.
Hope this helps
/Tony
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to load child objects lazily with the Data Mapper pattern? If I have a fairly complex User model that I would like to use the Data Mapping pattern to load, how would I lazily load some of the more intensive bits of user info without allowing the User to be aware of the UserMapper?
For example - if the User model allows for an array of Address objects (and the User might have many of them, but not necessarily needed up front), how would I load those object if/when needed?
Do I make the User model aware of the AddressMapper?
Do I pass the User model BACK into the UserMapper which then hydrates only the Addresses?
Is there a better option?
A: Well, I have found the following clever pattern at one time, courtesy of Ben Scholzen, developer for the Zend Framework. It goes something like this:
class ModelRelation
implements IteratorAggregate
{
protected $_iterator;
protected $_mapper;
protected $_method;
protected $_arguments;
public function __construct( MapperAbstract $mapper, $method, array $arguments = array() )
{
$this->_mapper = $mapper;
$this->_method = $method;
$this->_arguments = $arguments;
}
public function getIterator()
{
if( $this->_iterator === null )
{
$this->_iterator = call_user_func_array( array( $this->_mapper, $this->_method ), $this->_arguments );
}
return $this->_iterator;
}
public function __call( $name, array $arguments )
{
return call_user_func_array( array( $this->getIterator(), $name ), $arguments );
}
}
Ben Scholzen's actual implementation is here.
The way you would use it, is something like this:
class UserMapper
extends MapperAbstract
{
protected $_addressMapper;
public function __construct( AddressMapper $addressMapper )
{
$this->_addressMapper = $addressMapper;
}
public function getUserById( $id )
{
$userData = $this->getUserDataSomehow();
$user = new User( $userData );
$user->addresses = new ModelRelation(
$this->_addressesMapper,
'getAddressesByUserId',
array( $id )
);
return $user;
}
}
class AddressMapper
extends MapperAbstract
{
public function getAddressesByUserId( $id )
{
$addressData = $this->getAddressDataSomehow();
$addresses = new SomeAddressIterator( $addressData );
return $addresses;
}
}
$user = $userMapper->getUserById( 3 );
foreach( $user->addresses as $address ) // calls getIterator() of ModelRelation
{
// whatever
}
The thing is though; this could get very slow, if the object graphs get very complex and deeply nested at some point, because the mappers all have to query their own data (presuming you are using a database for persistence). I experienced this when I used this pattern for a CMS to get nested Pages objects (arbitrarily deep child Pages).
It could probably be tweaked with some caching mechanism, to speed things up considerably though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Can I create my own AppDomain in a SilverLight application? I'm building a SilverLight application that is dynamically loading assemblies. I would also like to be able to unload them without closing out the current SilverLight application. However, the SilverLight AppDomain class appears to be missing a CreateDomain method.
If I can't create an AppDomain, is there an alternate mechanism to unload the assemblies ? I have an alternate strategy if they can't be unloaded, but unloading them when they are done would be the ideal approach.
A: You can't create additional AppDomains. A Silverlight application runs in its own specific AppDomain and thats it.
There is no way that I know of to unload assemblies that have been loaded. Are sure its necessary to do so? What happens if you don't bother?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: SQL Server import of file created through bcp I'm currently reviewing how to import a file created from bcp in SQL Server on one computer into my local SQL Server. This is a datafile I received from a 3rd party so I have no idea of the data structure etc. of the information. My SQL Server skills are quite new so please bear with me :) I've reviewd the bcp documents and attempted the following:
bcp TestDatabase in File.bcp -T
Results: Invalid Object name 'TestDatabase'
I created the test database TestDatabase and tried the query again but with the same response. I then added -Slocal and got a login timeout, seems like progress!
I removed the -T flag and tried varying combinations of usernames and passwords without any luck.
So I guess to start, is there an underlying issue I'm missing, syntax I'm not following etc. or should I just play around with the creds for my local SQL Server?
A: You need to specify the server, username, and table. Try this:
bcp TestDatabase..SomeTableName in File.bcp -S Server -U Username -P Password
A: If you look at the bcp Utility docs
-T means to use Integrated Security (your logged in account)
-Sis the server name parameter.
These two parameters are not interchangeable.
You can only use the -U and -P in place of -T if you have SQL Authentication turned on (and you shouldn't if you can avoid it)
Finally Chris Shain is correct. You need to specify Schema and table or ViewName, not just a DB Name, as well as the Server (-S)
Also from the documentation (and the point E.J. Brennan was making)
To import data into a table, you must either use a format file created
for that table or understand the structure of the table and the types
of data that are valid for its columns.
So you can't expect to just take a file and have bcp magically make a table for you. You need to use SSIS to help you or some other tool to do that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sort ArrayList of strings by length I want to order an ArrayList of strings by length, but not just in numeric order.
Say for example, the list contains these words:
cucumber
aeronomical
bacon
tea
telescopic
fantasmagorical
They need to be ordered by their difference in length to a special string, for example:
intelligent
So the final list would look like this (difference in brackets):
aeronomical (0)
telescopic (1)
fantasmagorical (3) - give priority to positive differences? doesn't really matter
cucumber (3)
bacon (6)
tea (8)
A: *
*String in Ascending order
class StringLengthListSort implements Comparator<String>{
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
/**
* @param args
*/
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
StringLengthListSort ss = new StringLengthListSort();
list.add("ram");
list.add("rahim");
list.add("ramshyam");
Collections.sort(list, ss);
System.out.println(list);
}
}
A: Use a custom comparator:
public class MyComparator implements java.util.Comparator<String> {
private int referenceLength;
public MyComparator(String reference) {
super();
this.referenceLength = reference.length();
}
public int compare(String s1, String s2) {
int dist1 = Math.abs(s1.length() - referenceLength);
int dist2 = Math.abs(s2.length() - referenceLength);
return dist1 - dist2;
}
}
Then sort the list using java.util.Collections.sort(List, Comparator).
A: You'd do this with the version of Collections.sort() that takes an explicit Comparator.
A: I have a similar problem solved by lambda expression:
listBeforeSorting.sort((s1, s2) -> s1.length() - s2.length());
This way, we will get sorted-by-length(ascending order) list.
A: Collections.sort(list, (a, b)->Integer.compare(a.length(), b.length()));
A: The use of a custom comparator is correct. This is one way to implement it:
Comparator c = new Comparator<String>()
{
public int compare(String s1, String s2) {
return Integer.compare(s1.length(), s2.length());
}
};
Collections.sort(results, c);
return results;
A: If you are using java 8 you can also try using this lambda
packages.sort(Comparator.comparingInt(String::length));
A: If you're using Java 8+ you can use a lambda expression to implement (@Barend's answer as) the comparator
List<String> strings = Arrays.asList(new String[] {"cucumber","aeronomical","bacon","tea","telescopic","fantasmagorical"});
strings.sort((s1, s2) -> Math.abs(s1.length() - "intelligent".length()) - Math.abs(s2.length() - "intelligent".length()));
A: simple with Java8 solution with Comparator and Method reference only:
Stream.of(list).flatMap(Collection::stream).sorted( Comparator.comparing( String::length)).collect(toList());
A: The shortest code for this-
public static void main(String... str) {
List.of("am", "I", "Best", "the").stream().sorted((a, b) -> a.length() - b.length())
.forEach(System.out::println);
}
A: List<String> list = Arrays.asList("geeksforgeeks", "geeksfor", "geeks");
Collections.sort(list, new Comparator<String>(){
public int compare(String s1, String s2){
return s1.length() - s2.length();
}
});
A: if you are using Kotlin you can use this code
var A = ArrayList<String>()
A.add("Alen")
A.add("Nymar")
A.add("Ronaldo")
A.add("Totianas")
A.add("Ted")
A.add("Sara")
Collections.sort(A, object : Comparator<String?> {
override fun compare(p0: String?, p1: String?): Int {
return (p1!!.length - p0!!.length)
}
})
System.out.println(A)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: How can you send the exact number of notification (the number next to your apps) to facebook instead of each time we make a request? I'm trying to have more control on the number we have next to our apps for the user, How can we just send the exact number to show instead of sending notification that increment that number each time.
Basically the current behavior is :
Friend ask for something or give me a gift it increase the number
If another friend send me something its increase the number.
When I log to the game all the counter is reset.
Wanted behavior :
When I log to the game and i go see only one friend on the counter for this friend is reset.
We are currently using facebook-java-api but we will probably merge to restfb soon.
But if you know how to do it in any language it will probably help.
A: The old dashboard api support the set_count method that can reset to 0 or put the value you want for your apps.
See http://developers.facebook.com/docs/reference/rest/dashboard.setCount/
However the facebook-java-api don't support setCount but the newer restFB does so we need to update our apps to the new api.
EDIT: Note that you and extend the BasicClient and create a custom IFacebook Method with facebook-java-api it`s not clean but it do the trick utils we upgrade to a new facebook api.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jpg looks different in firefox 6 and 7 on Windows 7 This website renders a background jpg differently than it did in Firefox 5 and below on Windows 7. I know that's a bit confusing so I'll outline it.
It works:
All versions of firefox, chrome, and IE on windows XP
All versions of chrome, IE, and firefox 5 and below on windows 7
Example:
It doesn't work:
Firefox 6 and above on Windows 7
Example:
The website is repeating the gradient jpg horizontally. It then tries to make the background color the same color as the bottom of that gradient.
Thanks again SO.
A: On my Windows 7 / FF6, the gradient looks pretty smooth:
so I think that what you're seeing is machine specific.
However, you might have better results by using a .GIF with a transparent bottom (to fade to background color) rather than a .JPG. In general, you've got better control over the colors in a .GIF because it's not a lossy format if you have few enough colors.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting rid of Plone4Artists Calendar - migration from Plone 3.3.5 to Plone 4.0.7 I am trying to remove P4Artists Calendar from a Plone 3.3.5 site, to upgrade it to Plone 4.0.7.
I ran a script to remove all interfaces from all objects, specifically:
'p4a.subtyper.interfaces.ISubtyped',
'p4a.calendar.interfaces.ICalendarEnhanced',
'p4a.calendar.interfaces.IPossibleCalendar',
'p4a.calendar.interfaces.ICalendarConfig',
'p4a.calendar.interfaces.IEventProvider',
'p4a.calendar.interfaces.IEvent',
'p4a.calendar.interfaces.IBasicCalendarSupport',
'p4a.calendar.interfaces.ICalendarSupport'
The script I am using uses zope.interfaces.noLongerProvides to get the objects rid of them. First, I do a catalog search and find the objects with the interface, and then noLongerProvides(object, interface).
After doing that, I am able to remove all of them interfaces, except for 'p4a.calendar.interfaces.IPossibleCalendar'. This interface seems to be applied to all of the Folders and Collections at the site, and when trying to remove them, I get an exception. Does anyone know more of this interface and what is the correct way of getting rid of it?
EDIT:
Here are the error messages generated by my script:
Exception at removeinterfaces for interface p4a.calendar.interfaces.IPossibleCalendar
Exception type: exceptions.ValueError
Exception value: Can only remove directly provided interfaces.
Exception traceback (starting next line):
File "remove-p4a.py", line 53, in removeinterfaces
noLongerProvides(obj, interface)
File "d:\plone-3.3.5-teste-20110927\zope2\lib\python\zope\interface\declarations.py",line 969, in noLongerProvides
raise ValueError("Can only remove directly provided interfaces.")
A: These seem to be interfaces that are only applied on startup via zcml. So the only way to remove them is to remove the product from your setup.
Source: http://svn.plone.org/svn/collective/p4a/p4a.plonecalendar/trunk/p4a/plonecalendar/configure.zcml
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to: From one string to another in a long list of strings Imagine a long string of characters:
"AATTAATCTATATATTGAAATGGGGCCCCAATTTTCCCAAATC ...."
I define 4 strings:
"AAT"
"ATG"
"TTT"
"ATC"
My mission is to find the "end point" for every string "AAT" in the long string of characters. My end points are the three last strings "ATG", "TTT", "ATC", which means I need to find the index for my start position "AAT" to my end position, which can be either "ATG", "TTT" or "ATC". I have been told to advance in steps of 3, but im not sure how to do it.
I have tried to do this:
open1=open(<text>)
u=open1.read()
string1="AAT
while True:
p=u.find(string1,p)
p=p+1
mylist.append(p)
print mylist
, which will print the locations of the strings "ATG" in my textfile. Im not sure how to move on from here. I guess i could find the positions of the other strings as well, but how do I create a function that starts from "ATG" and stops until it meets one of the end points??
Hope this is somehow understandable
A: You can do this with a regex:
>>> import re
>>> s = "AATTAATCTATATATTGAAATGGGGCCCCAATTTTCCCAAATC ...."
>>> [(m.start(), m.end()) for m in re.finditer('AAT.*?(?:ATG|TTT|ATC)', s)]
[(0, 8), (18, 34)]
re.finditer searches for multiple non-overlapping matches of a regex and returns a MatchObject for each one. The start() and end() methods of the match object give the start and end index of the matched string.
The regex searches for AAT followed by anything up to and including the first occurrence of ATG, TTT or ATC.
You may need to construct the regex dynamically if you do not know the start & end strings until the program runs - this is pretty simple to do:
start = "AAT"
end = ["ATG", "TTT", "ATC"]
regex = "%s.*?(?:%s)" % (start, '|'.join(end))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I use a mock when the code validates the types it receives I want to test the following code:
public IEnumerable<KeyValuePair<Fact, Exception>> ValidateAll()
{
//...do something
var invalidFacts = GetInvalidFacts();
//...do something
return duplicateFacts.Concat(invalidFacts);
}
private IEnumerable<KeyValuePair<Fact, Exception>> GetInvalidFacts()
{
var invalidFacts = Facts.Select(fact =>
{
try
{
fact.Validate();
return new KeyValuePair<Fact, Exception>(fact, null);
}
catch (FormatException e)
{
return new KeyValuePair<Fact, Exception>(fact, e);
}
catch (Exception e)
{
return new KeyValuePair<Fact, Exception>(fact, e);
}
}).Where(kv => kv.Value != null).ToList();
return invalidFacts;
}
Basically the test's objective is to verify that all objects that exist within the "Facts" IEnumerable will call their Validate method. Since I'm not interested to test the code within those objects, there are already lots of tests that do that, I want to inject a list of fake facts. I'm using MOQ to create the fakes.
So my unit test looks like this:
[TestMethod]
public void ValidateAll_ValidateMethodIsInvokedOnAllFacts_WhenCalled()
{
var anyFactOne = new Mock<Fact>(); //Fact is an abstract class.
anyFactOne.Setup(f => f.Validate());
var dataWarehouseFacts = new DataWarehouseFacts { Facts = new Fact[] { anyFactOne.Object, FactGenerationHelper.GenerateRandomFact<SourceDetails>() } };
dataWarehouseFacts.ValidateAll();
}
Now I'm getting an exception because the code is actually validating the kind of Facts that can be injected to the DataWarehouseFacts class, like so:
public IEnumerable<Fact> Facts
{
get
{
.....
}
set
{
var allowedTypes = new []
{
typeof(ProductUnitFact),
typeof(FailureFact),
typeof(DefectFact),
typeof(ProcessRunFact),
typeof(CustomerFact),
typeof(ProductUnitReturnFact),
typeof(ShipmentFact),
typeof(EventFact),
typeof(ComponentUnitFact),
typeof(SourceDetails)
};
if(!value.All(rootFact => allowedTypes.Contains(rootFact.GetType())))
throw new Exception ("DataWarehouseFacts can only be set with root facts");
ProductUnitFacts = value.OfType<ProductUnitFact>().ToList();
FailureFacts = value.OfType<FailureFact>().ToList();
DefectFacts = value.OfType<DefectFact>().ToList();
ProcessRunFacts = value.OfType<ProcessRunFact>().ToList();
CustomerFacts = value.OfType<CustomerFact>().ToList();
ProductUnitReturnFacts = value.OfType<ProductUnitReturnFact>().ToList();
ShipmentFacts = value.OfType<ShipmentFact>().ToList();
EventFacts = value.OfType<EventFact>().ToList();
ComponentUnitFacts = value.OfType<ComponentUnitFact>().ToList();
SourceDetails = value.OfType<SourceDetails>().Single();
}
}
What would be the best way to get around this validation?
Thanks.
A: The two obvious methods that leap to mind are:
*
*Add Fact to your list of allowed types.
*Moq one of your allowed fact types rather than the base Fact class itself. (I presume that your Validate() method is overrideable.)
Another slightly more complicated option would be to inject your list of allowed types at test time, assuming you have control over the DataWarehouseFacts class. That might look something like this:
class DWF
{
static IEnumerable<Fact> defaultAllowedFacts = new Fact[] { ... }
IEnumerable<Fact> allowedFacts;
public DWF() : this(defaultAllowedFacts) { ... }
internal DWF(IEnumerable<Fact> allowed)
{
// for testing only, perhaps
this.allowedFacts = allowed;
}
...
}
Then just delete that var allowedTypes = new [] bit and use this.allowedFacts instead.
A: I would leverage Type.IsAssignableFrom
E.g. instead of saying
allowedTypes.Contains(v.GetType())
I'd say
allowedTypes.Any(t => t.IsAssignableFrom(v.GetType()))
That way you can pass proper subclasses just as well as the exact matching types. Perhaps, maybe, that was what you were after with the typelist itself?
A: First of all I want to thank both ladenedge (I did gave a +1 to his answer) and sehe for their answers. Even though it was not exactly what I was looking for they are interesting ideas to keep in mind.
I couldn't just add the Fact class to the list of allowed types since that would have opened the door for lots of classes that should not be allowed; there are about 30 classes inheriting from it.
So what I ended up doing was to extract the code from the set part of the Facts property in their own methods and made one of them protected virtual, like so:
public IEnumerable<Fact> Facts
{
get
{
...
}
set
{
ValidateReceived(value);
ExtractFactTypesFrom(value.ToList());
}
}
protected virtual void ValidateReceived(IEnumerable<Fact> factTypes)
{
if (factTypes == null) throw new ArgumentNullException("factTypes");
var allowedTypes = GetAllowedFactTypes();
if (!factTypes.All(rootFact => allowedTypes.Contains(rootFact.GetType()))) throw new Exception("DataWarehouseFacts can only be set with root facts");
}
private IEnumerable<Type> GetAllowedFactTypes()
{
var allowedTypes = new[]
{
typeof (ProductUnitFact),
typeof (SequenceRunFact),
typeof (FailureFact),
typeof (DefectFact),
typeof (ProcessRunFact),
typeof (CustomerFact),
typeof (ProductUnitReturnFact),
typeof (ShipmentFact),
typeof (EventFact),
typeof (ComponentUnitFact),
typeof (SourceDetails)
};
return allowedTypes;
}
private void ExtractFactTypesFrom(List<Fact> value)
{
ProductUnitFacts = value.OfType<ProductUnitFact>().ToList();
FailureFacts = value.OfType<FailureFact>().ToList();
DefectFacts = value.OfType<DefectFact>().ToList();
ProcessRunFacts = value.OfType<ProcessRunFact>().ToList();
SequenceRunFacts = value.OfType<SequenceRunFact>().ToList();
CustomerFacts = value.OfType<CustomerFact>().ToList();
ProductUnitReturnFacts = value.OfType<ProductUnitReturnFact>().ToList();
ShipmentFacts = value.OfType<ShipmentFact>().ToList();
EventFacts = value.OfType<EventFact>().ToList();
ComponentUnitFacts = value.OfType<ComponentUnitFact>().ToList();
SourceDetails = value.OfType<SourceDetails>().Single();
}
That way I was able to create a DataWarehouseFactsForTest and override the ValidateReceived method so it wouldn't do anything:
public class DataWarehouseFactsForTests : DataWarehouseFacts
{
protected override void ValidateReceived(IEnumerable<Fact> factTypes)
{}
}
That way I was able to to use Moq to create the Facts and verify the code within the private GetInvalidFacts method. For example:
[TestMethod]
public void ValidateAll_ReturnsADictionaryWithAFormatException_WhenOneOfTheFactsValidationThrowsAFormatException()
{
var anyFactOne = new Mock<ProductUnitFact>();
var anyFactTwo = new Mock<SequenceRunFact>();
var anyFactThree = new Mock<SourceDetails>();
anyFactOne.Setup(f => f.Validate()).Throws(new FormatException());
var dataWarehouseFacts = new DataWarehouseFactsForTests { Facts = new Fact[] { anyFactOne.Object, anyFactTwo.Object, anyFactThree.Object } };
var result = dataWarehouseFacts.ValidateAll().ToList();
anyFactOne.Verify(f => f.Validate(), Times.Exactly(1));
anyFactTwo.Verify(f => f.Validate(), Times.Exactly(1));
anyFactThree.Verify(f => f.Validate(), Times.Exactly(1));
Assert.AreEqual(1, result.Count());
Assert.AreEqual(typeof(FormatException), result.First().Value.GetType());
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: FlowDecision Designer components My question is about the Flow Decision designer object. Can I change the sides that the "True", "False", and Inputs come from? Currently, True is always to the left, False on the Right, and input is at the top or the bottom. Naturally some flows become very "Messy" because of this. I know that I can always 'Not' the condition to switch the true and false, but that is sloppy. Thanks!
A: No, there is no way to swap those around.
Personally I would prefer the true option to go down and false to go sideways, that is the way I learned to draw flowcharts way back when I started programming but this is the way it is.
I suggest adding a request on User Voice here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jQuery .hide doesn't hide elements fast enough When I use .hide() with jQuery, it doesn't hide elements fast enough. I can see them all loading and being organized for another script that is also running. It looks really awkward.
Is there anyway to make .hide() actually hide elements before the document loads? I don't want to do display:none since this would hurt SEO.
A: jQuery can't do anything before the document completes at least a partial load - that's how the ready() function works. However, you could use plain JavaScript executed before the jQuery ready function to hide the element you want hidden. Search engines typically ignore JavaScript, so you'd be safe.
Since we're talking about JavaScript... is the "stuff" you're hiding loaded in by scripts or is it static (in the context of the loaded document)? If the content is being loaded in by Ajax, I'm not sure a search engine would see it anyway, in which case you might just want to hide it with CSS and be done with it.
A: When are you calling the hide() method? On the document ready? Maybe adding the call to the hide() method directly after inserting the html for the element?
Something like:
<div id="element">your element</div>
<script type="text/javascript"> $("#element").hide(); </script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Hooking WinAPI functions called from DLL I have a DLL file library.dll which contains a function foo. The function foo calls a WinAPI function goo. I wrote an application that calls foo from library.dll. The problem is that I want to override the call to goo function by my own function hoo I declared in the application (not in the DLL).
How can I hook the call to goo function? I'm not looking for a global hook, I just want to override calls made by application I wrote.
A: There is library called Detours provided by Microsoft Research: http://research.microsoft.com/en-us/projects/detours/. You can use it to re-route any API call in Windows.
It does exactly what you describe -- instead of calling into Win32 API, your function gets called. Within that function you are free to do what you want, e.g. you can call again to the original Win32 function or you can return failure code right away or anything you like.
Express edition of Detours is free, but it is limited for non-commercial use on x86 architecture.
A: Patch the import descriptor for goo in library.dll's import address table. IAT patching is a well known hooking technique for intercepting function calls between two PE modules.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Group functions fine by themselves, but not when added together? I have a mysql query that looks something like this:
SELECT
SUM(reg_yr) AS reg_yr_total,
SUM(spot_as_reg_yr) AS spot_as_reg_yr_total
FROM foo
WHERE bar
GROUP BY baz
ORDER BY reg_yr_total
which works just fine. if I want to change the ORDER BY clause to be reg_yr_total+spot_as_reg_yr_total however, I get an error stating Reference 'reg_yr_total' not supported (reference to group function).
Why can I use each of these columns by themselves, but as soon as I try to add the two together it fails? Is there a way around this?
A: If you don't want to SELECT another column, try the following:
SELECT
SUM(reg_yr) AS reg_yr_total,
SUM(spot_as_reg_yr) AS spot_as_reg_yr_total
FROM foo
WHERE bar
GROUP BY baz
ORDER BY SUM(reg_yr) + SUM(spot_as_reg_yr)
A: Try summing them to another virtual column:
SELECT
SUM(reg_yr) AS reg_yr_total,
SUM(spot_as_reg_yr) AS spot_as_reg_yr_total,
(reg_yr_total + spot_as_reg_yr_total) AS reg_yr_total
FROM foo
WHERE bar
GROUP BY baz
ORDER BY reg_yr_total
This is untested, but should work.
If this is an incorrect answer, please tell me so and I will gladly remove it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: getting the frame rate of a currently playing video I was wondering - is there a way to get the frame rate at which an Android videoView is currently playing. I looked into the documentation of the VideoView class but it was to no avail. Is there some other way to do this?
Thanks.
A: Yes you can.
VideoView extends View, so you'd make your own YourVideoView class which extends VideoView, implement onDraw method, call super.onDraw there, and also performing your FPS computation there.
So you can count yourself how many times in secound onDraw is called for VideoView. Display it wherever you need (on screen / logcat / ...).
Counting framerate is another story, you can look for simple example here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Visual c++ 6.0: error C2065: 'PWR_CString' : undeclared identifier This error for the following: C:\software\CATS\includes\Commun\xml_transfer.cpp(1527) : error C2065: 'PWR_CString' : undeclared identifier
CString s1; // Empty string
I did include:"stdafx.h" , "resource.h"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: programming language recommendation for Expressing Network Configs I would like to see if there is a language for expressing network configuration. I can use M4 and YAML for macro-fying some of the configs but with conditional statements, they seem to break down.
Any recommendations?
Thanks,
Neel
A: My NCD programming language may be just what you're looking for.
Here's a sample program for configuring a wired network interface with DHCP (same one as from the wiki):
process lan {
# Set device.
var("eth0") dev;
# Wait for device, set it up, and wait for network cable.
net.backend.waitdevice(dev);
net.up(dev);
net.backend.waitlink(dev);
# DHCP configuration.
# net.ipv4.dhcp() will block here until it obtaines an IP address.
# Note that it will only obtain the IP address, and *not* assign it;
# we do that with a separate command below.
net.ipv4.dhcp(dev) dhcp;
# Check IP address - make sure it's not local.
# If you have other reserved subnets around, check for those too.
ip_in_network(dhcp.addr, "127.0.0.0", "8") test_local;
ifnot(test_local);
# Assign IP address, as obtained by DHCP.
net.ipv4.addr(dev, dhcp.addr, dhcp.prefix);
# Add default route, as obtained by DHCP.
net.ipv4.route("0.0.0.0", "0", dhcp.gateway, "20", dev);
# Configure DNS servers, as obtained by DHCP.
net.dns(dhcp.dns_servers, "20");
}
Be sure to read the entire NCD wiki page. NCD is capable of much more then what it may look like at first (say, conditionals, loops, dynamic configuration of unknown devices...). It can even do some non-network-related tasks, like report input device (keyboard, mouse) events.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Android - read all mobile numbers into a List Can someone give me a correct example on how to load all MOBILE numbers saved on the phone into a List, Array or whatever is appropriate? All the examples I have found are either depreciated or do not work. Sorry to ask for a freebie like this but I am getting desparate, I can't find anything!
Here's what I have, it doesn't work. The Log.d doesn't happen.
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, "DISPLAY_NAME = '" + People.NAME + "'", null, null);
if (cursor.moveToFirst()){
Log.d("Number", "Cursor moved");
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phones = cr.query(People.CONTENT_URI, new String[]{People.NAME, People.NUMBER}, null, null, People.NAME + " ASC");
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
switch (type) {
case Phone.TYPE_MOBILE:
//Add to the list of numbers
Log.d("Number", number);
break;
}
}
}
Thank you!
A: Joel,
Cursor phones = cr.query( ContactsContract.CommonDataKind.Phone.NUMBER, .... );
And you need to compare with ContactsContract.CommonDataKind.Phone.TYPE = 2.
Thank you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: java.lang.UnsatisfiedLinkError: Java cannot find my dll's? I am developing a program that calls R functions from Java using JRI/rJava. I was coding the program in NetBeans on another machine, which was working fine (i.e. able to run the code). I have since then moved to another machine and have been running into problems.
The exact error message I am seeing is this:
Cannot find JRI native library!
Please make sure that the JRI native library is in a directory listed in java.library.path.
java.lang.UnsatisfiedLinkError: E:\R\R-2.13.1\library\rJava\jri\jri.dll: The specified path is invalid
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1807)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1732)
at java.lang.Runtime.loadLibrary0(Runtime.java:823)
at java.lang.System.loadLibrary(System.java:1028)
at org.rosuda.JRI.Rengine.<clinit>(Rengine.java:19)
at com.rjava.test.rtest.main(rtest.java:64)
Java Result: 1
I have read the FAQs for JRI/rJava, and have been scouring the internet for fixes, but have made no progress. Here is what I have done so far:
*
*Created an environment variable called R_HOME: "E:\R\R-2.13.1"
*Added "%R_HOME%\bin\x64" to the PATH environment variable
*Added "%R_HOME%\library\rJava\JRI" to the PATH environment variable (this is where jri.dll is located)
*Set the required jar files as compile time libraries (JRI.jar, JRIEngine.jar, REngine.jar) in NetBeans
*set the following VM options in NetBeans: : -Djava.library.path=E:\R\R-2.13.1\library\rJava\jri (This is where jri.dll is located)
I have restarted my computer to make sure that the changes stick.
To make sure I configured things correctly, I ran the following in the command line:
java -cp E:\R\R-2.13.1\library\rJava\jri\JRI.jar;E:\R\R-2.13.1\library\rJava\jri\examples rtest
And the example java files ran fine. I'm beginning to think my new machine just hates me.
A: The message indicates that it the path E:\R\R-2.13.1\library\rJava\jri\jri.dll is invalid. Are you sure that path exists? Also, is E a mapped drive that is mapped to a path that has spaces in it? I'm not sure if the spaces are the issue, but it eliminates one issue. I would try just putting the dll in C:\ or somewhere very simple and seeing if it can find it there as a simple test.
Also verify that the -Djava.library.path is being passed as you think it is (you can check that with visualvm or jconsole).
A: You could try this:
-Djava.library.path=E:\R\R-2.13.1\library\rJava\jri -cp E:\R\R-2.13.1\library
\rJava\jri;E:\R\R-2.13.1\library\rJava\jri\JRI.jar;E:\R\R-2.13.1
\library\rJava\jri\examples
The reason I say this is that, perhaps the .dll also needs to be in the classpath as well as the library path in order for the classloader to load it? Its probably not true, but worth trying. Also is "rJava" correct? Other than that, it looks to me like your doing it right.
A: To locate JRI installed with rJava, use system.file("jri",package="rJava") in R.
set that path to your path (environment variables in windows),
restart your netbeans. and try to run your program again
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Xcode 4 and iPad2 splash screen issue Thank you for reading this.
I created a brand new project in Xcode 4 (Window based kind) and tried to get the splash screens working.
If I click on the blue icon of my project (top of the project hierarchy) and then click on "Target/Project", I see that I can drag and drop two launch images to use them as splash screens.
My portrait picture is a 768 x 1004 px png file and my landscape picture is a 1024 x 748 png file.
When I drop the portrait picture, everything looks fine but when I do the same with the landscape picture, I have a big yellow exclamation point that appears.
If I hover my mouse pointer long enough on the exclamation point, it says:"
the size of the launch image for iPad in landscape mode does not match
the recommended size of 1024 x 748 pixels
".
Just to be sure, I verified in Photoshop and a mac buit-in application and both do say my image is a png file of 1024 x 748.
I tried another picture and got the same message. I created a new Xcode project and also got the same message.
When I build and run the minimalistic project in the iPad simulator, I get the portrait splash vertically in Portrait orientation (ok) and the portrait splash horizontally in Landscape mode (not ok).
What can I do?
Just for you to know:
When I go to the Project-Info.plist, I do see "Supported Interface Orientations (iPad)" and it has 4 items:
*
*Portrait (Bottom home button)
*Portrait (top home button)
*Landscape (left home button)
*Landscape (right home button)
I also copied manually the 5 following files at the root of the project but it didn't help
*
*Default-Landscape~ipad.png
*Default-Portrait~ipad.png
*Default-LandscapeLeft~ipad.png
*Default-LandscapeRight~ipad.png
*Default-PortraitUpsideDown~ipad.png
Whatever I do, it just recognizes the portrait picture and uses them for each orientation...
At this point, my project is very minimal and is just made of an appDelegate "h" and "m" file and a "mainWindow.xib" file, that's it (I didn't edit any of them yet).
Any clue?
Thank you.
A: Edit: try making the image 748x1024 instead of 1024x748 as suggested here.
From SO question - iPad Launch image landscape:
If you're on Xcode 4.0.2+ then the landscape iPad launch image needs
to be 748 * 1024. This is how it works in one of my apps.
Also, Upgrading to xcode 4.1 will fix the big yellow warning you get even when an image is the correct size.
The warning is also different based on your plist setting for "Status Bar is initially hidden" or not. If it's hidden, then it needs to be 1024x768, it not hidden then 1024x748... etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Postgres 9.1 Replication vs MySQL Replication Since Postgres now has built-in replication/clustering/HA support, how does it compare to the built-in features and functionality of MySQL replication/clustering/HA?
What are the PRO/CONs of Postgres vs MySQL related strictly to replication/clustering/HA capabilities?
Please don't make this a blastfest on one product over another. I'm simply looking for an objective matrix of features & support of the two products related strictly to replication/clustering/HA abilities.
UPDATE:
I found this very old comparison matrix. If someone updated it and included MySQL - that would answer my question.
--------------------------------------------------------------------------------------------------------------------------------------------
Product | License | Replication Method | (A)Synch? | Connection Pooling (Y/N) | Load Balancing (Y/N) | Query Partioning (Y/N) |
--------------------------------------------------------------------------------------------------------------------------------------------
MYSQL | | | | | | |
--------------------------------------------------------------------------------------------------------------------------------------------
POSTGRES | | | | | | |
--------------------------------------------------------------------------------------------------------------------------------------------
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: RequestMapping on presence of one of multiple parameters I have a Spring3 controller in which I'm using the @RequestMapping annotation. I know I can use the params value to route based on the the presence or lack of a url parameter, but is there a way to route based on the presence of one of two parameters?
Ideally I'd have something like the following:
@RequestMapping(value="/auth", params="error OR problem")
public ModelAndView errorInAuthenticate()
Where I route to errorInAuthenticate if the parameters error OR problem exist.
A: Unfortunately @RequestMapping params are combined using AND, not OR. (Source)
A: simply map both params as not required and test them:
@RequestMapping(value="/auth")
public ModelAndView errorInAuthenticate(@RequestParam(value="error", required=false) String errorParam,
@RequestParam(value="problem", required=false) String problemParam) {
if(errorParam != null || problemParam != null) {
//redirect
}
}
A: You can do it using Spring AOP and create a surrounding aspect for that request mapping.
Create an annotation like the following:
public @interface RequestParameterOrValidation{
String[] value() default {};
}
Then you can annotate your request mapping method with it:
@GetMapping("/test")
@RequestParameterOrValidation(value={"a", "b"})
public void test(
@RequestParam(value = "a", required = false) String a,
@RequestParam(value = "b", required = false) String b) {
// API code goes here...
}
Create an aspect around the annotation. Something like:
@Aspect
@Component
public class RequestParameterOrValidationAspect {
@Around("@annotation(x.y.z.RequestParameterOrValidation) && execution(public * *(..))")
public Object time(final ProceedingJoinPoint joinPoint) throws Throwable {
Object[] args= joinPoint.getArgs();
MethodSignature methodSignature = (MethodSignature) thisJoinPoint.getStaticPart().getSignature();
Method method = methodSignature.getMethod();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
RequestParameterOrValidation requestParamsOrValidation= method.getAnnotation(RequestParameterOrValidation.class);
String[] params=requestParamsOrValidation.value();
boolean isValid=false;
for (int argIndex = 0; argIndex < args.length; argIndex++) {
for (Annotation annotation : parameterAnnotations[argIndex]) {
if (!(annotation instanceof RequestParam))
continue;
RequestParam requestParam = (RequestParam) annotation;
if (Arrays.stream(params).anyMatch(requestParam.value()::equals) && args[argIndex]!=null) {
// Atleast one request param exist so its a valid value
return joinPoint.proceed();
}
}
}
throw new IllegalArgumentException("illegal request");
}
}
Note:- that it would be a good option to return 400 BAD REQUEST here since the request was not valid. Depends on the context, of course, but this is a general rule of thumb to start with.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Selenium and iframe I have an iframe that gets loaded when i click on a tab on a page. When i use Firebug to look at the iframe on IE8, all i see is:
iframe id=tabContextFrame class=contextFrame contentEditable=inherit src=/xyz.dt?forward=show&layouttype=NoHeader&runid=1234 name=tabContextFrame url=/xyz.dt?forward=show&layouttype=NoHeader&runid=1234 scrolling=auto
and that's it.The hierarchy below the iframe can't be seen. I want to click on a link within the iframe. To find the elements within the iframe, I did a selenium.click("on the tab that loads the iframe") and then selenium.getHtmlSource(). From this source, I can at least locate my link of interest. I did a selenium.click("//span[text()='Link']") but it doesn't seem to do anything. Any ideas please?
Here is the code:
selenium.click("//span[text()='tab that loads iframe']");
Thread.sleep(5000);
selenium.selectFrame("tabContextFrame");
selenium.mouseOver("//span[text()='Link']");
selenium.mouseDown("//span[text()='Link']");
selenium.mouseUp("//span[text()='Link']");
Thread.sleep(5000);
selenium.selectFrame("null");
A: I'm guessing you are using Selenium 1.0. Have you looked at Selenium 2.0 and WebDriver. I found the following and it worked for me:
Q: How do I type into a contentEditable iframe? A: Assuming that the
iframe is named "foo":
driver.switchTo().frame("foo");
WebElement editable = driver.switchTo().activeElement();
editable.sendKeys("Your text here");
Sometimes this doesn't work, and this is because the iframe
doesn't have any content. On Firefox you can execute the following
before "sendKeys":
((JavascriptExecutor) driver).executeScript("document.body.innerHTML = '<br>'");
This is needed because the iframe has no content by default:
there's nothing to send keyboard input to. This method call inserts an
empty tag, which sets everything up nicely.
Remember to switch out of the frame once you're done (as all further
interactions will be with this specific frame):
driver.switchTo().defaultContent();
I found this on http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions
A: Use driver.switchTo().defaultContent(); first then do your operation
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: html form button to stop multiple submissions I have this form that submits to work.php.
What I want to do is disable the submit button when the form is submitted, then re-enable it after 5 seconds or so, so I don't get multiple posts.
How can I do this?
Also, if I press the enter key in one of the text boxes while the submit button is not clickable then it will redirect me to work.php which don't want to happen.
<form method="post" action="work.php">
<strong>Message:</strong>
<input type="text" id="message" name="message" class="message" />
<input type="submit" id="submit" onClick="this.value='Processing form';this.disabled=true;if(Submitting()){this.form.submit()}else{this.value='Submit';this.disabled=false;}" value="Submit" />
</form>
A: <form id="your-form">
<input type="submit" id="submit" onclick="doSubmit(this);" value="Submit" />
</form>
<script>
function doSubmit(el) {
var frm = document.getElementById('#your-form');
el.value = 'Processing...';
el.disabled = true;
frm.submit();
setTimeout(function(el) {
el.value = 'Submit';
el.disabled = false;
}, 5000);
}
</script>
This is one way to do it. There are several others.
A: You don't need to worry about this. If the user spams the form submit in any way (clicking submit or hitting enter), only one complete request is sent to the server - every time the submit is triggered, it resets the POST and starts again.
Do note that using JavaScript to stop this behaviour is pretty bad, considering it's incredibly easy to disable JS and spam away, which is one of the reasons why browsers only allow one POST submission at a time.
If you're using AJAX (which you haven't specified), then you should use @drrcknlsn's answer.
A: If your using Ajax you use the "Ajax Manager Plugin." It will prevent double requests.
That way you don't have to worry about a person hitting enter or the submit button multiple times. Only one request will go through until it is finished(but by then I would assume a success message and clearing of the form would happen)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Asynchronous WCF Services in WPF - events I am using WCF services asynchronously in a WPF application. So I have class with all the web service. The view models call the method in this proc, which in-turn calls the web service.
So the view Model code looks like this:
WebServiceAgent.GetProductByID(SelectedProductID, (s, e)=>{States = e.Result;});
And the WebService agent looks like:
public static void GetProductByID(int ProductID, EventHandler<GetProductListCompletedEventArgs> callback)
{
Client.GetProductByIDCompleted += callback;
Client.GetProductByIDAsync(ProductID);
}
Is this a good approach? I am using MVVM light toolkit. So the View Model static, so in the lifetime of the application, the view model stays. But each time the view model calls this WebServiceAgent, I think I am registering an event. But that event is not being unregistered.
Is this a problem. Lets say the view Model is called for 20 - 30 times. I am inserting some kind of memory leak?
A: Some helpful information, based on the mistakes I learned from myself:
*
*The Client object seems to be re-used all the time. When not unregisering event handlers, they will stack up when future invokations of the same operations finish and you'll get unpredictable results.
*The States = e.Result statement is executed on the event handler's thread, which is not the UI dispatcher thread. When updating lists or complex properties this will cause problems.
*In general not unregistering event handlers when they are invoked is a bad idea as it will indeed cause hard to find memory leaks.
You should probably refactor to create or re-use a clean client, wrap the viewmodel callback inside another callback that will take care of unregistering itself, cleaning up the client, and invoking the viewmodel's callback on the main dispatcher thread.
If you think all this is tedious, check out http://blogs.msdn.com/b/csharpfaq/archive/2010/10/28/async.aspx and http://msdn.microsoft.com/en-us/vstudio/async.aspx. In the next version of C# an async keyword will be introduced to make this all easier. A CTP is available already.
A: Event handlers are death traps and you will leak them if you do not "unsubscribe" with "-=".
One way to avoid is to use RX (Reactive Extensions) that will manage your event subscriptions. Take a look at http://msdn.microsoft.com/en-us/data/gg577609 and specifically creating Observable by using Observable.FromEvent or FromAsync http://rxwiki.wikidot.com/101samples.
A: This is unfortunaltely not a good approach.
I learned this the hard way in silverlight.
Your WebserviceAgent is probably a long-life object, whereas the model or view is probably short-life
Events give references, and in this case the webservice agent, and wcf client a reference to the model. A long lifeobject has a reference to a short life object, this means the short life object will not be collected, and so will have a memory leak.
As Pieter-Bias said, the async functionality will make this easier.
Have you looked at RIA services? This is the exact problem that RIA services was designed to solve
A: Yes, the event handlers are basically going to cause a leak unless removed. To get the near-single line equivalent of what you're expressing in your code, and to remove handlers you're going to need an instance of some sort of class that represents the full lifecycle of the call and does some housekeeping.
What I've done is create a Caller<TResult> class that uses an underlying WCF client proxy following this basic pattern:
*
*create a Caller instance around an existing or new client proxy (the proxy's lifecycle is outside of the scope of the call to be made (so you can use a new short-lived one or an existing long-lived one).
*use one of Caller's various CallAsync<TArg [,...]> overloads to specify the async method to call and the intended callback to call upon completion. This method will choose the async method that also takes a state parameter. The state parameter will be the Caller instance itself.
*I say intended because the real handler that will be wired up will do a bit more housekeeping. The real callback is what will be called at the end of the async call, and will
*
*check that ReferenceEquals(e.UserState, this) in your real handler
*if not true, immediately return (the event was not intended to be the result of this particular call and should be ignored; this is very important if your proxy is long lived)
*otherwise, immediately remove the real handler
*call your intended, actual callback with e.Result
*Modify Caller's real handler as needed to execute the intended callback on the right thread (more important for WPF than Silverlight)
The above implementation should also have separate handlers for cases where e.Error is non-null or e.Cancelled is true. This gives you the advantage of not checking these cases in your intended callback. Perhaps your overloads take in optional handlers for those cases.
At any rate, you end up cleaning up handlers aggressively at the expense of some per-call wiring. It's a bit expensive per-call, but with proper optimization ends up being far less expensive than the over-the-wire WCF call anyway.
Here's an example of a call using the class (you'll note I use method groups in many cases to increase the readability, though HandleStuff could have been result => use result ). The first method group is important, because CallAsync gets the owner of that delegate (i.e. the service instance), which is needed to call the method; alternatively the service could be passed in as a separate parameter).
Caller<AnalysisResult>.CallAsync(
// line below could also be longLivedAnalyzer.AnalyzeSomeThingsAsync
new AnalyzerServiceClient().AnalyzeSomeThingsAsync,
listOfStuff,
HandleAnalyzedStuff,
// optional handlers for error or cancelled would go here
onFailure:TellUserWhatWentWrong);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How can I add additional item templates to an extended WPF treeview I'm trying to set up a Treeview descendent class that can be used as a common template for
all Treeview instances in my application, but with additional formatting and templates for each instance.
For the base, I have a UserControl that descends from Treeview, with the common styles and a single standard data template
<TreeView x:Class="BaseTreeView" ... >
<TreeView.ItemContainerStyle> ... </TreeView.ItemContainerStyle>
<TreeView.Resources>
<HierarchicalDataTemplate ItemsSource="{Binding Children}" DataType="{x:Type local:BaseTreeViewItem}">
<TextBlock Text="{Binding Caption}" />
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
Then in each window, I use this extended Treeview and add additional data templates for the specific TreeviewItems I'm displaying.
e.g.
<Window x:Class="Window1" ... >
...
<BaseTreeView ItemsSource="{Binding RootTreeItems}" >
<MyTreeView.Resources>
<HierarchicalDataTemplate ItemsSource="{Binding Children}" DataType="{x:Type ExtendedTreeViewItem1}">
<StackPanel Orientation="Horizontal">
<Image Source="Images/Image1.png" />
<TextBlock Text="{Binding Caption}" />
</StackPanel>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type ExtendedTreeViewItem2}">
<StackPanel Orientation="Horizontal">
<Image Source="Images/Image2.png" />
<TextBlock Text="{Binding Caption}" />
</StackPanel>
</DataTemplate>
</MyTreeView.Resources>
</BaseTreeView>
...
</Window>
This compiles fine, but at runtime I get an error
"'Set property 'System.Windows.ResourceDictionary.DeferrableContent' threw an exception.' Line number '27' and line position '59'."
"Cannot re-initialize ResourceDictionary instance."
Is there any way around this, or can someone suggest a better way to set up a base treeview template and multiple descedent versions.
A: You could try moving your templates to the <Window.Resources> instead of <MyTreeView.Resources>
If it doesn't work, maybe using a DataTemplateSelector suits your case best. You can create a DataTemplateSelector class like this:
public class ExtendedTreeViewTemplateSelector : DataTemplateSelector
{
public DataTemplate ExtendedTreeViewItem1Template { get; set; }
public DataTemplate ExtendedTreeViewItem2Template { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item is ExtendedTreeViewItem1)
return ExtendedTreeViewItem1Template;
if (item is ExtendedTreeViewItem2)
return ExtendedTreeViewItem2Template;
}
}
And then use it in your XAML like this:
<Window x:Class="Window1" ... >
<Window.Resources>
<HierarchicalDataTemplate x:Key="extendedTreeViewItem1Template" ItemsSource="{Binding Children}" DataType="{x:Type ExtendedTreeViewItem1}">
<StackPanel Orientation="Horizontal">
<Image Source="Images/Image1.png" />
<TextBlock Text="{Binding Caption}" />
</StackPanel>
</HierarchicalDataTemplate>
<DataTemplate x:Key="extendedTreeViewItem2Template" DataType="{x:Type ExtendedTreeViewItem2}">
<StackPanel Orientation="Horizontal">
<Image Source="Images/Image2.png" />
<TextBlock Text="{Binding Caption}" />
</StackPanel>
</DataTemplate>
<selector:ExtendedTreeViewTemplateSelector x:Key="treeViewTemplateSelector"
ExtendedTreeViewItem1Template="{StaticResource extendedTreeViewItem1Template}"
ExtendedTreeViewItem2Template="{StaticResource extendedTreeViewItem2Template}" />
</Window.Resources>
...
<BaseTreeView ItemsSource="{Binding RootTreeItems}"
ItemTemplateSelector={StaticResource treeViewTemplateSelector}" />
...
</Window>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Relationship Set disappears in Core Data with multiple contexts I have an an entity A which has a to-many relationship with entity B along with the respective inverse relationship.
I add B objects to A like this:
NSMutableSet *bSet = [aObj mutableSetValueForKey:@"B"];
for (bData in some array) {
[ create and insert bObj within SAME context ];
[bSet addObject:bOjb];
}
[context insertObject:aObj];
[context save:&err];
This works fine and dandy in a one-thread situation or in a 2-thread situation using one NSManagedObjectContext across both threads (which is definitely BAD, but I was just testing).
But once I try creating the necessary second NSManagedObjectContext for the background thread that inserts the A & B objects, that relationship info doesn't seem to persist. The A and B objects are definitely there, but no relationship between them.
Here's how I create the 2nd MOC:
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:[(AppDelegate*) [UIApplication sharedApplication].delegate persistentStoreCoordinator]];
Note that I access the Core Data in the main thread, and insert them in the background thread. I've used mergeChangesFromContextDidSaveNotification in the main thread's context from a NSManagedObjectContextDidSaveNotification, but that didn't seem to do anything.
UPDATE:
It looks like this was an issue where I was releasing the MOC too early/improperly. Simply commenting out the release caused the issue to go away, but a little rewrite the memory management for the context fixed it correctly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Listing registration profiles in the admin interface of django-registration with django-nonrel I've successfully installed django-nonrel, and django-registration on Google app engine, thanks for this very useful article. However I have difficulties on listing the registration profiles ( visiting /admin/registration/registrationprofile ) in the admin interface, I got the following error, just in the deployed version.
File "/base/python_runtime/python_lib/versions/1/google/appengine/datastore/datastore_query.py", line 2324, in __query_result_hook
str(exc) + '\nThe suggested index for this query is:\n' + yaml)
NeedIndexError: no matching index found.
The suggested index for this query is:
- kind: registration_registrationprofile
properties:
- name: __key__
direction: desc
visiting /admin/registration/registrationprofile/add is just fine.
I had the same issue with one of my apps, but after a while it started working, don't know why.
What can be the problem?
EDIT
Strange, but now it's working. I guess it was because of my browser cache, or google servers needed more time to activate that index, don't know, maybe I'll try to find out later.
A: Error says everythig. You must define primary key in registration_registrationprofile as index in index.yaml file:
indexes:
- kind: registration_registrationprofile
properties:
- name: __key__
- direction: desc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pressing submit, nothing happens (jQuery AJAX Forms) Example: dev.alphenweer.nl
When someone clicks on a link, the form gets loaded, they fill out the form, and press a button to submit it. But when someone presses the button, nothing happends. Why is that? What is wrong with my code?
For example, click on "REQUEST API AGAIN", and then just fill SOMETHING in. Nothing happens. Why?
A: You need to use
live. Which will result in
$('#api_reg_submit').live('click', function(){...
This happens because the button, which you set click event on, is not in DOM at start aka when its ready, but its added later. If you had the button outside and loaded only inputs it would work like you have it now. Hope it makes sense :)
A: There's no <form> surrounding the input elements, so they're just a random textbox and button sitting on a webpage. There's no element with an id of api_req_submit on the page either, so the click function you're trying to add has nowhere to go.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How does JavaScript distinguish between objects? I have wriiten
document.createElement("p");
document.createElement("p")
How does Javascript intepreter knows do distinct between those two?
Id ? ( what is the Js property )? maybe something else ?
A: In this particular case:
document.createElement("p");
document.createElement("p")
the JavaScript runtime doesn't worry about the elements at all, because you didn't save the values returned. They're thrown away.
If you had written,
var p1 = document.createElementById('p');
var p2 = document.createElementById('p');
well then you've got two separate variables, and so you're keeping track of the difference.
It's important to be aware that the JavaScript interpreter itself doesn't really care too much about your DOM nodes. That's not really it's business. If you call methods and create objects, it's your problem to keep track of them.
A: Let's pick another real-life example: How does a human distinguish one orange from another one, in a basket? I look inside the basket, and notice that there're multiple orange-coloured, ball-shaped items
The JavaScript interpreter internally keeps track of the created objects. When an object isn't referred by anything (variables), the built-in Garbage Collector destroys the object.
A: It doesn't. createElement returns the object reference but if you don't assign it to anything or directly use it, it's lost.
var firstp = document.createElement("p");
var secondp = document.createElement("p");
Then you can assign an id or whatnot:
firstp.id = "first";
Keep in mind though, that this is not in the DOM yet. You have to insert it somewhere before it can be seen by the user/found with getElementById.
For that you can do something like this:
document.body.appendChild(firstp);
A: It doesn't. When you call document.createElement(), you create an element and it's inserted into the DOM. JavaScript can then grab certain p elements by ID, for example, or grab other p (and other) elements with getElementsByClassName().
If you'd assigned the returned values to variables, you'd be able to keep track of which one was which by referencing different variables. This is you distinguishing between them, not JavaScript, though.
A: You can refer to them by their index in the array of elemnts:
document.getElementsByTagName('p')[0]
You can assign id to them
document.getElementsByTagName('div')[0].id = 'first'
document.getElementsByTagName('div')[1].id = 'second'
And refer to them by id
document.getElementById('first')
It is up to you how you do it really...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: LINQ Joining 2 tables I have two tables in the database one contains a list of all possible grocery values. For Example
Milk
Cheese
Bread
Meat
the second table contains Items from Grocery that are selected. For Example:
Milk
Cheese
I want a result that has all possible grocery items with Milk and Cheese selected.
Any ideas?
Here are the tables.
The GroceryList Table:
ID INT PK
Description Varchar(50)
The ShoppingList Table:
ID INT PK
GroceryListID int FK to GroceryList.ID
So the resulting Entity would be all items from GroceryList and if they exist in ShoppingList then selected is marked as true:
ShoppingList.ID
Grocerylists.Description
Selected
A: Edit: Still sounds like you want to do a left join. In your case:
var LINQResult = from g in Datacontext.GroceryList
from s in DataContext.ShoppingList
.Where(c=>c.ID == g.ID)
.DefaultIfEmpty()
select new {
g.ID,
g.Description,
s.ID // Will be null if not selected.
};
For more examples:
Left Join on multiple tables in Linq to SQL
A: Based on understanding you can do something like this
//first get the list of product which satisfy your condition
var ids = (from p ShoppingList
select p.GroceryListID ).ToList();
//second filter the Grocery products by using contains
var myProducts = from p in GroceryList
where ids.Contains(p.ID)
Select p;
or
if you want to get info about join than this image would help you
Inner Join
Outer Join
Try to understand and which may help you to resolve your query
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: OpenGL constant color I read in this Apple documentation (under the header "Avoid Storing Constants in Attribute Arrays") it says that if a model's vertices all have the same colour then colour shouldn't be a vertex attribute. What do they mean by "OpenGL ES 2.0 applications can either set a constant vertex attribute…"?
My question is, is it better to use a uniform value for colour, and call have a uniform call and draw call for every object? Or to have the vertex attribute anyway, but draw everything in one fell swoop. (Or, a constant vertex attribute if that's better).
Basically, is the advantage of drawing everything at once only the lack of overhead of multiple function calls?
Just to get a sense of it, say I were drawing 1000 circles every frame, each a different colour and having 40 vertices. Which would be better in that case?
A: The answer depends on how much stuff you are drawing in a single draw call. If you have an object of 30,000 vertices, where all of them have the same color, then you're wasting a lot of per-vertex reads (assuming that the color data makes your per-vertex data bigger. It may not). However, if you're talking about quad rendering, where each quad has a different color, then the uniform update overhead and multiple draw calls is going to kill your performance.
Note that there are methods for instancing under OpenGL, which allows you to have per-instance data as well as per-vertex data. But this generally doesn't buy much until you have multiple thousands of instances, and more than 100 vertices in the model.
For your specific example, there's no way to know which would be faster. You'd have to benchmark it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WCF Parameter not Passed I call the following local WCF Client service.
var Key = 1000;
FormServiceClient formService = new FormServiceClient("WSHttpBinding_IFormService");
And I call
formService.GetCaseData(Key);
The Key value is not getting passed into the service via my asp.net application.
If I used WCF Test Client then there is no problem working.
When I hit this step--> formService.GetCaseData(Key);
The Key parameter has a value of 1000.
Once I get to the Service side, it has a value of 0.
I noticed that if I call an method that returns a simple POCO class it works fine. I am trying to return an Entity Domain object. Could this be the problem?
A: I have experienced the same problem. Although I have not yet found a solution, anyone reading this may want to unclick 'show my code only'. If you do you may see a System.Runtime.Fx.Async.Thunk.UnhandledExceptionFrame(AsyncResult) or something similar. If this is the case, and you are using ASP.NET with .NET 4.0+ the problem is likely a synchornization conflict between WCF and ASP that occurs only in debugging, and only when passing data through interfaces. However I know of no solutions to this problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Accepting a Request URL is incorrect? This started happening over the last weekend that FB notification page is no longer embedding the [app_id] in the acceptance URL and throwing a 404 when clicked on the "request" link on this page:
(Sent Today)
http://apps.facebook.com/224695104250620/?request_ids=161817803905540&ref=notif
Notice that how it is different than what we used to get earlier (and the working version):
(Sent September 21)
http://apps.facebook.com/piratesapp/?request_ids=10150329048068535&ref=notif
I've gone back and re-checked Facebook documentation on "Requests Dialog":
http://developers.facebook.com/docs/reference/dialogs/requests/
and found that it clearly states the working version:
http://apps.facebook.com/[app_name]/?request_ids=[request_ids]
None of the app settings changed on our part and all on a sudden, the strange # started showing up in place of [app_name]. We've verified that it's not app_id as it doesn't match with any of our registered apps. The behavior appears to be the same across apps, apps across different Facebook developer accounts and so on.
Is this a bug? Should I file a bug with Facebook? I wanted to check with the experts here before logging a bug.
Appreciate a prompt response on this.
A: Ok looks like this is a bug:
https://developers.facebook.com/bugs/209695662429264
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HTML5 image transformation library, no flash I found http://www.magmypic.com/, the concept is super nice, but flash is SO OUT... i like and think if it's possible to do it in html5. Do you know library that can do it, or site that show how-to
thanks in advance
A: I don't think you need 'HTML5' so do something similar, the first step is placing an image as a background of a div and using CSS3 'background-position' and 'background-size' take care of moving and scaling the image. Then just slap transparent PNG on top for the magazine text. You could also use CSS3 instead of a PNG to make the magazine graphics with @font-face and something like google web fonts or font squirrel for custom fonts.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575862",
"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.