text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Is There Any Advantage in Passing a UI wrapper to a view Most of the MVC samples I have seen pass an instance of the view to the controller like this
public class View
{
Controller controller = new Controller(this);
}
Is there any advantage to passing a class which provides access to just the the properties and events the controller is interested in, like this:
public class UIWrapper
{
private TextBox textBox;
public TextBox TextBox
{
get {return textBox;}
}
public UIWrapper(ref TextBox textBox)
{
this.textBox = textBox;
}
public class View
{
UIWrapper wrapper = new UIWrapper(this);
Controller controller = new Controller(wrapper)
}
A: There's a good series of posts by Jeremy Miller in relation to MVC/MVP triad. In particular you might be interested in part 6 it goes into detail about the comms between the view and the controller.
A: It depends on your architecture. If you're all on the same tier, then you can go without the wrapper, though I'd probably pass an interface that View implements to Controller. Functionally, and from a coupling perspective, the interface approach and the wrapper approach are equivalent.
However, if UI is on one tier and the controller is on another, then passing/serializing an entire View object might be awkward, or even inefficient. In cases like this, you might want to pass a DTO back and forth, which would be easier to serialize and probably more efficient.
I tend to favor the DTO approach, since if your architecture scales up, all you need to do is serialize and de-serialize.
Also, if your View is complicated and has lots of pieces of data to pass back and forth with the Controller, you might start fighting the Long Parameter List smell with Introduce Parameter Object anyway, which is essentially a DTO.
One more thing for you to chew on: for a complicated View, Controller will end up needing to map lots of pieces of data to various text boxes and other UI controls in the View. The same thing in reverse: View ends up grabbing data from a lot of controls and passing them to various methods in your Controller.
I like separating these two. I give Views a DTO and I consider it the View's job to know where to "plug in" and "plug out" each piece of data. Both View and Controller are now coupled only to the DTO, as far as data is concerned anyway.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I represent features v. tasks in FogBugz 6? In FogBugz 6, how do I represent the concepts of a "feature" versus a "task"? As defined by Joel Spolsky, the owner of Fog Creek Software (which makes FogBugz), a feature is essentially a user-visible capability. To estimate the time to implement a feature, the developer should break the implementation into short tasks (2 days max) to ensure they think about each step.
FogBugz has only cases. I can't tell whether they're supposed to correspond to features or tasks. Some FogBugz documentation indicates that each case is a task, which is fine except there is no way to group all the tasks for a given feature together. This is especially odd given that, before FogBugz 6, Joel advocated using a spreadsheet with that grouped all the tasks for each feature. But his own software doesn't appear to meaningfully support that grouping.
I realize that the Joel article I reference includes a disclaimer pointing to a later article. However, the later article does not settle this issue, in fact it doesn't discuss features versus tasks at all, which is surprising given how well Joel advocates for those concepts in the first article.
A: Responding to AviD's comment/question to Joel:
So, if you have 10 new features coming
in the next version, with each feature
needing 5 tasks to implement, you
recommend creating 10 releases? And
how do I define that these are the
features/"releases" that are to be
included in the upcoming release?
Here is how we dealt with this specific problem in our development process:
*
*First, we made a regular release schedule: monthly internal releases and quarterly external releases. This schedule never changes but task assignment / feature completion does. This is hugely important in terms of simplifying our inter-human communication: don't try to argue with the calendar.
*Major features ("10 new features" in your example) are turned into cases (e.g., case 101 to case 110).
*Each task that is a sub-component of a major feature also gets created as a sub-case with a description of what makes this chunk of work an important part of the larger picture. Previously, in Fogbugz 6, we used the "See also" feature by allowing it to search the text for us ("This is a sub-component of case 101" for example). This was effectively the same thing but less aesthetic.
*Now that we've broken down the work to its finest level of usefulness, we bring the actual developers into the discussion. Each task and major feature is individually assigned to a particular developer.
*The developer determines when they can get their assigned work done by picking the appropriate internal release date that they think they can commit to.
*At this point, we have a rough sketch of what will get done for each release. Further refinements continue as the working people actually estimate the hours that they'll need to do the work, enabling evidence-based scheduling, etc.
For AviD's question, though, he would have the release-assignment problem solved by step 5 above.
However, I think point 6 is the most interesting as that's where you really get a solid schedule. For example, if developers are having trouble estimating a larger task, they break it down into sub-cases even further. Notice how my assessment of "finest level of usefulness" can differ (perhaps greatly) from the person who really needs to get the work done.
This is also a time when a developer can reach out to someone else and say "I can do most of this but it would really help if person X could help me with this little piece Y." This is actually where I get most of my development tasking: I personally sit in multiple places during this process, from large-scale planning meetings to little fiddly tasks that no-one else has time to do.
PS: Making it a personal goal to get this answer rated higher than Joel's.... ;-)
PPS: My original response is now overcome by events since Fogbugz 7 has lovely sub-tasks. Program managers love those reports.
A: For FogBugz 6.0 and earlier:
Make a case for each work item (task). FogBugz calls them "Features," only to distinguish them from bugs, but you do want one case for each task.
The best way to group a bunch of tasks is to make a Release (Fix-For) and assign all of the tasks to that release.
A: You may have better luck asking your questions in the FogBugz Discussion Forum
A: We use a combination of projects in order to accomplish your grouping goals. We also commonly setup a project "parking" Wiki where links to development cases, technical documentation, systems requirements, user documentation, external links to resources etc. can all be placed. It provides a good "one-stop-shop" for everything related to that project.
As part of that Wiki, we would then setup two specific projects. One in relation to the large overall goals/outlines similar to what might correspond to your Project Management charts/whatnot. One in relation to the development tasks of each feature as they are broken down into the smaller and more manageable chunks. You can then, as was mentioned use case linking to both reference the "master" cases in the other project as well as reference the project Wiki itself so that you can quickly and easily get back to all of your project related information which is conveniently in one spot.
You can accomplish a pile of different organizational structures using FogBugz, you just have to approach things a little differently sometimes in order to hit each and every situation.
Hope that helps.
A: haha, that article has a disclaimer, but I understand what you are saying.
We use Fogbugz and the only 'Feature' that I am aware of is under category and I don't think you can associated it with sub-tasks.
You can type in 'Case N' is the feature for this task if you just wanted to reference it in the case text.
That kind of stuff sound like is lies more in the project management domain instead of software used to track bugs.
A: thats a good question, i have asked that myself, too..
we currently test-drive fogbugz for 45 days in a group of 5 developers, and we currently create a "release" for major features. in fact we do not release it, but multiple releases together when something is ready.
there should definately be some sort of advanced task grouping in fogbugz.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: KVM/QEMU network TAP problems with libvirt I'm trying to use libvirt with virsh to manage my kvm/qemu vms. The problem I have is with getting it to work with public IPs. The server is running ubuntu 8.04.
libvirt keeps trying to run it as:
/usr/bin/kvm -M pc -m 256 -smp 3 -monitor pty -no-acpi \
-drive file=/opt/virtual-machines/calculon/root.qcow2,if=ide,boot=on \
-net nic,vlan=0,model=virtio -net tap,fd=10,vlan=0 -usb -vnc 127.0.0.1:0
Which boots, but does not have any network access (pings go nowhere). Running it without fd=10 makes it work right, with kvm creating the necessary TAP device for me and networking functioning inside the host. All the setup guides I've seen focus on setting up masquerading, while I just want a simple bridge and unfiltered access to the net (both the guests and host must use public IPs).
Running ifconfig on the host gives this, the bridge is manually setup in my /etc/network/interfaces file. :
br0 Link encap:Ethernet HWaddr 00:1e:c9:3c:59:b8
inet addr:12.34.56.78 Bcast:12.34.56.79 Mask:255.255.255.240
inet6 addr: fe80::21e:c9ff:fe3c:59b8/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:3359 errors:0 dropped:0 overruns:0 frame:0
TX packets:3025 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:180646 (176.4 KB) TX bytes:230908 (225.4 KB)
eth0 Link encap:Ethernet HWaddr 00:1e:c9:3c:59:b8
inet6 addr: fe80::21e:c9ff:fe3c:59b8/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:6088386 errors:0 dropped:0 overruns:0 frame:0
TX packets:3058 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:680236624 (648.7 MB) TX bytes:261696 (255.5 KB)
Interrupt:33
Any help would be greatly appreciated.
A: I followed the bridged networking guide at https://help.ubuntu.com/community/KVM and have the following in /etc/network/interfaces:
auto eth0
iface eth0 inet manual
auto br0
iface br0 inet static
address 192.168.0.10
network 192.168.0.0
netmask 255.255.255.0
broadcast 192.168.0.255
gateway 192.168.0.1
bridge_ports eth0
bridge_fd 9
bridge_hello 2
bridge_maxage 12
bridge_stp off
I have not changed any libvirt network settings and my kvm images are booted like:
/usr/bin/kvm -M pc -no-kqemu -m 256 -smp 1 -monitor pty -boot c -hda \
/libvirt/apt.img -net nic,macaddr=00:16:3e:77:32:1d,vlan=0 -net \
tap,fd=11,script=,vlan=0 -usb -vnc 127.0.0.1:0
I then specify the static network settings in the kvm image as normal. Has all worked ok since I followed the guide.
I do have the following settings in my xml files in /etc/libvirt/qemu/ though under devices:
<interface type='bridge'>
<mac address='00:16:3e:77:32:1d'/>
<source bridge='br0'/>
</interface>
A: i guess your tap device should be shown in ifconfig.
run "brctl show "
it will show bridge and tunnel device connection.
you may have to put iptable entry show that all the packets will be routed through bridge
iptables -I INPUT -i br0 -j ACCEPT
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is there a plugin in Eclipse for applying tags to files? I have searched for such a plugin but haven't found any. I need a facility to "tag" my java files. Similar to tagging on stackoverflow.
I want to be able to group my files based on projects/tasks I wam working on. Mylyn helps a little but it dynamically changes the context (list of resources associated with a task) based on various factors.
I just want a basic tagging facility for all the files in my workspace.
A: http://taggerplugin.sourceforge.net/
A: There is a plugin called Resource Tagger which may do what you are looking for. Report back on what you find works please.
A: I would recommend tagging them with tag interfaces -- these will persist across checkins and different workspaces.
Something like
public interface Observer {} // no required methods
and then when you want to tag a class as an observer, you do
public class SomeClass implements Observer {...}
In eclipse, you can then open a hierarchy view on the tag interface (Observer in this instance) and see everything that implements it.
You could also use annotations for tagging as well.
In both cases, you could also write code that reflects your code base to find tagged classes.
A: Since you're already using Mylyn, try right-clicking on the file you want to "tag" and select "mark as landmark". The landmarked file will then stay put in your context.
A: A little bit late , but you can try to use eclipse workingset to group source files.
Create as many working set as you need and add files to each of them; after that you juste have to use explorer select or deselect workingSet option to switch between group of files
HTH !
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to do a "where in values" in LINQ-to-Entities 3.5 Does anybody know how to apply a "where in values" type condition using LINQ-to-Entities? I've tried the following but it doesn't work:
var values = new[] { "String1", "String2" }; // some string values
var foo = model.entitySet.Where(e => values.Contains(e.Name));
I believe this works in LINQ-to-SQL though? Any thoughts?
A: Update: found out how to do this. And EF will generate the appropriate SQL on the database. I'm not sure if this is for EF4 only but I got the tip from Entity Framework 4.0 Recipes
var listOfIds=GetAListOfIds();
var context=CreateEntityFrameworkObjectContext();
var results = from item in context.Items
where listOfIds.Contains(item.Category.Id)
select item;
//results contains the items with matching category Ids
This query generates the correct in clause on the server side. I haven't tested it with EF 3.5 but it does work with EF4.
NB: The values passed into the in clause are NOT parameters so make sure you validate your inputs.
A: It is somewhat of a shame that Contains is not supported in Linq to Entities.
IN and JOIN are not the same operator (Filtering by IN never changes the cardinality of the query).
A: Contains is not supported in EF at this time.
A: FYI:
If you are using ESql you are able to use in operation.
I don't have VS 2008 With me but code should be something like following:
var ids = "12, 34, 35";
using (context = new Entites())
{
var selectedProducts = context.CreateQuery<Products>(
String.Format("select value p from [Entities].Products as p
where p.productId in {{{0}}}", ids)).ToList();
...
}
A: For the cases when you want to use expressions when querying your data, you can use the following extension method (adapted after http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/095745fe-dcf0-4142-b684-b7e4a1ab59f0/):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Data.Objects;
namespace Sample {
public static class Extensions {
public static IQueryable<T> ExtWhereIn<T, TValue>(this ObjectQuery<T> query,
Expression<Func<T, TValue>> valueSelector,
IEnumerable<TValue> values) {
return query.Where(BuildContainsExpression<T, TValue>(valueSelector, values));
}
public static IQueryable<T> ExtWhereIn<T, TValue>(this IQueryable<T> query,
Expression<Func<T, TValue>> valueSelector,
IEnumerable<TValue> values) {
return query.Where(BuildContainsExpression<T, TValue>(valueSelector, values));
}
private static Expression<Func<TElement, bool>> BuildContainsExpression<TElement, TValue>(
Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values) {
if (null == valueSelector) { throw new ArgumentNullException("valueSelector"); }
if (null == values) { throw new ArgumentNullException("values"); }
ParameterExpression p = valueSelector.Parameters.Single();
// p => valueSelector(p) == values[0] || valueSelector(p) == ...
if (!values.Any()) {
return e => false;
}
var equals = values.Select(value => (Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue))));
var body = equals.Aggregate<Expression>((accumulate, equal) => Expression.Or(accumulate, equal));
return Expression.Lambda<Func<TElement, bool>>(body, p);
}
}
class Program {
static void Main(string[] args) {
List<int> fullList = new List<int>();
for (int i = 0; i < 20; i++) {
fullList.Add(i);
}
List<int> filter = new List<int>();
filter.Add(2);
filter.Add(5);
filter.Add(10);
List<int> results = fullList.AsQueryable().ExtWhereIn<int, int>(item => item, filter).ToList();
foreach (int result in results) {
Console.WriteLine(result);
}
}
}
}
Using the extensions is really easy (as you can see in the sample). To use it on a database object, assuming you are filtering a table called "Product" by more than one id, you could do something like that:
class Product {
public int Id { get; set; }
/// ... other properties
}
List<Product> GetProducts(List<int> productIds) {
using (MyEntities context = new MyEntities()) {
return context.Products.ExtWhereIn<Product, int>(product => product.Id, productIds).ToList();
}
}
A: Yes it does translate to SQL, it generates a standard IN statement like this:
SELECT [t0].[col1]
FROM [table] [t0]
WHERE [col1] IN ( 'Value 1', 'Value 2')
A: Using the where method doesn't alway work
var results = from p in db.Products
where p.Name == nameTextBox.Text
select p;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: Trying to load files from github through a firewall is impossibly slow. Any suggestions for workarounds? I'm a little hesitant to post this, as I'm not completely sure what I'm doing. Any help would be wonderful.
I'm on a computer with a firewall/filter on it. I can download files without any difficulty. When I try to clone files from Github, though, the computer just hangs. Nothing happens. It creates a git file in the folder, but the key files don't get loaded in. For context, I'm working on a Rails app, trying to load in Restful Authentication.
Have any of you dealt with this? Any suggestions for getting the clone to work? Disabling the firewall might be an option, but if I can do something without going through that process, I'd appreciate it.
A: If you're firewalled out of existence and want the speed of git [update: HTTP(S) is practically as fast as ssh these days, but this information is still useful if SSH is the only way to access a repo], and have ssh access to a machine that isn't firewalled, then use an ssh tunnel.
To do so, run this in one window, and leave it running:
$ ssh username@some_host_not_firewalled -L9418:github.com:9418
Then wherever you used the former command:
$ git clone git://github.com/jruby/jruby.git
use this instead:
$ git clone git://localhost/jruby/jruby.git
This translation can be done automatically if you modify your (global) git config:
$ git config --global url.git://localhost/.insteadOf git://github.com/
A: The git:// protocol uses port 9418, so you should make sure your firewall allows outbound connections to this port.
A: Github supports cloning using both the git protocol over port 9418 and HTTP over port 80. Using the later is very slow (Reference).
You should open port 9418 on your firewall or use HTTP cloning otherwise.
A: Or... just change the "git://" prefix to "http://"
A: I'm use git clone git@ssh.github.com:xxx.user/xxx.proj
A: git config --global url."https://".insteadOf git://
Done!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: Can Adobe AIR display SVG? I see that Adobe AIR uses WebKit as its render and I see that WebKit (at least the most current build) has some SVG support. Does this mean (and has anyone specifically tried) that an Adobe AIR application could render SVG on an HTML page?
A: On the offchance that it's helpful (and that you don't already know), Flex can embed SVG at runtime compile time, which effectively converts it to SWF format and embeds it as a resource.
[Embed(source="assets/frog.svg")]
[Bindable]
public var SvgAsset:Class;
More info at Adobe's embedding assets article.
A: If ActionScript 2: use the com.itechnica.svg (PathToArray) library to load SVGs at SWF runtime and display them (uses XML for SVG parsing):
Using SVG Path Data in Flash, Download button on the right pane.
If ActionScript 3: use the com.zavoo.svg (SvgPath) library to load SVGs at SWF runtime and display them (uses RegExp for SVG parsing):
Source code for SvgLoad and SvgDraw, Download button on the bottom-left.
A: No, according to the Adobe AIR Developer Center article What's new about HTML, HTML5, CSS, and JavaScript in AIR 2.5?.
SVG
Another feature that has received
a great deal of interest lately is
support for SVG. While present in
WebKit, the current version of Adobe
AIR does not support SVG.
The main reason for not including it
was runtime size concerns (adding it
would have increased the runtime size
by 15 to 20 percent). Initially, the
main pain-points regarding AIR were
the size of the runtime, integration
with the operating system and native
APIs, support for the tag and
new CSS properties, and JavaScript
performance. These priorities, coupled
with a trend toward reduced interest
in SVG graphics, led to SVG support
not being included in the current
version of Adobe AIR.
However, the renewed interest in rich
JavaScript applications powered by
HTML5 canvas and faster JavaScript
engines increased the number of
requests for scriptable vector
graphics via SVG. Thus, adding support
for SVG graphics may be considered for
the next version of AIR.
A: Adobe AIR can only support SVG once Adobe updates their version of WebKit (AIR's HTML rendering engine) and enables the SVG support within their version of WebKit. Might be a business decision not to (ie Flash).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Tell if a Javascript function is defined by looking at self[name] - is this a good way? This is a follow up question to This Question.
I like (and understand) the solution there. However, in the code I am working in, another way to solve the same problem is used:
function exist(sFN) {
if(self[sFN]) return true;
return false;
}
It seems to work fine, although I don't understand how. Does it work? How? What are minuses of this approach? Should I switch to solution from the other question?
A: Try this:
function exist(sFN) {
return (typeof sFN == 'function');
}
A: Your condition is checking the existence of the "sFN" property in the "self" object. Anything that isn't null, undefined, 0, and "" will evaluate to true.
As others have said, you can use typeof, or instanceof to see if it's actually a function.
Looking at your linked example, you should read up on the difference between ==/!= and ===/!== in javascript. Short answer: ("" == null) is true, ("" === null) is false.
A: just use typeof.
typeof(foobar) // -> undefined
typeof(alert) // -> function
You can't, however, defined a function based on typeof, because you'd need to pass an identifier which might not exist. So if you define function isfun(sym) { return typeof(sym) }, and then tried calling isfun(inexistent), your code would throw.
The fun thing about typeof is that it's an operator, not a function. So you can use it to check a symbol that's not defined without throwing.
if you assume a function in the global scope (i.e., not within a closure), you can define a function to check it as follows:
function isfun(identifier) {
return typeof(window[identifier]) == 'function';
}
Here you pass an string for the identifier, so:
isfun('alert'); // -> true
isfun('foobar'); // -> false
closure?
Here's an example of a function defined within a closure. Here, the printed value would be false, which is wrong.
(function closure() {
function enclosed() {}
print(isfun('enclosed'))
})()
A: FYI: There is (or was) a nice pitfall for typeof.
FF2 returns 'function' for typeof(/pattern/).
FF3, IE7, and Chrome all return 'object' for the same code.
(I can't verify other browsers.)
Assuming everyone that used FF2 has upgraded, you're in the clear.
But, that's probably a far-fetched assumption.
A: You can't really wrap this in a method, but it's so simple there is really no need.
function bob()
{}
if( typeof bob == "function" )
alert( "bob exists" );
if( typeof dave != "function" )
alert( "dave doesn't" );
A: Object.prototype.toString.apply(value) === '[object Function]'
A: I read somewhere (here and here) that functions are properties of the window object, so you can do the following:
if (window.my_func_name) {
my_func_name('tester!');
}
or for popups:
if (window.opener.my_func_name) {
my_func_name('tester!');
}
A complete solution then:
function function_exists(func_name) {
var eval_string;
if (window.opener) {
eval_string = 'window.opener.' + func_name;
} else {
eval_string = 'window.' + func_name;
}
return eval(eval_string + ' ? true : false');
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Getting a DrawingContext for a wpf WriteableBitmap Is there a way to get a DrawingContext (or something similar) for a WriteableBitmap? I.e. something to allow you to call simple DrawLine/DrawRectangle/etc kinds of methods, rather than manipulate the raw pixels directly.
A: I'm wondering the same thing, as currently I do something like:
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
//
// ... draw on the drawingContext
//
RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, dpi, dpi, PixelFormats.Default);
bmp.Render(drawingVisual);
image.Source = bmp;
}
I'm trying to use the WriteableBitmap to allow multithreaded access to the pixel buffer, which is currently not allowed with neither a DrawingContext nor a RenderTargetBitmap. Maybe some sort of WritePixels routine based off of what you've retrieved from the RenderTargetBitmap would work?
A: It appears the word is no.
For future reference, we plan to use a port of the Writeable Bitmap Extensions for WPF.
For a solution using purely existing code, any of the other suggestions mentioned below will work.
A: I found sixlettervariables' solution the most workable one. However, there's a "drawingContext.Close()" missing. According to MSDN, "A DrawingContext must be closed before its content can be rendered".
The result is the following utility function:
public static BitmapSource CreateBitmap(
int width, int height, double dpi, Action<DrawingContext> render)
{
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
render(drawingContext);
}
RenderTargetBitmap bitmap = new RenderTargetBitmap(
width, height, dpi, dpi, PixelFormats.Default);
bitmap.Render(drawingVisual);
return bitmap;
}
This can then easily be used like this:
BitmapSource image = ImageTools.CreateBitmap(
320, 240, 96,
drawingContext =>
{
drawingContext.DrawRectangle(
Brushes.Green, null, new Rect(50, 50, 200, 100));
drawingContext.DrawLine(
new Pen(Brushes.White, 2), new Point(0, 0), new Point(320, 240));
});
A: If you don't mind using System.Drawing you could do something like:
var wb = new WriteableBitmap( width, height, dpi, dpi,
PixelFormats.Pbgra32, null );
wb.Lock();
var bmp = new System.Drawing.Bitmap( wb.PixelWidth, wb.PixelHeight,
wb.BackBufferStride,
PixelFormat.Format32bppPArgb,
wb.BackBuffer );
Graphics g = System.Drawing.Graphics.FromImage( bmp ); // Good old Graphics
g.DrawLine( ... ); // etc...
// ...and finally:
g.Dispose();
bmp.Dispose();
wb.AddDirtyRect( ... );
wb.Unlock();
A: A different way to solve this problem is to use a RenderTargetBitmap as a backing store, just like in the WriteableBitmap example. Then you can create and issue WPF drawing commands to it whenever you want. For example:
// create the backing store in a constructor
var backingStore =
new RenderTargetBitmap(200,200,97,97,PixelFormats.Pbgra32);
myImage.Source = backingStore;
// whenever you want to update the bitmap, do:
var drawingVisual = new DrawingVisual();
var drawingContext = drawingVisual.RenderOpen();
{
// your drawing commands go here
drawingContext.DrawRectangle(
Brushes.Red, new Pen(),
new Rect(this.RenderSize));
}
Render(drawingContext);
drawingContext.Close();
backingStore.Render(drawingVisual);
If you want to redraw this RenderTargetBitmap every frame, you can catch the CompositionTarget.Rendering event, like this:
CompositionTarget.Rendering += MyRenderingHandler;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: When is a browser considered "dead"? Keep in mind that I'm not looking for a list of current browsers to support, I'm looking for logical ways to make that list, backed by some kind of hard statistics.
Since it's been a while since my last web job, I decided to do this latest site up from scratch. Now I have to decide again what to support in terms of browsers. Certainly I have a list of what I'd like to support, but the decisions that went into that list seem to be a little arbitrary to me. Where can I go to get a reliable picture of browser usage and what seems to be a good point at which to cut off an old version of a browser from support?
A: The easiest way to do it is sign up for Google Analytics and add their tracking code to your site (there are a number of similar services, but Google's one is the best I've found). It gives you detailed statistics as to what browsers people who visit your site use.
Once you have a couple of months data, you can start making decisions as to which browsers you will support. I work for a mainstream web company who want to make our site work for as many users as possible, so we consider any browser with above 0.5% market share to be within our testing matrix. However, other sites may choose to only support and test on major browsers such as IE and Firefox.
As a rough guide, the major browsers you'll see are IE 6 and 7, and Firefox 2 and 3. This should cover well over 90% of your audience so is a good starting point for the first couple of months. Then use your analytics data and make a business decision as to whether the potential revenue (or whatever you're trying to achieve) is worth the additional effort it will take to support other browsers.
Added 2008-09-18:
Admittedly one issue with this method is that if your support for some browser types is so bad that your site is unusable with them then it will potentially skew the statistics as those people will stop coming back, and thus those browsers will appear to have a lower percentage of users.
To determine whether this is happening, you can use Google Analytics' detailed breakdown of behaviour for each browser type and version. This gives you the bounce rate, average time on site, pages per visit, and percent of new visits. If the figures for a given browser type and version are significantly worse than others (i.e. the bounce rate is higher, time on site is lower, pages per visit is lower, or percent of new visits is higher) then it's possible that your site isn't supporting that browser sufficiently well and that you might get more users with it if you had better support.
At this point the figures will still give you a reasonable feeling for how important the browser is (i.e. if it you don't support Google Chrome and it is being shown as 2% of your traffic, then it wouldn't jump to 20% just because you added support) so you can use that browser to see how bad your site is, and make a judgment call as to whether you add support; sometimes this may involve fixing only the worst issues and leaving the site imperfect but usable until the browser gets to a higher percentage of users, or out of beta status.
A: You could take a look at the way Yahoo! supports browsers at Graded browser support.
A: Browsers don't die out completely for about a decade. The first thing you must realise is that you will have some visitors that are using a browser you don't support. The question is not which browsers are not dead, but which browsers are worth supporting (the benefit) relative to the work it takes to do so (the cost).
I've never seen browser statistics I'm comfortable recommending, they all seem to be snake oil. A rule of thumb I feel is appropriate is that a browser isn't worth supporting if somebody using that browser is going to regularly run into problems on other websites as well. In other words "stick with what everybody else is supporting". To that end, Yahoo's graded browser support is useful.
Ultimately, the best choice depends on your individual circumstances and will change over time. For instance, 37signals have recently dropped support for Internet Explorer 6 and Facebook are slowly heading in the same direction. This isn't a decision that most organisations can make yet, but give it a year or two and you'll see a lot more organisations follow suit. Right now, it's a bold step that you probably can't justify, but give it time.
Don't fall into the trap of thinking that supporting as many browsers as possible is automatically the best choice - it may be that you are doing your visitors a disservice by wasting time working on compatibility with a browser used by five people when you could be improving the experience for the other million users you have.
Also, it's worth considering that you can "officially" not support a browser. For example, one thing I've done in the past is use JavaScript served only to Internet Explorer 5.5 and below (via a conditional comment), to automatically remove stylesheets, JavaScript and replace images with their alt text. Without those measures, the site would be unreadable due to Internet Explorer's many layout bugs, but with it, the site at least works, even if it's too much work to "support" it.
A: The browser is dead when (a) a very small percentage of people use it and (b) you don't care about (selling to? educating? whatever your business is) such a small percentage of people.
A: Unfortunately, you won't find a good answer to this; even if you found some hard statistics on browser versions for visitors to your website, that almost certainly doesn't tell you what you need to know.
What you need to know isn't "what percent of my visitors use Browser X", it's "what percent of my revenue comes from visitors who use Browser X". That one guy visiting your site using an ancient copy of IE might be the managing director of a big company wanting to buy a site license; the 10k visitors you had last month using Firefox 3 might be college students wanting to plagiarize your documentation for an essay.
Really, you need to know your market - not just the raw browser statistics. If you pay the bills by selling stuff to graphic designers, then rock solid Safari support matters a lot more than if you're in the job of selling Visual Studio plugins. Not helpful, I know!
A: There are 2 main groups to target. (There are plenty of others though)
Group #1 is browsers that use Webkit (Safari for example), Presto (Opera for example), KHTML (Konqueror for example) or Gecko (Firefox for example). These browsers should all get the same markup, CSS and Javascript code (as they're all in the same group of standard-compliant browsers). Only work around bugs in one of these if you absolutely have to and have the resources to do so. Instead, test in the latest stable versions of each (as you're developing so they can keep each other in check as to what the expected behavior is) and (after checking in the nightlies for the bugs) file bug reports. Again, avoid workarounds for a specific browser if you can. Instead, plan a cross-browser compatible solution from the beginning.
With Group #1, you don't have to worry about older versions much, if it all.
Group #2 is browsers that use Trident (IE for example). Target IE versions you care about and still only workaround the most severe bugs.
Also, don't deny browsers you don't officially support. Let them fend for themselves instead of blocking them (either intentionally or through crappy browser detection).
Also, remember that when looking at market share percentages, try to figure out the numbers they represent so you can see how many millions of potential visitors with that browser there are. 1% or 5% might not seem like a lot, but that could still mean millions.
Most of all, listen to the visitors. If you're getting multiple complaints about a certain browser, look into it if you can. Even if it's for a browser with low market share, if it's a trivial fix, you should just do it.
Ones that are definitely not dead are: IE6 (starting to push it), IE7, IE8, latest Opera 9.x, latest FF 3.x, latest Safari 3.x and others that have about the same capabilities. FF 2.x isn't dead either and is needed for Win9X users (if they don't want to use Opera)
A: See also this topic
A: You should use a good UI framework that solves most of the compatibility issues among browsers, like YUI!, jQuery, and so on...
Personaly, I recommend YUI!
A: Try to answer this locally, consider your audience. For example when I was developing my own Blog Engine, my appeal was mostly to .NET developers. I hope it stands to reason what browser I primarily develop for. From that point I consider the market share and try to ensure a "reasonable" support level for all other browsers. For example even .NET developers occasionally use Firefox, maybe even Opera. Safari and Chrome are possibilities too now. So my current level of support ranks in this order:
*
*It MUST run perfectly in Internet Explorer 7. All features I intended to build are there
*It MUST run reasonably in Internet Explorer 6, Firefox 3.0, Opera 9+ and Safari for Windows, not everything has to be flawless, but it can't look downright ugly either
Everything else I don't care about. I just don't have the time and willing effort to support everything.
How do I determine whether or not I want to even consider supporting another browser or continuing supporting one of the above browsers any more? Simply I look at the market share and the statistics of who is hitting my page. If someone is dying, or I just haven't seen them in awhile, then I consider support dropped.
So in short, I would simply make a statement to yourself about the browsers that must run your code perfectly then reasonably and update periodically as the browser world changes. For the first run of your website, just think about your audience, for subsequent updates, your statistics should tell you enough.
A: My (very poor) solution was to get stats from w3schools and base my decisions on that. While those numbers aren't really terrible, they are skewed because viewers of that site are more likely to be upgrade-conscious. Also, it doesn't give a breakdown of any browser versions except FF.
A: If you purely build to standards, some browser won't render correctly since no browser supports all standards. You have to pick a few browsers and test your site in those.
Don't try to be too bleeding edge. If you must use some cutting edge CSS, then you have to expect it not to work 100% of the time.
A: What are you really going to do with the list? Are you planning to block browsers you don't support? What if the user hacks the User-Agent response?
Like others, I would strongly suggest going with something like Yahoo's "Graded Browsers" and, if possible, leveraging YUI or other libraries so you don't have to do it yourself.
A: <1% market share isn't a criteria - esp if the browser is new.
For me, < IE6 is dead, and the HTML monkeys I work with WISH it was dead. < FF2 is dead. Opera is a nice to have. < Safari 2 is dead, tho most are designing for Saf 3 now.
So it's:
IE6,7,8
FF 2,3
Saf 3,4
Chrome (which is basicly Saf4)
But depending on your app, and how many people you think you are going to get wih hold machines, you COULD drop IE6, which would make your life so much easier.
A: I would say IE6 and below are dead... but many are still stuck using it.
This site has a nice live listing of each browser and its actual age.
http://webbugtrack.blogspot.com/2008/08/browser-life-statuses.html
A: I'd go with the http://browser-update.org/ defaults, which currently say the following are dead:
IE <= 6
FF <= 2.0
Op <= 10.01
Sf <= 2.0
A: I agree with Unkwntech.
You should try to make the website compatible to both IE and Firefox
A: It's simple - most users keep using the browser that came with the PC when they bought it (think of your mom). The browser is dead when the machines that it pre-installed with are not longer used for Internet access... which is probably around 5 years. As prices of new PC's drops and they become more of a consumer electronics item then this period will drop as people will easily buy a new PC
A: Start with the browser with the highest market share and work your way down from there.
If you have existing metrics on browsers that visit your site, use those instead of the general market share.
A: Whichever has < 1% market share.
A: My opinion (has always been) build it to the standards and leave it to the browsers to render it correctly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: Throwing exceptions in ASP.NET C# Is there a difference between just saying throw; and throw ex; assuming ex is the exception you're catching?
A: throw ex; will erase your stacktrace. Don't do this unless you mean to clear the stacktrace. Just use throw;
A: You have two options throw; or throw the orginal exceptional as an innerexception of a new exception. Depending on what you need.
A: Here is a simple code snippet that will help illustrate the difference. The difference being that throw ex will reset the stack trace as if the line "throw ex;" were the source of the exception.
Code:
using System;
namespace StackOverflowMess
{
class Program
{
static void TestMethod()
{
throw new NotImplementedException();
}
static void Main(string[] args)
{
try
{
//example showing the output of throw ex
try
{
TestMethod();
}
catch (Exception ex)
{
throw ex;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.WriteLine();
Console.WriteLine();
try
{
//example showing the output of throw
try
{
TestMethod();
}
catch (Exception ex)
{
throw;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
}
}
Output (notice the different stack trace):
System.NotImplementedException: The method or operation is not implemented.
at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 23
System.NotImplementedException: The method or operation is not implemented.
at StackOverflowMess.Program.TestMethod() in Program.cs:line 9
at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 43
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: How to replace $*=1 with an alternative now $* is no longer supported I'm a complete perl novice, am running a perl script using perl 5.10 and getting this warning:
$* is no longer supported at migrate.pl line 380.
Can anyone describe what $* did and what the recommended replacement of it is now?
Alternatively if you could point me to documentation that describes this that would be great.
The script I'm running is to migrate a source code database from vss to svn and can be found here:
http://www.x2systems.com/files/migrate.pl.txt
The two snippets of code that use it are:
$* = 1;
$/ = ':';
$cmd = $SSCMD . " Dir -I- \"$proj\"";
$_ = `$cmd`;
# what this next expression does is to merge wrapped lines like:
# $/DeviceAuthority/src/com/eclyptic/networkdevicedomain/deviceinterrogator/excep
# tion:
# into:
# $/DeviceAuthority/src/com/eclyptic/networkdevicedomain/deviceinterrogator/exception:
s/\n((\w*\-*\.*\w*\/*)+\:)/$1/g;
$* = 0;
and then some ways later on:
$cmd = $SSCMD . " get -GTM -W -I-Y -GL\"$localdir\" -V$version \"$file\" 2>&1";
$out = `$cmd`;
# get rid of stupid VSS warning messages
$* = 1;
$out =~ s/\n?Project.*rebuilt\.//g;
$out =~ s/\n?File.*rebuilt\.//g;
$out =~ s/\n.*was moved out of this project.*rebuilt\.//g;
$out =~ s/\nContinue anyway.*Y//g;
$* = 0;
many thanks,
*
*Rory
A: From Perl 5.8 version of perlvar:
Set to a non-zero integer value to do
multi-line matching within a string
[...] Use of $* is deprecated in
modern Perl, supplanted by the /s and
/m modifiers on pattern matching.
While using /s and /m is much better, you need to set the modifiers (appropriately!) for each regular expression.
perlvar also says "This variable influences the interpretation of only ^ and $." which gives the impression that it's equivalent to /m only and not /s.
Note that $* is a global variable. Because the change to it is not made local with the local keyword, it will affect all regular expressions in the program, not just those that follow it in the block. This will make it more difficult to update the script correctly.
A: From perldoc perlvar:
$*
Set to a non-zero integer value to do multi-line matching within a string, 0 (or undefined) to tell Perl that it can assume that strings contain a single line, for the purpose of optimizing pattern matches. Pattern matches on strings containing multiple newlines can produce confusing results when $* is 0 or undefined. Default is undefined. (Mnemonic: * matches multiple things.) This variable influences the interpretation of only ^ and $. A literal newline can be searched for even when $* == 0.
Use of $* is deprecated in modern Perl, supplanted by the /s and /m modifiers on pattern matching.
Assigning a non-numerical value to $* triggers a warning (and makes $* act as if $* == 0), while assigning a numerical value to $* makes that an implicit int is applied on the value.
A: From perlvar:
Use of $* is deprecated in modern Perl, supplanted by the /s and /m modifiers on pattern matching.
If you have access to the place where it's being matched just add it to the end:
$haystack =~ m/.../sm;
If you only have access to the string, you can surround the expression with
qr/(?ms-ix:$expr)/;
Or in your case:
s/\n((\w*\-*\.*\w*\/*)+\:)/$1/gsm;
A: It turns on multi-line mode. Since perl 5.0 (from 1994), the correct way to do that is adding a m and/or the s modifier to your regexps, like this
s/\n?Project.*rebuilt\.//msg
A: It was basically a way of saying that in subsequent regexes (s/// or m//), the ^ or $ assertions should be able to match before or after newlines embedded in the string.
The recommended equivalent is the m modifier at the end of your regex (e.g., s/\n((\w*-*.*\w*/*)+:)/$1/gm;).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Best way to convert a decimal value to a currency string for display in HTML I wanting to show prices for my products in my online store.
I'm currently doing:
<span class="ourprice">
<%=GetPrice().ToString("C")%>
</span>
Where GetPrice() returns a decimal. So this currently returns a value e.g. "£12.00"
I think the correct HTML for an output of "£12.00" is "£12.00", so although this is rendering fine in most browsers, some browsers (Mozilla) show this as $12.00.
(The server is in the UK, with localisation is set appropriately in web.config).
Is the below an improvement, or is there a better way?
<span class="ourprice">
<%=GetPrice().ToString("C").Replace("£","£")%>
</span>
A: Try this, it'll use your locale set for the application:
<%=String.Format("{0:C}",GetPrice())%>
A: Use
GetPrice().ToString("C", CultureInfo.CreateSpecificCulture("en-GB"))
A: The £ symbol (U+00A3), and the html entities & #163; and & pound; should all render the same in a browser.
If the browser doesn't recognise £, it probably won't recognise the entity versions.
It's in ISO 8859-1 (Latin-1), so I'd be surprised if a Mozilla browser can't render it (my FF certainly can).
If you see a $ sign, it's likely you have two things:
1. The browser default language is en-us
2. Asp.net is doing automatic locale switching. The default web.config setting is something like
<globalization culture="auto:en-us" uiCulture="auto:en-US" />
As you (almost certainly) want UK-only prices, simply specify the locale in web.config:
<globalization culture="us" uiCulture="en-gb" />
(or on page level:)
<%@Page Culture="en-gb" UICulture="en-gb" ..etc... %>
Thereafter the string formats such as String.Format("{0:C}",GetPrice()) and GetPrice().ToString("C") will use the en-GB locale as asp.net will have set the currentCulture for you
(although you can specify the en-gb culture in the overloads if you're paranoid).
A: You could write a function which would perform the conversion from price to string. This way you have a lot of control over the output.
The problem with locale is that it's web server dependent and not web browser dependent.
A: If you need to explicity state the localisation you can use the CultureInfo and pass that to the string formatter.
A: just use the ToString("C2") property of a decimal value. Set your globalization in the web.config - keep it simple.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Business Objects, Validation And Exceptions I’ve been reading a few questions and answers regarding exceptions and their use. Seems to be a strong opinion that exceptions should be raised only for exception, unhandled cases. So that lead me to wondering how validation works with business objects.
Lets say I have a business object with getters/setters for the properties on the object. Let’s say I need to validate that the value is between 10 and 20. This is a business rule so it belongs in my business object. So that seems to imply to me that the validation code goes in my setter. Now I have my UI databound to the properties of the data object. The user enters 5, so the rule needs to fail and the user is not allowed to move out of the textbox. . The UI is databound to the property so the setter is going to be called, rule checked and failed. If I raised an exception from my business object to say the rule failed, the UI would pick that up. But that seems to go against the preferred usage for exceptions. Given that it’s a setter, you aren’t really going to have a ‘result’ for the setter. If I set another flag on the object then that would imply the UI has to check that flag after each UI interaction.
So how should the validation work?
Edit: I've probably used an over-simplified example here. Something like the range check above could be handled easily by the UI but what if the valdation was more complicated, e.g. the business object calculates a number based on the input and if that calculated number is out of range it should be recjected. This is more complicated logic that should not be in th UI.
There is also the consideration of further data entered based on a field already entered. e.g.I have to enter an item on the order to get certain informaion like stock on hand, current cost, etc. The user may require this information to make decisions on further entry (liek how many units to order) or it may be required in order for further validation to be done. Should a user be able to enter other fields if the item isn't valid? What would be the point?
A: Assuming that you have separate validation and persist (i.e. save to database) code, I would do the following:
*
*The UI should perform validation. Don't throw exceptions here. You can alert the user to errors and prevent the record from being saved.
*Your database save code should throw invalid argument exceptions for bad data. It makes sense to do it here, since you cannot proceed with the database write at this point. Ideally this should never happen since the UI should prevent the user from saving, but you still need it to ensure database consistency. Also you might be calling this code from something other than the UI (e.g. batch updates) where there is no UI data validation.
A: I've always been a fan of Rocky Lhotka's approach in the CSLA framework (as mentioned by Charles). In general, whether it's driven by the setter or by calling an explicit Validate method, a collection of BrokenRule objects is maintained internally by the business object. The UI simply needs to check an IsValid method on the object, which in turn checks the number of BrokenRules, and handle it appropriately. Alternatively, you could easily have the Validate method raise an event which the UI could handle (probably the cleaner approach). You can also use the list of BrokenRules to display error messages to the use either in summary form or next to the appropriate field. Although the CSLA framework is written in .NET, the overall approach can be used in any language.
I don't think throwing an Exception is the best idea in this case. I definitely follow the school of thought that says Exceptions should be for exceptional circumstances, which a simple validation error is not. Raising an OnValidationFailed event would be the cleaner choice, in my opinion.
By the way, I have never liked the idea of not letting the user leave a field when it is in an invalid state. There are so many situations where you might need to leave the field temporarily (perhaps to set some other field first) before going back and fixing the invalid field. I think it's just an unnecessary inconvenience.
A: You might want to move the validation outside of the getters and setters. You could have a function or property called IsValid that would run all the validation rules. t would populate a dictionary or hashtable with all of the "Broken Rules". This dictionary would be exposed to the outside world, and you can use it to populate your error messages.
This is the approach that is taken in CSLA.Net.
A: Exceptions should not be thrown as a normal part of validation. Validation invoked from within business objects is a last line of defense, and should only happen if the UI fails to check something. As such they can be treated like any other runtime exception.
Note that here's a difference between defining validation rules and applying them. You might want to define (ie code or annotate) your business rules in your business logic layer but invoke them from the UI so that they can handled in a manner appropriate to that particular UI. The manner of handling will vary for different UI's, eg form based web-apps vs ajax web-apps. Exception-on-set validation offers very limited options for handling.
Many applications duplicate their validation rules, such as in javascript, domain object constraints and database constraints. Ideally this information will only be defined once, but implementing this can be challenge and requires lateral thinking.
A: Perhaps you should look at having both client-side and server-side validation. If anything slips past the client-side validation you can then feel free to throw an exception if your business object would be made invalid.
One approach I've used was to apply custom attributes to business object properties, which described the validation rules. e.g.:
[MinValue(10), MaxValue(20)]
public int Value { get; set; }
The attributes can then be processed and used to automatically create both client-side and server-side validation methods, to avoid the problem of duplicating business logic.
A: I'd definitely advocate both client and server-side validation (or validating at the various layers). This is especially important when communicating across physical tiers or processes, as the cost of throw exceptions becomes increasingly expensive. Also, the further down the chain you wait for validation, the more time is wasted.
As to use Exceptions or not for data validation. I think it's ok to use exception in process (though still not preferrable), but outside of process, call a method to validate the business object (eg before saving) and have the method return the success of the operation along with any validation errors. Errors arent' exceptional.
Microsoft throw exceptions from business objects when validation fails. At least, that's how the Enterprise Library's Validation Application Block works.
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
public class Customer
{
[StringLengthValidator(0, 20)]
public string CustomerName;
public Customer(string customerName)
{
this.CustomerName = customerName;
}
}
A: Your business objects should throw exceptions for bad inputs, but those exceptions should never be thrown in the course of a normal program run. I know that sounds contradictory, so I shall explain.
Each public method should validate its inputs, and throw "ArgumentException"s when they are incorrect. (And private methods should validate their inputs with "Debug.Assert()"s to ease development, but that's another story.) This rule about validating inputs to public methods (and properties, of course) is true for every layer of the application.
The requirements of the software interface should be spelled out in the interface documentation, of course, and it is the job of the calling code to make sure the arguments are correct and the exceptions will never be thrown, which means the UI needs to validate the inputs before handing them to the business object.
While the rules given above should almost never be broken, sometimes business object validation can be very complex, and that complexity shouldn't be foisted onto the UI. In that case it's good for the BO's interface to allow some leeway in what it accepts and then provide for an explicit Validate(out string[]) predicate to check the properties and give feedback on what needs to be changed. But notice in this case that there are still well-defined interface requirements and no exceptions need ever be thrown (assuming the calling code follows the rules).
Following this latter system, I almost never do early validation on property setters, since that soft-of complicates the use of the properties, (but in the case given in the question, I might). (As an aside, please don't prevent me from tabbing out of a field just because it has bad data in it. I get clausterphobic when I can't tab around a form! I'll go back and fix it in a minute, I promise! OK, I feel better now, sorry.)
A: It depends on what sort of validation you will be performing and where. I think that each layer of the application can be easily protected from bad data and its too easy to do for it not to be worth it.
Consider a multi-tiered application and the validation requirements/facilities of each layer. The middle layer, Object, is the one that seems to be up for debate here.
*
*Database
protects itself from an invalid state with column constraints and referential integrity, which will cause the application's database code to throw exceptions
*Object
?
*ASP.NET/Windows Forms
protects the form's state (not the object) using validator routines and/or controls without using exceptions (winforms does not ship with validators, but there's an excellent series at msdn describing how to implement them)
Say you have a table with a list of hotel rooms, and each row has a column for the number of beds called 'beds'. The most sensible data type for that column is an unsigned small integer*. You also have a plain ole object with an Int16* property called 'Beds'. The issue is that you can stick -4555 into an Int16, but when you go to persist the data to a database you're going to get an Exception. Which is fine - my database shouldn't be allowed to say that a hotel room has less than zero beds, because a hotel room can't have less than zero beds.
* If your database can represent it, but let's assume it can
* I know you can just use a ushort in C#, but for the purpose of this example, let's assume you can't
There's some confusion as to whether objects should represent your business entity, or whether they should represent the state of your form. Certainly in ASP.NET and Windows Forms, the form is perfectly capable of handling and validating its own state. If you've got a text box on an ASP.NET form that is going to be used to populate that same Int16 field, you've probably put a RangeValidator control on your page which tests the input before it gets assigned to your object. It prevents you from entering a value less than zero, and probably prevents you from entering a value greater than, say, 30, which hopefully would be enough to cater for the worst flea-infested hostel you can imagine. On postback, you would probably be checking the IsValid property of the page before building your object, thereby preventing your object from ever representing less than zero beds and preventing your setter from ever being called with a value it shouldn't hold.
But your object is still capable of representing less than zero beds, and again, if you were using the object in a scenario not involving the layers which have validation integrated into them (your form and your DB) you're outta luck.
Why would you ever be in this scenario? It must be a pretty exceptional set of circumstances! Your setter therefore needs to throw an exception when it receives invalid data. It should never be thrown, but it could be. You could be writing a Windows Form to manage the object to replace the ASP.NET form and forget to validate the range before populating the object. You could be using the object in a scheduled task where there is no user interaction at all, and which saves to a different, but related, area of the database rather than the table which the object maps to. In the latter scenario, your object can enter a state where it is invalid, but you won't know until the results of other operations start to be affected by the invalid value. If you're checking for them and throwing exceptions, that is.
A: I tend to believe business objects should throw exceptions when passed values that violate its business rules. It however seems that winforms 2.0 data binding architecture assumes the opposite and so most people are rail-roaded into supporting this architecture.
I agree with shabbyrobe's last answer that business objects should be built to be usable and to work correctly in multiple environments and not just the winforms environment, e.g., the business object could be used in a SOA type web service, a command line interface, asp.net, etc. The object should behave correctly and protect itself from invalid data in all these cases.
An aspect that is often overlooked is also what happens in managing the collaborations between objects in 1-1, 1-n or n-n relationships, should these also accept the addition of invalid collaborators and just maintain a invalid state flag which should be checked or should it actively refuse to add invalid collaborations. I have to admit that I'm heavily influenced by the Streamlined Object Modeling (SOM) approach of Jill Nicola et al. But what else is logical.
The next thing is how to work with windows forms. I'm looking at creating a UI wrapper for the business objects for these scenarios.
A: As Paul Stovell's article mentioned, you can implement error-free validation in your business objects by implementing the IDataErrorInfo interface. Doing so will allow user error notification by WinForm's ErrorProvider and WPF's binding with validation rules. The logic to validate your objects properties is stored in one method, instead of in each of your property getters, and you do not necessarily have to resort to frameworks like CSLA or Validation Application Block.
As far as stopping the user from changing focus out of the textbox is concerned:
First of all, this is usually not the best practice. A user may want to fill out the form out of order, or, if a validation rule is dependent on the results of multiple controls, the user may have to fill in a dummy value just to get out of one control to set another control. That said, this can be implemented by setting the Form's AllowValidate property to its default, EnableAllowFocusChange and subscribing to the Control.Validating event:
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text != String.Empty)
{
errorProvider1.SetError(sender as Control, "Can not be empty");
e.Cancel = true;
}
else
{
errorProvider1.SetError(sender as Control, "");
}
}
Using rules stored in the business object for this validation is a little more tricky since the Validating event is called before the focus changes and the data bound business object is updated.
A: You want to delve a bit in the remarkable work of Paul Stovell concerning data validation. He summed up his ideas at one time in this article. I happen to share his point of view on the matter, which I implemented in my own libraries.
Here are, in Paul's words, the cons to throwing exceptions in the setters (based on a sample where a Name property should not be empty) :
*
*There may be times where you actually need to have an empty name. For example, as the default value for a "Create an account" form.
*If you're relying on this to validate any data before saving, you'll miss the cases where the data is already invalid. By that, I mean, if you load an account from the database with an empty name and don't change it, you might not ever know it was invalid.
*If you aren't using data binding, you have to write a lot of code with try/catch blocks to show these errors to the user. Trying to show errors on the form as the user is filling it out becomes very difficult.
*I don't like throwing exceptions for non-exceptional things. A user setting the name of an account to "Supercalafragilisticexpialadocious" isn't an exception, it's an error. This is, of course, a personal thing.
*It makes it very difficult to get a list of all the rules that have been broken. For example, on some websites, you'll see validation messages such as "Name must be entered. Address must be entered. Email must be entered". To display that, you're going to need a lot of try/catch blocks.
And here are basic rules for an alternative solution :
*
*There is nothing wrong with having an invalid business object, so long as you don't try to persist it.
*Any and all broken rules should be retrievable from the business object, so that data binding, as well as your own code, can see if there are errors and handle them appropriately.
A: You might like to consider the approach taken by the Spring framework. If you're using Java (or .NET), you can use Spring as-is, but even if you're not, you could still use that pattern; you'd just have to write your own implementation of it.
A: Throwing an exception in your case is fine. You can consider the case a true exception because something is trying to set an integer to a string (for example). The business rules lack of knowledege of your views means that they should consider this case exceptonal and return that back to the view.
Whether or not you validate your input values before you send them through to the business layer is up to you, I think that as long as you follow the same standard throughout your application then you will end up with clean and readable code.
You could use the spring framework as specified above, just be careful as much of the linked document was indicating writing code that is not strongly typed, I.E. you may get errors at run time that you could not pick up at compile time. This is something I try to avoid as much as possible.
The way we do it here currently is that we take all the input values from the screen, bind them to a data model object and throw an exception if a value is in error.
A: In my experience, validation rules are seldom universal across all screens/forms/processes in an application. Scenarios like this are common: on the add page, it may be ok for a Person object not to have a last name, but on the edit page it must have a last name. That being the case I've come to believe that validation should happen outside of an object, or the rules should be injected into the object so the rules can change given a context. Valid/Invalid should be an explicit state of the object after validation or one that can be derived by checking a collection for failed rules. A failed business rule is not an exception IMHO.
A: Have you considered raising an event in the setter if the data is invalid? That would avoid the problem of throwing an exception and would eliminate the need to explicitly check the object for an "invalid" flag. You could even pass an argument indicating which field failed validation, to make it more reusable.
The handler for the event should be able to take care of putting focus back onto the appropriate control if needed, and it could contain any code needed to notify the user of the error. Also, you could simply decline to hook up the event handler and be free to ignore the validation failure if needed.
A: I my opinion this is an example where throwing an exception is okay. Your property probably does not have any context by which to correct the problem, as such an exception is in order and the calling code should handle the situation, if possible.
A: If the input goes beyond the business rule implemented by the business object, I'd say it's a case not handled by the busines object. Therefore I'd throw an exception. Even though the setter would "handle" a 5 in your example, the business object won't.
For more complex combinations of input, a vaildation method is required though, or else you'll end up with quite complex validations scattered about all over the place.
In my opinion you'll have to decide which way to go depending on the complexity of the allowed/disallowed input.
A: I think it depends on how much your business model is important. If you want to go the DDD way, your model is the most important thing. Therefore, you want it to be in a valid state at all time.
In my opinion, most people are trying to do too much (communicate with the views, persist to the database, etc.) with the domain objects but sometimes you need more layers and a better separation of concerns i.e., one or more View Models. Then you can apply validation without exceptions on your View Model (the validation could be different for different contexts e.g., web services/web site/etc.) and keep exception validations inside your business model (to keep the model from being corrupted). You would need one (or more) Application Service layer to map your View Model with your Business Model. The business objects should not be polluted with validation attributes often related to specific frameworks e.g., NHibernate Validator.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
}
|
Q: Perl: why is the if statement slower than "and"? In Perl, a conditional can be expressed either as
if (condition) { do something }
or as
(condition) and do { do something }
Interestingly, the second way seems to be about 10% faster. Does anyone know why?
A: How many tests did you do before you averaged? Very, very small deviations are statistically insignificant! There are plenty of reasons for speed to vary slightly between tests.
A: According to Benchmark, the second is slightly slower. Possibly it has something to do with the condition, but here's results for a very simple case:
use Benchmark;
timethese(10000000, {
'if' => '$m=5;if($m > 4){my $i=0;}',
'and' => '$m=5; $m > 4 and do {my $i =0}',
});
Results:
Benchmark: timing 10000000 iterations of Name1, Name2...
if: 3 wallclock secs ( 2.94 usr + 0.01 sys = 2.95 CPU) @ 3389830.51/s (n=10000000)
and: 3 wallclock secs ( 3.01 usr + 0.01 sys = 3.02 CPU) @ 3311258.28/s (n=10000000)
A: Some comments about the deparse below:
First, don't use B::Terse, it's obsolete. B::Concise gives you much better information once you are used to it.
Second, you've run it using the literal code given, so condition was taken as a bareword that happens to be true, so the boolean check was optimized away in both cases, which kind of defeats the purpose.
Third, there isn't an extra opcode - the "null" indicates an opcode that's been optimized away (completely out of the execution tree, though still in the parse tree.)
Here's the Concise execution tree for the two cases, which shows them as identical:
$ perl -MO=Concise,-exec -e'($condition) and do { do something }'
1 <0> enter
2 <;> nextstate(main 2 -e:1) v
3 <#> gvsv[*condition] s
4 <|> and(other->5) vK/1
5 <$> const[PV "something"] s/BARE
6 <1> dofile vK/1
7 <@> leave[1 ref] vKP/REFC
-e syntax OK
$ perl -MO=Concise,-exec -e'if ($condition) { do something }'
1 <0> enter
2 <;> nextstate(main 3 -e:1) v
3 <#> gvsv[*condition] s
4 <|> and(other->5) vK/1
5 <$> const[PV "something"] s/BARE
6 <1> dofile vK/1
7 <@> leave[1 ref] vKP/REFC
-e syntax OK
A: I've deparsed it, and it really shouldn't be faster. The opcode tree for the first is
LISTOP (0x8177a18) leave [1]
OP (0x8176590) enter
COP (0x8177a40) nextstate
LISTOP (0x8177b20) scope
OP (0x81779b8) null [174]
UNOP (0x8177c40) dofile
SVOP (0x8177b58) const [1] PV (0x81546e4) "something"
The opcode tree for the second is
LISTOP (0x8177b28) leave [1]
OP (0x8176598) enter
COP (0x8177a48) nextstate
UNOP (0x8177980) null
LISTOP (0x8177ca0) scope
OP (0x81779c0) null [174]
UNOP (0x8177c48) dofile
SVOP (0x8177b60) const [1] PV (0x81546e4) "something"
I really don't see how the latter could be faster. It does an opcode more!
A: Which just goes to show, if you don't know how to do proper code profiling, don't be doing this stuff. The speed difference of these two methods are within the same Big O() speed (As proven by @Leon Timmermans opcode analyisis) - the benchmarks are just going to show differences based on other local conditions, not necessarily your code.
@Svante said the "and" was faster, and @shelfoo said "if" was faster.
I mean really... 7 hundredths of a second change for 10 million loops? That's not faster or slower, statistically.... that's equal.
Instead of looking at miniscule timings like this, learn about code refactoring and Big O() notation... how to reduce the number of loops in your code... and most of all, how to use code profilers to see where the real bottlenecks are. Don't worry about the statistically insignificant stuff. ;)
A: It also could depend on the version of Perl. Which you haven't mentioned. And the difference is not enough to worry about anyway. So use whatever makes more sense.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: In Python, how do you take tokenized input such as with the C++? In C++, I can have take input like this:
cin >> a >> b >> c;
And a can be int, b can be float, and c can be whatever... How do I do the same in python?
input() and raw_input(), the way I'm using them, don't seem to be giving me the desired results.
A: You generally shouldn't use input() in production code. If you want an int and then a float, try this:
>>> line = raw_input().split()
>>> a = int(line[0])
>>> b = float(line[1])
>>> c = " ".join(line[2:])
It all depends on what exactly you're trying to accomplish, but remember that readability counts. Obscure one-liners may seem cool but in the face of maintainability, try to choose something sensible :)
(P.S.: Don't forget to check for errors with try: ... except (ValueError, IndexError):)
A: Since the C++ cin reads from sys.stdin, you'll often do something more like the following.
import sys
tokens= sys.stdin.read().split()
try:
a= int(token[0])
b= float(token[1])
except ValueError, e:
print e # handle the invalid input
A: Depending upon what you are doing, something like the getopt module could be useful, but only in certain situations and I'm not sure if it would apply in yours.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: C++ Derived Class problems I am making a game in C++ and am having problems with my derived class. I have a base class called GameScreen which has a vitrual void draw() function with no statements. I also have a derived class called MenuScreen which also has a virtual void draw() function and a derived class from MenuScreen called TestMenu which also has a void draw() function. In my program I have a list of GameScreens that I have a GameScreen iterator pass through calling each GameScreens draw() function.
The issue is that I have placed a TestMenu object on the GameScreen list. Instead of the iterator calling the draw() function of TestMenu it is calling the draw() function of the GameScreen class. Does anyone know how I could call the draw() function of TestMenu instead of the one in GameScreen.
Here is the function:
// Tell each screen to draw itself.
//gsElement is a GameScreen iterator
//gsScreens is a list of type GameScreen
void Draw()
{
for (gsElement = gsScreens.begin(); gsElement != gsScreens.end(); gsElement++)
{
/*if (gsElement->ssState == Hidden)
continue;*/
gsElement->Draw();
}
}
Here are a copy of my classes:
class GameScreen {
public:
string strName;
bool bIsPopup;
bool bOtherScreenHasFocus;
ScreenState ssState;
//ScreenManager smScreenManager;
GameScreen(string strName){
this->strName = strName;
}
//Determine if the screen should be drawn or not
bool IsActive(){
return !bOtherScreenHasFocus &&
(ssState == Active);
}
//------------------------------------
//Load graphics content for the screen
//------------------------------------
virtual void LoadContent(){
}
//------------------------------------
//Unload content for the screen
//------------------------------------
virtual void UnloadContent(){
}
//-------------------------------------------------------------------------
//Update changes whether the screen should be updated or not and sets
//whether the screen should be drawn or not.
//
//Input:
// bOtherScreenHasFocus - is used set whether the screen should update
// bCoveredByOtherScreen - is used to set whether the screen is drawn or not
//-------------------------------------------------------------------------
virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){
this->bOtherScreenHasFocus = bOtherScreenHasFocus;
//if the screen is covered by another than change the screen state to hidden
//else set the screen state to active
if(bCoveredByOtherScreen){
ssState = Hidden;
}
else{
ssState = Active;
}
}
//-----------------------------------------------------------
//Takes input from the mouse and calls appropriate actions
//-----------------------------------------------------------
virtual void HandleInput(){
}
//----------------------
//Draw content on screen
//----------------------
virtual void Draw(){
}
//--------------------------------------
//Deletes screen from the screen manager
//--------------------------------------
void ExitScreen(){
//smScreenManager.RemoveScreen(*this);
}
};
class MenuScreen: public GameScreen{
public:
vector <BUTTON> vbtnMenuEntries;
MenuScreen(string strName):GameScreen(strName){
}
virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){
GameScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen);
for(unsigned int i = 0; i < vbtnMenuEntries.size(); i++){
vbtnMenuEntries[i].IsPressed();
}
}
virtual void Draw(){
GameScreen::Draw();
for(unsigned int i = 0; i < vbtnMenuEntries.size(); i++)
vbtnMenuEntries[i].Draw();
}
};
class testMenu : public MenuScreen{
public:
vector<OBJECT> test;
//OBJECT background3();
// OBJECT testPic(512, 384, buttonHover.png, 100, 40, 100, 40);
// BUTTON x(256, 384, buttonNormal.png, buttonHover.png, buttonPressed.png, 100, 40, test());
bool draw;
testMenu():MenuScreen("testMenu"){
OBJECT background3(1, 1, 0, TEXT("background.png"), 1, 1, 1024, 768);
OBJECT testPic(512, 384,0, TEXT("buttonHover.png"), 1, 1, 100, 40);
test.push_back(background3);
test.push_back(testPic);
//background3.Init(int xLoc, int yLoc, int zLoc, LPCTSTR filePath, int Rows, int Cols, int Width, int Height)
//test.push_back(background3);
// vbtnMenuEntries.push_back(x);
draw = false;
}
void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){
MenuScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen);
//cout << "X" << endl;
/*if(MouseLButton == true){
testMenu2 t;
smManager.AddScreen(t);
}*/
}
void Draw(){
//background3.Draw();
test[0].Draw();
test[1].Draw();
MenuScreen::Draw();
///*if(draw){*/
// testPic.Draw();
//}
}
/*void test(){
draw = true;
}*/
};
A: If gsScreens is a list of objects instead of a list of pointers (as your code suggests), then you're not storing what you think you're storing in it.
What's happening is that -- instead of putting a TestMenu into the list, you're actually constructing a new MenuScreen using the compiler-generated copy constructor and putting this MenuScreen into the list.
C++ is polymorphic through pointers, so if you don't have a pointer you won't get polymorphic behavior.
A: To get the polymorphic behavior you're after and at the same time use a std::vector<>, you must store pointers to the base class type in the vector, instead of storing values. Also, you must remember to free their memory before the vector goes out of scope.
For instance:
#include <vector>
#include <algorithm>
struct Base
{
virtual void Foo() = 0;
virtual ~Base() { }
};
struct Derived1 : public Base
{
void Foo() { }
};
struct Derived2 : public Base
{
void Foo() { }
};
struct delete_ptr
{
template <typename T>
void operator()(T& p)
{
delete p;
p = 0;
}
};
int wmain(int, wchar_t*[])
{
std::vector<Base*> items;
items.push_back(new Derived1);
items.push_back(new Derived2);
Base& first = items.front();
first.Foo(); // Will boil down to Derived1::Foo().
Base& last = items.back();
last.Foo(); // Will boil down to Derived2::Foo().
std::for_each(items.begin(), items.end(), delete_ptr())
};
A: Curt is absolutely correct, but I'd just like to throw a little more information at it.
This problem (storing base-class objects, rather than pointers) is sometimes called "slicing".
Also, I tend to make use of the following macro:
#define DISALLOW_COPYING(X) \
private: \
X(const X &); \
const X& operator= (const X& x)
Then you put this somewhere in your class definition:
class Foo {
// ...
DISALLOW_COPYING(Foo);
};
If another class attempts to copy the object, you'll get a compiler error (because the methods are declared private). If the class itself attempts to copy the object, you'll get a linker error (because the methods have no implementation).
A: Boost (www.boost.org, a library I would recommend anyone coding in C++ use) provides a noncopyable base class that does exactly that; you don't need an ugly macro that way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I create a node from a cron job in drupal? In a custom module for drupal 4.7 I hacked together a node object and passed it to node_save($node) to create nodes. This hack appears to no longer work in drupal 6. While I'm sure this hack could be fixed I'm curious if there is a standard solution to create nodes without a form. In this case the data is pulled in from a custom feed on another website.
A: node_save() still works fine in Drupal 6; you'll need a couple of specific pieces of data in place to make it work.
$node = new stdClass();
$node->type = 'story';
$node->title = 'This is a title';
$node->body = 'This is the body.';
$node->teaser = 'This is the teaser.';
$node->uid = 1;
$node->status = 1;
$node->promote = 1;
node_save($node);
'Status' and 'Promote' are easy to overlook -- if you don't set those, the node will remain unpublished and unpromoted, and you'll only see if you go to the content administration screen.
A: I don't know of a standard API for creating a node pragmatically. But this is what I've gleaned from building a module that does what you're trying to do.
*
*Make sure the important fields are set: uid, name, type, language, title, body, filter (see node_add() and node_form())
*Pass the node through node_object_prepare() so other modules can add to the $node object.
A: The best practices method of making this happen is to utilize drupal_execute. drupal_execute will run standard validation and basic node operations so that things behave the way the system expects. drupal_execute has its quirks and is slightly less intuitive than simply a node_save, but, in Drupal 6, you can utilize drupal_execute in the following fashion.
$form_id = 'xxxx_node_form'; // where xxxx is the node type
$form_state = array();
$form_state['values']['type'] = 'xxxx'; // same as above
$form_state['values']['title'] = 'My Node Title';
// ... repeat for all fields that you need to save
// this is required to get node form submits to work correctly
$form_state['submit_handlers'] = array('node_form_submit');
$node = new stdClass();
// I don't believe anything is required here, though
// fields did seem to be required in D5
drupal_execute($form_id, $form_state, $node);
A: One more answer I discovered was to use the example from the blogapi module in drupal core. The fact that it is in core gives me a bit more confidence that it will continue to work in future versions.
A: There are some good answers above, but in the specific example of turning an ingested feed item into a node, you could also take the approach of using the simplefeed module (http://wwww.drupal.org/project/simplefeed). This module uses the simplepie engine to ingest feeds and turns individual items from each feed into nodes. I realize that this doesn't specifically address the issue of creating nodes from cron, but it might be an easier solution to your problem overall.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Can regex capture and substitution be used with an Apache DirectoryMatch directive? Does anyone know if it's possible to use regex capture within Apache's DirectoryMatch directive? I'd like to do something like the following:
<DirectoryMatch ^/home/www/(.*)>
AuthType Basic
AuthName $1
AuthUserFile /etc/apache2/svn.passwd
Require group $1 admin
</DirectoryMatch>
but so far I've had no success.
Specifically, I'm trying to create a group-based HTTP Auth for individual directories/vhosts on a server in Apache 2.0.
For example, Site A, pointing to /home/www/a will be available to all users in group admin and group a, site b at /home/www/b will be available to all users in group admin and group b, etc. I'd like to keep everything based on the directory name so I can easily script adding htpasswd users to the correct groups and automate this as much as possible, but other suggestions for solving the problem are certainly welcome.
A: You could tackle the problem from a completely different angle: enable the perl module and you can include a little perl script in your httpd.conf. You could then do something like this:
<Perl>
my @groups = qw/ foo bar baz /;
foreach ( @groups ) {
push @PerlConfig, qq| <Directory /home/www/$_> blah </Directory> |;
}
</Perl>
That way, you could even read your groups and other information from a database or by simply globbing /home/www or whatever else tickles your fancy.
A: What you are trying to do looks very similar to per-user home directories. The way Apache handles these is through file system permissions and .htaccess files. I don't believe there is any way to use regex capture in the enclosed directives (AuthName, etc).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Any problems running SharpDevelop 3.0 and Visual Studio 2008 side by side? I have been asked to lend a hand on a hobby project that a couple friends are working on, they are using SharpDevelop 3.0 (Beta 2 I think, but it might be Beta 1) is there any hassle for me to install and use this IDE given that I have Visual Studio 2008 installed?
A: I've had no problems at all, in fact some of the tools in sharpdevelop (like the vb.net -> c# converter) are very nice to have.
In addition, there are some good libraries included with sharpdevelop that are also handy (like sharpziplib for zip files)
I actually have VS2005, VS2008, SharpDevelop and VisualStudio 6 installed at the moment, and there's more compat problems with MS's tools than with #develop.
A: They behave very well together, I have had SharpDevelop installed with 2003, 2005 and 2008. No issues at all.
A: I haven't had SharpDevelop installed for a while but when I did the only problem I ran in to was that I couldn't easily share the solution file. If you don't mind having two different solutions there should be no problems.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Should I use an exception specifier in C++? In C++, you can specify that a function may or may not throw an exception by using an exception specifier. For example:
void foo() throw(); // guaranteed not to throw an exception
void bar() throw(int); // may throw an exception of type int
void baz() throw(...); // may throw an exception of some unspecified type
I'm doubtful about actually using them because of the following:
*
*The compiler doesn't really enforce exception specifiers in any rigorous way, so the benefits are not great. Ideally, you would like to get a compile error.
*If a function violates an exception specifier, I think the standard behaviour is to terminate the program.
*In VS.Net, it treats throw(X) as throw(...), so adherence to the standard is not strong.
Do you think exception specifiers should be used?
Please answer with "yes" or "no" and provide some reasons to justify your answer.
A: gcc will emit warnings when you violate exception specifications. What I do is to use macros to use the exception specifications only in a "lint" mode compile expressly for checking to make sure the exceptions agree with my documentation.
A: The only useful exception specifier is "throw()", as in "doesn't throw".
A: Avoid exception specifications in C++. The reasons you give in your question are a pretty good start for why.
See Herb Sutter's "A Pragmatic Look at Exception Specifications".
A: Exception specifications are not wonderfully useful tools in C++. However, there /is/ a good use for them, if combined with std::unexpected.
What I do in some projects is code with exception specifications, and then call set_unexpected() with a function that will throw a special exception of my own design. This exception, upon construction, gets a backtrace (in a platform-specific manner) and is derived from std::bad_exception (to allow it to be propagated if desired). If it causes a terminate() call, as it usually does, the backtrace is printed by what() (as well as the original exception that caused it; not to hard to find that) and so I get information of where my contract was violated, such as what unexpected library exception was thrown.
If I do this, I never allow propagation of library exceptions (except std ones) and derive all my exceptions from std::exception. If a library decides to throw, I will catch and convert into my own hierarchy, allowing for me to always control the code. Templated functions that call dependent functions should avoid exception specifications for obvious reasons; but it's rare to have a templated function interface with library code anyway (and few libraries really use templates in a useful manner).
A: If you're writing code that will be used by people that would rather look at the function declaration than any comments around it, then a specification will tell them which exceptions they might want to catch.
Otherwise I don't find it particularly useful to use anything but throw() to indicate that it doesn't throw any exceptions.
A: Yes, if you're into internal documentation. Or maybe writing a libary that others will use, so that they can tell what happens without consulting the documentation. Throwing or not throwing can be considered part of the API, almost like the return value.
I agree, they are not really useful for enforcing correctness Java style in the compiler, but it's better than nothing or haphazard comments.
A: No. If you use them and an exception is thrown that you did not specify, either by your code or code called by your code, then the default behavior is to promptly terminate your program.
Also, I believe their use has been deprecated in current drafts of the C++0x standard.
A: A "throw()" specification allows the compiler to perform some optimisations when doing code flow analysis if it know that function will never throw an exception (or at least promises to never throw an exception). Larry Osterman talks about this briefly here:
http://blogs.msdn.com/larryosterman/archive/2006/03/22/558390.aspx
A: Generally I would not use exception specifiers. However, in cases where if any other exception were to come from the function in question that the program would definitively be unable to correct, then it can be useful. In all cases, make sure to document clearly what exceptions could be expected from that function.
Yes, the expected behavior of a non-specified exception being thrown from a function with exception specifiers is to call terminate().
I will also note that Scott Meyers addresses this subject in More Effective C++. His Effective C++ and More Effective C++ are highly recommended books.
A: They can be useful for unit testing so that when writing tests you know what to expect the function to throw when it fails, but there is no enforcement surrounding them in the compiler. I think that they are extra code that is not necessary in C++. Which ever you choose all that you should be sure of is that you follow the same coding standard across the project and the team members so that your code remains readable.
A: I think the standardly except convention (for C++)
Exception specifiers were an experiment in the C++ standard that mostly failed.
The exception being that the no throw specifier is useful but you should also add the appropriate try catch block internally to make sure the code matches the specifier. Herb Sutter has a page on the subject. Gotch 82
In a addition I think it is worth describing Exception Guarantees.
These are basically documentation on how the state of an object is affected by exceptions escaping a method on that object. Unfortunately they are not enforced or otherwise mentioned by the compiler.
Boost and Exceptions
Exception Guarantees
No Guarantee:
There is no guarantee about the state of the object after an exception escapes a method
In these situations the object should no longer be used.
Basic Guarantee:
In nearly all situations this should be the minimum guarantee a method provides.
This guarantees the object's state is well defined and can still be consistently used.
Strong Guarantee: (aka Transactional Guarantee)
This guarantees that the method will complete successfully
Or an Exception will be thrown and the objects state will not change.
No Throw Guarantee:
The method guarantees that no exceptions are allowed to propagate out of the method.
All destructors should make this guarantee.
| N.B. If an exception escapes a destructor while an exception is already propagating
| the application will terminate
A: No.
Here are several examples why:
*
*Template code is impossible to write with exception specifications,
template<class T>
void f( T k )
{
T x( k );
x.x();
}
The copies might throw, the parameter passing might throw, and x() might throw some unknown exception.
*Exception-specifications tend to prohibit extensibility.
virtual void open() throw( FileNotFound );
might evolve into
virtual void open() throw( FileNotFound, SocketNotReady, InterprocessObjectNotImplemented, HardwareUnresponsive );
You could really write that as
throw( ... )
The first is not extensible, the second is overambitious and the third is really what you mean, when you write virtual functions.
*Legacy code
When you write code which relies on another library, you don't really know what it might do when something goes horribly wrong.
int lib_f();
void g() throw( k_too_small_exception )
{
int k = lib_f();
if( k < 0 ) throw k_too_small_exception();
}
g will terminate, when lib_f() throws. This is (in most cases) not what you really want. std::terminate() should never be called. It is always better to let the application crash with an unhandled exception, from which you can retrieve a stack-trace, than to silently/violently die.
*Write code that returns common errors and throws on exceptional occasions.
Error e = open( "bla.txt" );
if( e == FileNotFound )
MessageUser( "File bla.txt not found" );
if( e == AccessDenied )
MessageUser( "Failed to open bla.txt, because we don't have read rights ..." );
if( e != Success )
MessageUser( "Failed due to some other error, error code = " + itoa( e ) );
try
{
std::vector<TObj> k( 1000 );
// ...
}
catch( const bad_alloc& b )
{
MessageUser( "out of memory, exiting process" );
throw;
}
Nevertheless, when your library just throws your own exceptions, you can use exception specifications to state your intent.
A: From the article:
http://www.boost.org/community/exception_safety.html
“It is well known to be impossible to
write an exception-safe generic
container.” This claim is often heard
with reference to an article by Tom
Cargill [4] in which he explores the
problem of exception-safety for a
generic stack template. In his
article, Cargill raises many useful
questions, but unfortunately fails to
present a solution to his problem.1 He
concludes by suggesting that a
solution may not be possible.
Unfortunately, his article was read by
many as “proof” of that speculation.
Since it was published there have been
many examples of exception-safe
generic components, among them the C++
standard library containers.
And indeed I can think of ways to make template classes exception safe. Unless you don't have control over all the sub-classes then you may have a problem anyway. To do this one could create typedefs in your classes that define the exceptions thrown by various template classes. This think the problem is as always tacking it on afterwards as opposed to designing it in from the start, and I think it's this overhead that's the real hurdle.
A: Exception specifications = rubbish, ask any Java developer over the age of 30
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "134"
}
|
Q: Structure of a PDF file? For a small project I have to parse pdf files and take a specific part of them (a simple chain of characters). I'd like to use python to do this and I've found several libraries that are capable of doing what I want in some ways.
But now after a few researches, I'm wondering what is the real structure of a pdf file, does anyone know if there is a spec or some explanations anywhere online? I've found a link on adobe but it seems that it's a dead link :(
A: I'm trying to do pretty much the same thing. The PDF reference is a very difficult document to read. This tutorial is a better start I think.
A: This may help shed a little light:
(from page 11 of PDF32000.book)
PDF syntax is best understood by considering it as four parts, as shown in Figure 1:
• Objects. A PDF document is a data structure composed from a small set of basic types of data objects.
Sub-clause 7.2, "Lexical Conventions," describes the character set used to write objects and other
syntactic elements. Sub-clause 7.3, "Objects," describes the syntax and essential properties of the objects.
Sub-clause 7.3.8, "Stream Objects," provides complete details of the most complex data type, the stream
object.
• File structure. The PDF file structure determines how objects are stored in a PDF file, how they are
accessed, and how they are updated. This structure is independent of the semantics of the objects. Sub-
clause 7.5, "File Structure," describes the file structure. Sub-clause 7.6, "Encryption," describes a file-level
mechanism for protecting a document’s contents from unauthorized access.
• Document structure. The PDF document structure specifies how the basic object types are used to
represent components of a PDF document: pages, fonts, annotations, and so forth. Sub-clause 7.7,
"Document Structure," describes the overall document structure; later clauses address the detailed
semantics of the components.
• Content streams. A PDF content stream contains a sequence of instructions describing the appearance of
a page or other graphical entity. These instructions, while also represented as objects, are conceptually
distinct from the objects that represent the document structure and are described separately. Sub-clause
7.8, "Content Streams and Resources," discusses PDF content streams and their associated resources.
Looks like navigating a PDF file will require a little more than a passing effort.
A: If You want to parse PDF using Python please have a look at PDFMINER. This is the best library to parse PDF files till date.
A: Here is a link to Adobe's reference material
http://www.adobe.com/devnet/pdf/pdf_reference.html
You should know though that PDF is only about presentation, not structure. Parsing will not come easy.
A: I found the GNU Introduction to PDF to be helpful in understanding the structure. It includes an easily readable example PDF file that they describe in complete detail.
Other helpful links:
*
*PDF Succinctly book is longer and has helpful pictures.
*Introduction to the Insides of PDF is a presentation that isn't as in-depth but gives a quick overview and has lots of pictures.
A: Didier have a tool to parse the PDF:
http://didierstevens.com/files/software/pdf-parser_V0_4_3.zip
or here:
http://blog.didierstevens.com/programs/pdf-tools/ which cataloged several related pdf-analysis tools.
Another tool is here:
http://mshahzadlatif.wordpress.com/2011/09/28/view-pdf-structure-using-adobe-acrobat-or-a-free-tool-called-pdfxplorer/
A: When I first started working with PDF, I found the PDF reference very hard to navigate.
It might help you to know that the overview of the file structure is found in syntax, and what Adobe call the document structure is the object structure and not the file structure. That is also found in Syntax. The description of operators is hidden away in Appendix A - very useful for understanding what is happening in content streams. If you ever have the pain of working with colour spaces you will find that hidden in Graphics! Hopefully these pointers will help you find things more quickly than I did.
If you are using windows, pdftron CosEdit allows you to browse the object structure to understand it. There is a free demo available that allows you to examine the file but not save it.
A: Extracting text from PDF is a hard problem because PDF has such a layout-oriented structure. You can see the docs and source code of my barely-successful attempt on CPAN (my implementation is in Perl). The PDF data structure is very cool and well designed, but it's easier to write than read.
A: One way to get some clues is to create a PDF file consisting of a blank page. I have CutePDF Writer on my computer, and made a blank Wordpad document of one page. Printed to a .pdf file, and then opened the .pdf file using Notepad.
Next, use a copy of this file and eliminate lines or blocks of text that might be of interest, then reload in Acrobat Reader. You'd be surprised at how little information is needed to make a working one-page PDF document.
I'm trying to make up a spreadsheet to create a PDF form from code.
A: You need the PDF Reference manual to start reading about the details and structure of PDF files. I suggest to start with version 1.7.
On windows I used a free tool PDF Analyzer to see the internal structure of PDF files.
This will help in your understanding when reading the reference manual.
(I'm affiliated with PDF Analyzer, no intention to promote)
A: Here's the raw reference of PDF 1.7, and here's an article describing the structure of a PDF file. If you use Vim, the pdftk plugin is a good way to explore the document in an ever-so-slightly less raw form, and the pdftk utility itself (and its GPL source) is a great way to tease documents apart.
A: To extract text from a PDF, try this on Linux, BSD, etc. machine or use Cygwin if on Windows:
pdfinfo -layout some_pdf_file.pdf
A plain text file named some_pdf_file.txt is created. The simpler the PDF file layout, the more straightforward the .txt file output will be.
Hexadecimal characters are frequently present in the .txt file output and will look strange in text editors. These hexadecimal characters usually represent curly single and double quotes, bullet points, hyphens, etc. in the PDF.
To see the context where the hexadecimal characters appear, run this grep command, and keep the original PDF handy to see what character the codes represent in the PDF:
grep -a --color=always "\\\\[0-9][0-9][0-9]" some_pdf_file.txt
This will provide a unique list of the different octal codes in the document:
grep -ao "\\\\[0-9][0-9][0-9]" some_pdf_file.txt|sort|uniq
To convert these hexadecimal characters to ASCII equivalents, a combination of grep, sed, and bc can be used, I'll post the procedure to do that soon.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "82"
}
|
Q: How do I split a string containing a math expression into a list? How do I tokenize the string:
"2+24*48/32"
Into a list:
['2', '+', '24', '*', '48', '/', '32']
A: This is a parsing problem, so neither regex not split() are the "good" solution. Use a parser generator instead.
I would look closely at pyparsing. There have also been some decent articles about pyparsing in the Python Magazine.
A: It just so happens that the tokens you want split are already Python tokens, so you can use the built-in tokenize module. It's almost a one-liner; this program:
from io import StringIO
from tokenize import generate_tokens
STRING = 1
print(
list(
token[STRING]
for token in generate_tokens(StringIO("2+24*48/32").readline)
if token[STRING]
)
)
produces this output:
['2', '+', '24', '*', '48', '/', '32']
A:
s = "2+24*48/32"
p = re.compile(r'(\W+)')
p.split(s)
A: Regular expressions:
>>> import re
>>> splitter = re.compile(r'([+*/])')
>>> splitter.split("2+24*48/32")
You can expand the regular expression to include any other characters you want to split on.
A: Another solution to this would be to avoid writing a calculator like that altogether. Writing an RPN parser is much simpler, and doesn't have any of the ambiguity inherent in writing math with infix notation.
import operator, math
calc_operands = {
'+': (2, operator.add),
'-': (2, operator.sub),
'*': (2, operator.mul),
'/': (2, operator.truediv),
'//': (2, operator.div),
'%': (2, operator.mod),
'^': (2, operator.pow),
'**': (2, math.pow),
'abs': (1, operator.abs),
'ceil': (1, math.ceil),
'floor': (1, math.floor),
'round': (2, round),
'trunc': (1, int),
'log': (2, math.log),
'ln': (1, math.log),
'pi': (0, lambda: math.pi),
'e': (0, lambda: math.e),
}
def calculate(inp):
stack = []
for tok in inp.split():
if tok in self.calc_operands:
n_pops, func = self.calc_operands[tok]
args = [stack.pop() for x in xrange(n_pops)]
args.reverse()
stack.append(func(*args))
elif '.' in tok:
stack.append(float(tok))
else:
stack.append(int(tok))
if not stack:
raise ValueError('no items on the stack.')
return stack.pop()
if stack:
raise ValueError('%d item(s) left on the stack.' % len(stack))
calculate('24 38 * 32 / 2 +')
A: You can use split from the re module.
re.split(pattern, string, maxsplit=0, flags=0)
Split string by the occurrences of pattern. If capturing parentheses
are used in pattern, then the text of all groups in the pattern are
also returned as part of the resulting list.
Example code:
import re
data = re.split(r'(\D)', '2+24*48/32')
\D
When the UNICODE flag is not specified, \D matches any non-digit
character; this is equivalent to the set [^0-9].
A: This looks like a parsing problem, and thus I am compelled to present a solution based on parsing techniques.
While it may seem that you want to 'split' this string, I think what you actually want to do is 'tokenize' it. Tokenization or lexxing is the compilation step before parsing. I have amended my original example in an edit to implement a proper recursive decent parser here. This is the easiest way to implement a parser by hand.
import re
patterns = [
('number', re.compile('\d+')),
('*', re.compile(r'\*')),
('/', re.compile(r'\/')),
('+', re.compile(r'\+')),
('-', re.compile(r'\-')),
]
whitespace = re.compile('\W+')
def tokenize(string):
while string:
# strip off whitespace
m = whitespace.match(string)
if m:
string = string[m.end():]
for tokentype, pattern in patterns:
m = pattern.match(string)
if m:
yield tokentype, m.group(0)
string = string[m.end():]
def parseNumber(tokens):
tokentype, literal = tokens.pop(0)
assert tokentype == 'number'
return int(literal)
def parseMultiplication(tokens):
product = parseNumber(tokens)
while tokens and tokens[0][0] in ('*', '/'):
tokentype, literal = tokens.pop(0)
if tokentype == '*':
product *= parseNumber(tokens)
elif tokentype == '/':
product /= parseNumber(tokens)
else:
raise ValueError("Parse Error, unexpected %s %s" % (tokentype, literal))
return product
def parseAddition(tokens):
total = parseMultiplication(tokens)
while tokens and tokens[0][0] in ('+', '-'):
tokentype, literal = tokens.pop(0)
if tokentype == '+':
total += parseMultiplication(tokens)
elif tokentype == '-':
total -= parseMultiplication(tokens)
else:
raise ValueError("Parse Error, unexpected %s %s" % (tokentype, literal))
return total
def parse(tokens):
tokenlist = list(tokens)
returnvalue = parseAddition(tokenlist)
if tokenlist:
print 'Unconsumed data', tokenlist
return returnvalue
def main():
string = '2+24*48/32'
for tokentype, literal in tokenize(string):
print tokentype, literal
print parse(tokenize(string))
if __name__ == '__main__':
main()
Implementation of handling of brackets is left as an exercise for the reader. This example will correctly do multiplication before addition.
A: >>> import re
>>> re.findall(r'\d+|\D+', '2+24*48/32=10')
['2', '+', '24', '*', '48', '/', '32', '=', '10']
Matches consecutive digits or consecutive non-digits.
Each match is returned as a new element in the list.
Depending on the usage, you may need to alter the regular expression. Such as if you need to match numbers with a decimal point.
>>> re.findall(r'[0-9\.]+|[^0-9\.]+', '2+24*48/32=10.1')
['2', '+', '24', '*', '48', '/', '32', '=', '10.1']
A: >>> import re
>>> my_string = "2+24*48/32"
>>> my_list = re.findall(r"-?\d+|\S", my_string)
>>> print my_list
['2', '+', '24', '*', '48', '/', '32']
This will do the trick. I have encountered this kind of problem before.
A: i'm sure Tim meant
splitter = re.compile(r'([\D])').
if you copy exactly what he has down you only get the digits not the operators.
A: This doesn't answer the question exactly, but I believe it solves what you're trying to achieve. I would add it as a comment, but I don't have permission to do so yet.
I personally would take advantage of Python's maths functionality directly with exec:
expression = "2+24*48/32"
exec "result = " + expression
print result
38
A: Here is a good way that I always use when splitting str with different special characters. However, this code does not work with _, if there is a _ in the str you want to split, you might need to do another split one more time.
import re
# initializing string
data = "2+24*48/32"
# printing original string
print("The original string is : " + data)
# Using re.findall()
# Splitting characters in String
res = re.findall(r"[\w']+", data)
# printing result
print("The list after performing split functionality : " + str(res))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
}
|
Q: What algorithm can you use to find duplicate phrases in a string? Given an arbitrary string, what is an efficient method of finding duplicate phrases? We can say that phrases must be longer than a certain length to be included.
Ideally, you would end up with the number of occurrences for each phrase.
A: In theory
*
*A suffix array is the 'best' answer since it can be implemented to use linear space and time to detect any duplicate substrings. However - the naive implementation actually takes time O(n^2 log n) to sort the suffixes, and it's not completely obvious how to reduce this down to O(n log n), let alone O(n), although you can read the related papers if you want to.
*A suffix tree can take slightly more memory (still linear, though) than a suffix array, but is easier to implement to build quickly since you can use something like a radix sort idea as you add things to the tree (see the wikipedia link from the name for details).
*The KMP algorithm is also good to be aware of, which is specialized for searching for a particular substring within a longer string very quickly. If you only need this special case, just use KMP and no need to bother building an index of suffices first.
In practice
I'm guessing you're analyzing a document of actual natural language (e.g. English) words, and you actually want to do something with the data you collect.
In this case, you might just want to do a quick n-gram analysis for some small n, such as just n=2 or 3. For example, you could tokenize your document into a list of words by stripping out punctuation, capitalization, and stemming words (running, runs both -> 'run') to increase semantic matches. Then just build a hash map (such as hash_map in C++, a dictionary in python, etc) of each adjacent pair of words to its number of occurrences so far. In the end you get some very useful data which was very fast to code, and not crazy slow to run.
A: Like the earlier folks mention that suffix tree is the best tool for the job. My favorite site for suffix trees is http://www.allisons.org/ll/AlgDS/Tree/Suffix/. It enumerates all the nifty uses of suffix trees on one page and has a test js applicaton embedded to test strings and work through examples.
A: Suffix trees are a good way to implement this. The bottom of that article has links to implementations in different languages.
A: Like jmah said, you can use suffix trees/suffix arrays for this.
There is a description of an algorithm you could use here (see Section 3.1).
You can find a more in-depth description in the book they cite (Gusfield, 1997), which is on google books.
A: suppose you are given sorted array A with n entries (i=1,2,3,...,n)
Algo(A(i))
{
while i<>n
{
temp=A[i];
if A[i]<>A[i+1] then
{
temp=A[i+1];
i=i+1;
Algo(A[i])
}
else if A[i]==A[i+1] then
mark A[i] and A[i+1] as duplicates
}
}
This algo runs at O(n) time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How do you include a JavaScript file from within a SharePoint WebPart? We have a medium sized .js file that we include in our web framework that I am porting over to SharePoint. However, I'm not sure how to go about this or what the best practice is. This is for a framework solution that will be used by other client projects, so it's best for it to be self contained and deploy-able, rather than requiring manually deploying files to the webserver.
My current thinking to put the JavaScript into an embedded resource and then use the script manager to write out the file. Does this seem reasonable? Or does anyone have any other recommendations?
A: Embeded resource is the best way and you don't need to use the ScriptManager to render it out (as AJAX is not configured OoB on SharePoint), you can just render it as any other client script resource (through the ClientScriptManager).
Best idea is the have an if ContainsScriptManager else UsClientScriptManager style.
That way you get the best of both worlds
A: You could just toss it into a doc library.
If you are packaging your web part into a sharepoint solution, you could include it as a Module (VSEWSS item). Your manifest file would get something like:
<TemplateFiles>
<TemplateFile Location="LAYOUTS\somescript.js" />
</TemplateFiles>
Theres lots of info on how to do this on the web. I've liked the doc library option for images, css, and javascript because I don't have to rebuild and wait for for SP to JIT compile for 30 seconds each time I do a minor tweak to some style or script. I just edit these things in SPDesigner right out of the doc library.
A: Create resource mapped folder in your project and put the js file there and give the referene of the js file as _layout/jsfilename.js and this js file will be deployed with your project where ever you will deploy it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Best platform for learning embedded programming? I'm looking to learn about embedded programming (in C mainly, but I hope to brush up on my ASM as well) and I was wondering what the best platform would be. I have some experience in using Atmel AVR's and programming them with the stk500 and found that to be relatively easy. I especially like AVR Studio and the debugger that lets you view that state of registers.
However, If I was to take the time to learn, I would rather learn about something that is prevalent in industry. I am thinking ARM, that is unless someone has a better suggestion.
I would also be looking for some reference material, I have found the books section on the ARM website and if one is a technically better book than another I would appreciate a heads up.
The last thing I would be looking for is a prototyping/programming board like the STK500 that has some buttons and so forth.
Thanks =]
A: Myself I've worked in embedded programming for 9 years now and have experience on TI MSP430, Atmel AVR (a couple of flavours) and will be using an ARM soon.
My suggestion is to pickup something that has some extra features in the processor like ethernet controller and CAN controller, even get two or three if you can. Embedded devices are nice to work with, but once they can talk to other similar devices via CAN or get onto a network, they can become much more fun to play with.
A: ADI's Blackfin is another option since it's quite a straight forward architecture to program, yet can also do some fairly hefty DSP stuff should you choose to go down that route. It helps that the assembly language is quite sane too.
The Blackfin STAMP boards are an inexpensive (~$100 last I checked) way in, and they support the free GCC tools and uClinux.
Whatever architecture you choose I'd definitely recommend first downloading the toolchain\SDK and looking through the sample projects and tutorials - generally having a bit of a play about. You can often get quite acquainted with the architecture through simulation without even touching any hardware.
A: ARM has the nicest instruction set of the widely used embedded platforms, leaving you free to pick up the general principles of writing software for embedded platforms without getting bogged down in weird details like non-orthogonal registers or branch delay slots. There are plenty of emulators - ARM's own, while not free, is cycle-accurate; and a huge variety of programmable ARM-based hardware is cheap and easy to come by as well.
A: The TI MSP430 is a great platform for learning how to program microcontrollers. TI has a variety of FREE Tools and some cheap evaluation boards (starting at $20). Plus, it's a low-power, modern microcontroller.
A: "embedded programming" is a very broad term. AVR is pretty well in that category, but it's a step below ARM, in that it's both simpler to use, as well as less powerful.
If you just want to play around with ARM, buy a Nintendo DS or a Gameboy Advance. These are very cheap compared to the hardware inside (wonders of mass production), and they both have free development toolchains based off of gcc which can compile to them.
If you want to play around with embedded linux, BeagleBoard is looking to be a good option, only $150 and it has a ton of features.
Personally I think AVR is best for the smaller-sized 8-bit platforms, and ARM is best for the larger, more powerful 32-bit based platforms. Like many AVR fans, I don't like PIC. It just seems worse in pretty much every way. Also avoid anything that requires you to write any type of BASIC.
A: A nice choice would be PIC18 by Microchip
*
*It has quite alot of material, documentation, tutorials and projects on the internet
*Free IDE and compiler.
*you can pull your own flash writer in a few minutes.
(Although for a debugger to work you'll need to work harder)
*If you're a student (or has a student email address) Microchip will send you free sample chips. So basically you can have a full development environment for close to nothing.
*PICs are quite prevalent in the industry. Specifically as controllers for robots for some reason although they can do so much more.
A: Arduino seems to be the platform of choice these days for beginners although there are lots of others. I like the Olimex boards personally but they are not really for beginners.
Microchip's PIC range of CPUs are also excellent for beginners, especially if you want to program in assembler.
BTW, Assembler is not used as much as it used to. The general rule with embedded is if you've got 4k of memory or more, use C. You get portability and you can develop code faster.
I suppose it depends on your skill level and what you want to do with the chip. I usually choose which embedded chip to use by the available peripherals. If you want a USB port, find one with USB built in, if you want analogue-to-digital, find one with an ADC etc. If you've got a simple application, use an 8-bit but if you need serious number crunching, go 32 bits.
A: I'd like to suggest the beagleboard from TI. It has a Omap3 on it. That's a Cortex-A8 ARM11 CPU, a C64x+ DSP and a video accelerator as well.
The board does not need an expensive jtag device. A serial cable an an SD-Card is all you need to get started. Board costs only $150 and there is a very active community.
www.beagleboard.org
A: If you just want to play around with it, I'd suggest the Arduino platform (http://www.arduino.cc). It's based on the ATmega168 or ATmega8, depending on the version. It uses a C-like language and has its own IDE.
A: Your question sort of has been answered in this question.
To add to that, the embedded processor industry is very segmented, it doesn't have a major player like Intel/x86 is for the "desktop" processor industry. The ARM processor does have a large share, so does MIPS I believe, and there are many smaller more specific microcontroller like chips available (like the MSP430 etc from TI).
As for documentation, I do embedded development for a day job, and the documentation we have access to (as software developers) is rather sparse. Your best bet is to use the documentation available on the processor manufacturers site.
A: Take a look at Processing and the associated Arduino and Wiring boards.
A: If you just want to have fun, then try the Parallax Propeller chip. The HYDRA game platform looks like a blast. There's a $100 C compiler for it now.
I started on BASIC stamps, moved up through SX chips and PICs into 8051s, then 68332s, various DSPs, FPGA soft processors, etc.
8051s are more useful in the real world... the things won't go away. There's TONS of derivatives and crazy stuff for them. (Just stay away from the DS80C400) The energy industry is absolutely full of them.
Start with something tiny. If you have external RAM and plenty of registers... what's the difference between that and a SBC?
A: Many moons ago I've worked with 8-bitters like 68HC05 and Z80, later AVR and MSP430 (16-bit). However most recent projects were on ARM7. Several manufacturers offer ARM controllers, in all colors and sizes (well, not really color).
ARM(7) is replacing 8-bit architecture: it's more performant (32-bit RISC at faster instruction cycles than most 8-bitters), has more memory and is available with several IO-configurations.
I worked with NXP LPC2000 controllers, which are also inexpensive (< 1 USD for a 32-bitter!).
If you're in Europe http://www.olimex.com/dev/index.html has some nice low-cost development boards. Works in the rest of the world too :-)
A: For a fun project to test, have a look at xgamestation
But for a more industrial used one chip solution programming, look at PIC
A: For my Computer Architecture course I had to work with both a PIC and an AVR; in my opinion the PIC was easier to work with, but that's maybe because that's what we worked with the most and we had the most time to get used to. We used the AVR maybe only a couple of times so I couldn't get the hang of it perfectly but it also was nothing overly complicated, or at least not more frustrating than the other.
I think you can also order microprocessor samples from Microchip's website so you could also get started with that?
A: Second that:
Arduino platform http://www.arduino.cc
HTH
A: For learning, you can't go past the AVR. The chips are cheap and they'll run with zero external components - they also supply enough current to drive an LED straight from the port.
You can start with a cheap programmer such as lady-ada's USBTinyISP (USD$22 for a kit) which can power your board with 5V from the USB port. Get the free tools WinAVR (GCC based) and AVRStudio and get a small project working in no time.
Yes the AVRs have limitations - but developing software for microcontrollers is largely about managing resources and coping with those problems. It's unlikely that you'll experience problems such as running out of stack space, RAM or ROM when you're making hobbist projects for powerful ARM platforms.
That said, ARM is also a great platform which is widely used in the industry, however, for learning I highly recommend AVRs.
A: I would suggest Microchip's PIC18F series. I just started developing for them with the RealICE in-circuit emulator, but the pickit2 is a decent debugger for the price. You could say this for the AVR's also, but there is a large following for the device all over the web. I was able to have a - buggy, yet functional - embedded USB device running within days due to all the PIC related chatter.
The only thing I don't like about the PICs is that a lot of the sample code is VERY entwined into the demo boards. That can make it hard to tear out sections that you need and still have an application that will build and run for your application.
A: Texas Instruments has released a very interesting development kit at a very low price: The eZ430-Chronos Development Tool contains an MSP430 with display and various sensors in a sports watch, including a usb debug programmer and a usb radio access point for 50$
There is also a wiki containing lots and lots of information.
I have already created a stackexchange proposal for the eZ430-Chronos Kit.
A: You should try and learn from developpers kits provided by Embedded Artists. After you get the kit, check their instructional videos and videos provided by NXP, which are not as detailed as they could be, but they cover a lot of things. Problems with learning ARM as your first architecture and try to do something practicall are:
*
*You need to buy dev. kit.
*You need a good book to learn ARM assembly, because sooner or later you will come across ARM startup code, which is quite a deal for a beginner. The book i mentioned allso covers some C programming.
*Combine book mentioned above with a user guide for your speciffic processor like this one. Make sure you get this as studying this in combination with above book is the only way to learn your ARM proc. in detail.
*If you want to make a transfer from ARM assembly to C programming you will need to read this book, which covers a different ARM processor but is easier for C beginner. The down side is that it doesn't explain any ARM assembly, but this is why you need the first book.
There is no easy way.
A: mikroElektronika has nice ARM boards and C, Pascal and Basic compilers that might suite your demands.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: How do you do performance testing in Ruby webapps? I've been looking at ways people test their apps in order decide where to do caching or apply some extra engineering effort, and so far httperf and a simple sesslog have been quite helpful.
What tools and tricks did you apply on your projects?
A: I use httperf for a high level view of performance.
Rails has a performance script built in, that uses the ruby-prof gem to analyse calls deep within the Rails stack. There is an awesome Railscast on Request Profiling using this technique.
NewRelic have some seriously cool analysis tools that give near real-time data.
They just made it a "Lite" version available for free.
A: I use jmeter for session-based testing - it allows very fine-grained control over pages you want to hit, parameters to inject, loops to go through, etc. It's great for simulating how many real users your site can handle, rather than just performance testing a set of static urls. You can distribute tests over multiple machines quite easily by loading up the jmeter-server on computers with publicly accessible IP's. I have found some limitations in the number of users/threads any one machine can throw at a server at once (it depends on the test), but jmeter has helped my team improve our apps capacity for users to 6x.
It doesn't have any fancy graphing -- I actually use my own in-house graphing with gruff that can do performance analysis on request time for certain pages and actions.
A: I'm evaluating a new opensource web page instrumentation and measurement suite called Jiffy. It's not particularly for ruby, it works for all kind of webapps
There's also a Jiffy Firebug Extension for rendering the metrics inside the browser.
A: I also suggest you look at Browser Mob for load testing.
A: A colleague of mine has also posted some interesting thoughts on this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Kerberos Delegation for Clients Ouside the Firewall I am trying to run a SQL Server Reporting Services where the data for the report is on a SQL Server database that's on a different server. Integrated Authentication is turned on for both the Report Server and the report. I have confirmed that Kerberos delegation is working fine by using Internet Explorer to run the report from inside the network.
However, when I open the report server through the firewall, I cannot run the report. I get the following error: An error has occurred during report processing. Cannot create a connection to data source 'frattoxppro2'. Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.
Does Kerberos authentication not work outside a firewall?
A: Kerberos requires a port 88 connection to the KDC, in this case, most likely your DC.
What you probably want to look at is HTTPS + Basic Authentication + Protocol Transition to take the Basic Authentication and translate it into a DC based Kerberos Ticket for delegation and back end authentication.
*
*Protocol Transition with
Constrained Delegation Technical
Supplement
*How To: Use Protocol Transition and
Constrained Delegation in
ASP.NET
Not exactly the easiest to set up, but when its working, it works amazingly well.
A: I'm not really in a position to tell you why kerberos isn't working for you, but did have a alternative suggestion for your configuration. You can use ISA services to expose the reporting server rather than simply poking a hole in your firewall. This is something our company has done successfully - it republishes the reporting services site so the browsers are talking to ISA, not directly to the server. ISA Services is quite happy to pass through your credentials as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Best way of getting notifications in SQL Server Reporting Services using Notification Services Is it possible to get notifications using SQL Server Reporting Services? Say for example I have a report that I want by mail if has for example suddenly shows more than 10 rows or if a specific value drop below 100 000. Do I need to tie Notification Services into it and how do I do that?
Please provide as much technical details as possible as I've never used Notification Services before.
Someone also told me that Notifications Services is replaced by new functionality in Reporting Services in Sql Server 2008 - is this the case?
A: I'd agree with Simon re Notification Services
Also, data driven SSRS Subscriptions are not available unless you use Enterprise Edition (and isn't available if you use SharePoint Integrated Mode).
An alternate way would be to create an Agent job that runs a proc. The proc could check the conditions you require and kick off the subscription if they are met using:
exec ReportServer.dbo.AddEvent @EventType='TimedSubscription', @EventData='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx'
Where the @EventData is the ID of the subscription in dbo.Subscriptions.
This will drop a row in [dbo].[Event]. The Service polls this table a few times a minute to kick off subscriptions.
Really, this isn't far from what happens when you set up a new Subscription, might even be easier to create a Subscription in the Report Server site, find which agent job was created (the ones with GUID names) and edit the T-SQL.
Hope this helps
A: I wouldn't go down the ntofications services route - it is pretty much a deprecated feature of SQL Server and even if it is around in future it will stagnate. So don't build a dependency on it.
A: Depending on your needs a data driven SSRS subscription to e-mail you the report would probably work.
http://msdn.microsoft.com/en-us/library/ms159150(SQL.90).aspx
A: Sending mail using SSRS subscription to your data driven report
A: A data-driven subscription is composed of multiple parts. The fixed aspects of a data-driven subscription are defined when you create the subscription, and these include the following:
The report for which the subscription is defined (a subscription is always associated with a single report).
The delivery extension used to distribute the report. You can specify report server e-mail delivery, file share delivery, the null delivery provider used for preloading the cache, or a custom delivery extension. You cannot specify multiple delivery extensions within a single subscription.
The subscriber data source. You must specify a connection string to the data source that contains subscriber data when you define the subscription. The subscriber data source cannot be specified dynamically at run time.
The query that you use to select subscriber data must be specified when you define the subscription. You cannot change the query at run time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What's the best way to serialize a HashTable for SOAP/XML? What's the best way to serialize a HashTable (or a data best navigated through a string indexer) with SOAP/XML?
Let's say I have a Foo that has an property Bar[] Bars. A Bar object has a key and a value. By default, this serializes to the following XML:
<Foo>
<Bars>
<Bar key="key0" value="value0"/>
...
</Bars>
</Foo>
For JSON, this serializes to:
{"Foo":["Bars":[{"Key":"key0","Value":"key1} ... ]}]}
What I'd really like to have is this serialize to better reflect the underlying relationship. E.g.,
<Foo>
<Bars>
<Key0 value="value0"/>
<Key1 value="value1"/>
...
</Bars>
</Foo>
I realize there are some challenges with serializing to SOAP in this way, but what's the best approach to providing a schema that better reflects this?
I've tried creating a BarsCollection object and defining custom serialization on that, but it doesn't seem to actually invoke the serialization on that object. E.g.
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
foreach (Bar bar in Bars){
info.AddValue(bar.Key. bar);
}
}
Any suggestions? What's the best practice here?
A: I really don't think that what you want reflects the structure better. To define a schema (think XSD) for this you would have to know all of the potential keys in advance since you indicate that you want each one to be a separate custom type. Conceptually Bars would be an array of objects holding objects of type Key0, Key1, with each of the KeyN class containing a value property. I believe that the first serialization actually is the best reflection of the underlying structure. The reason it "works" more like you want in JSON is that you lose the typing -- everything is just an object. If you don't care about the types why not just use JSON?
A: ISerializable isn't used for xml serialization; its used for binary serialization. You would be better implementing IXmlSerializable.
But I think that the KeyedCollection serializes more like you're thinking. Except you'll never get <key0 ... /> <key1 ... /> since the elements map to classes.
A: You could pass the hashtable in a SOAP Extension. That way, you can serialize it whichever way you would like. Although there is custom code for this that has to be on the client and server.
A: I think you're missing a fundamental key of the SOAP protocol.
One of the things I really like about the SOAP protocol is that you can define arbitrary objects (along with methods) in your WSDL file and pass these objects around from one end to the other using the SOAP protocol. You don't have to serialize the data on one end and then unserialize it on the other end.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: what's the best app to draw UI wireframes on the mac? (And why) I want to draw user interfaces for web and desktop applications.
I need something less print-oriented than omnigraffle. think pixels!
Also, need good building blocks (aka stencils). Form elements, tableviews, etc.
A: I've been playing around with Balsamiq Mockups and it's OK for basic wireframes. I still prefer pen and paper sketches that are later refined in Photoshop when working on my own, but Balsamiq is useful when working in a team.
A: WireframeSketcher wireframing tool comes with fast and native UI on Mac. It works well with retina display too. There is a large built-in library of controls and extra stencils are available.
A: I very much like Omnigraffle, with stencils for UI design. More UI stencils are also available.
You might also check some other stackoverflow questions on this topic.
A: I'll be honest - I find Interface Builder just as fast as using Omnigraffle with (the aforementioned) stencils for prototyping desktop application UIs.
Plus the bonus is you get all of the available controls to look at.
A: Speaking of Illustrator, InDesign is actually better because you can do multipage layouts and use master pages for constants like headers/nav etc...
A: Axure just released Axure RP 5.6 for mac in Alpha. Great for websites and apps. http://axure.com/CS/blogs/axure/archive/2009/12/22/6104.aspx
You can also pair OmniGraffle with the free Web UX Template from Konigi.com
A: All these answers, and nobody has mentioned the grandaddy of them all?
Use Adobe Illustrator!
Create your own stencils / reusable components in layers and share those between documents.
A: Sharpie and paper first.
Then MAYBE illustrator to show detail close-ups if necessary.
A: With anything except Interface Builder you're going to have to get the standard UI control templates from somewhere else or make them yourself.
I've been using Lineform, which turns out to be pretty good at specifying dimensions in Pixels (just select "Points / Pixels" as the Measurement Unit in Lineform Preferences). That was something I had trouble doing in older versions of OmniGraffle (haven't used it lately though).
A: Try Skitch. It seems to be one of the best kept secrets for simple drawing and image manipulation on the Mac. I heard about it recently on TMO Geek Gab podcast.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How Does Relational Theory Apply in Ways I can Care About while Learning it? So I'm taking the Discrete Math course from MIT's OpenCourseWare and I'm wondering... I see the connection between relations and graphs but not enough to "own" it. I've implemented a simple state machine in SQL as well so I grok graphs pretty well, just not the more rigorous study of how relations and sets compeltely apply. Should I just be following the Yegge train of thought where I just glance over the stuff that I'm not grokking readily and come back when I've learned more? I'd like to be able to better analyze the graph structures I create on a day to day basis (sounds fun) and I want to make sure I'm not passing up valuable information right now.
(EDIT: I'd like to get a better idea of how the different set and relation properties relate to things like graph theory and how basic graph theory relates to sets/relations.)
Any good resources where I could learn more about this? I'm using the 5th edition of Discrete Mathematics and Its Applications by Rosen in case it matters.
Thanks!
A: wow, 4 hours and no answer; i had a similar experience in school but just learned the stuff and figured out what it was good for later. it turns out to be very useful, so let's see if this helps -
a database is formally defined as a set of relations, but it is also a graph; each table is a node, each column is a node connected to the table, each row is a node connected to the table, each field is a node connected to the row, relationships between tables interconnect nodes, foreign-key relationships interconnect rows, query constraints (where clauses) and joins interconnect nodes and sets of nodes, and so on.
An SQL query may be visualized as traversing the graph formed by the database relations and values and performing operations on each node. Under the hood that is what the query execution planner does, it breaks down the query into a set of fundamental operations and arranges them in a graph that is most efficient.
Updates to your database may also be thought of as graph operations, e.g. updating the quantity in an order line item row propagates the change to the the total in the order row, which propagates the change to the TotalSales in the Customer row, and so on.
many common problems devolve into graph-traversal problems. Ever used Google Maps to get directions to some place?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Reporting Services Deployment I need to create a repeatable process for deploying SQL Server Reporting Services reports. I am not in favor of using Visual Studio and or Business Development Studio to do this. The rs.exe method of scripting deployments also seems rather clunky. Does anyone have a very elegant way that they have been able to deploy reports. The key here is that I want the process to be completely automated.
A: I used the script @David supplied but I had to add some code (I'm typing this up as an answer, as this would be too long for a comment.
The problem is: if there is already a "shared datasource" attached to a report in the report definition, this is never the same datasource as the one that is created in the script.
This also becomes apparent from the warning emitted by the "CreateReport" method:
The data set '' refers to the shared data source '', which is not published on the report server.
So the data source has to be set explicitly afterwards. I've made the following code changes:
I added a global variable:
Dim dataSourceRefs(0) As DataSource
At the end of the CreateDataSource method, that variable gets filled:
Dim dsr As New DataSourceReference
dsr.Reference = "/" + parentFolder + "/" + db
Dim ds As New DataSource
ds.Item = CType(dsr, DataSourceDefinitionOrReference)
ds.Name = db
dataSourceRefs(0) = ds
And in the PublishReport method, that data source gets explicitly set (after CreateReport has been called):
rs.SetItemDataSources(targetFolder + "/" + reportName.Substring(0, reportName.Length - 4), dataSourceRefs)
Note that this last call is only RS 2005 or higher. If you want to load your reports onto a RS 2000 server, you have to use SetReportDataSources in stead:
rs.SetReportDataSources(targetFolder + "/" + reportName.Substring(0, reportName.Length - 4), dataSourceRefs)
A: We use rs.exe, once we developed the script we have not needed to touch it anymore, it just works.
Here is the source (I slightly modified it by hand to remove sensitive data without a chance to test it, hope I did not brake anything), it deploys reports and associated images from subdirectories for various languages. Also datasource is created.
'=====================================================================
' File: PublishReports.rss
'
' Summary: Script that can be used with RS.exe to
' publish the reports.
'
' Rss file spans from beginnig of this comment to end of module
' (except of "End Module").
'=====================================================================
Dim langPaths As String() = {"en", "cs", "pl", "de"}
Dim filePath As String = Environment.CurrentDirectory
Public Sub Main()
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
'Create parent folder
Try
rs.CreateFolder(parentFolder, "/", Nothing)
Console.WriteLine("Parent folder created: {0}", parentFolder)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
PublishLanguagesFromFolder(filePath)
End Sub
Public Sub PublishLanguagesFromFolder(ByVal folder As String)
Dim Lang As Integer
Dim langPath As String
For Lang = langPaths.GetLowerBound(0) To langPaths.GetUpperBound(0)
langPath = langPaths(Lang)
'Create the lang folder
Try
rs.CreateFolder(langPath, "/" + parentFolder, Nothing)
Console.WriteLine("Parent lang folder created: {0}", parentFolder + "/" + langPath)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
'Create the shared data source
CreateDataSource("/" + parentFolder + "/" + langPath)
'Publish reports and images
PublishFolderContents(folder + "\" + langPath, "/" + parentFolder + "/" + langPath)
Next 'Lang
End Sub
Public Sub CreateDataSource(ByVal targetFolder As String)
Dim name As String = "data source"
'Data source definition.
Dim definition As New DataSourceDefinition
definition.CredentialRetrieval = CredentialRetrievalEnum.Store
definition.ConnectString = "data source=" + dbServer + ";initial catalog=" + db
definition.Enabled = True
definition.EnabledSpecified = True
definition.Extension = "SQL"
definition.ImpersonateUser = False
definition.ImpersonateUserSpecified = True
'Use the default prompt string.
definition.Prompt = Nothing
definition.WindowsCredentials = False
'Login information
definition.UserName = "user"
definition.Password = "password"
Try
'name, folder, overwrite, definition, properties
rs.CreateDataSource(name, targetFolder, True, definition, Nothing)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End Sub
Public Sub PublishFolderContents(ByVal sourceFolder As String, ByVal targetFolder As String)
Dim di As New DirectoryInfo(sourceFolder)
Dim fis As FileInfo() = di.GetFiles()
Dim fi As FileInfo
Dim fileName As String
For Each fi In fis
fileName = fi.Name
Select Case fileName.Substring(fileName.Length - 4).ToUpper
Case ".RDL"
PublishReport(sourceFolder, fileName, targetFolder)
Case ".JPG", ".JPEG"
PublishResource(sourceFolder, fileName, "image/jpeg", targetFolder)
Case ".GIF", ".PNG", ".BMP"
PublishResource(sourceFolder, fileName, "image/" + fileName.Substring(fileName.Length - 3).ToLower, targetFolder)
End Select
Next fi
End Sub
Public Sub PublishReport(ByVal sourceFolder As String, ByVal reportName As String, ByVal targetFolder As String)
Dim definition As [Byte]() = Nothing
Dim warnings As Warning() = Nothing
Try
Dim stream As FileStream = File.OpenRead(sourceFolder + "\" + reportName)
definition = New [Byte](stream.Length) {}
stream.Read(definition, 0, CInt(stream.Length))
stream.Close()
Catch e As IOException
Console.WriteLine(e.Message)
End Try
Try
'name, folder, overwrite, definition, properties
warnings = rs.CreateReport(reportName.Substring(0, reportName.Length - 4), targetFolder, True, definition, Nothing)
If Not (warnings Is Nothing) Then
Dim warning As Warning
For Each warning In warnings
Console.WriteLine(warning.Message)
Next warning
Else
Console.WriteLine("Report: {0} published successfully with no warnings", targetFolder + "/" + reportName)
End If
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End Sub
Public Sub PublishResource(ByVal sourceFolder As String, ByVal resourceName As String, ByVal resourceMIME As String, ByVal targetFolder As String)
Dim definition As [Byte]() = Nothing
Dim warnings As Warning() = Nothing
Try
Dim stream As FileStream = File.OpenRead(sourceFolder + "\" + resourceName)
definition = New [Byte](stream.Length) {}
stream.Read(definition, 0, CInt(stream.Length))
stream.Close()
Catch e As IOException
Console.WriteLine(e.Message)
End Try
Try
'name, folder, overwrite, definition, MIME, properties
rs.CreateResource(resourceName, targetFolder, True, definition, resourceMIME, Nothing)
Console.WriteLine("Resource: {0} with MIME {1} created successfully", targetFolder + "/" + resourceName, resourceMIME)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End Sub
Here is the batch to call the rs.exe:
SET ReportServer=%1
SET DBServer=%2
SET DBName=%3
SET ReportFolder=%4
rs -i PublishReports.rss -s %ReportServer% -v dbServer="%DBServer%" -v db="%DBName%" -v parentFolder="%ReportFolder%" >PublishReports.log 2>&1
pause
A: Well not really elegant. We created our own tool that uses the reportingservices2005 web service. We found this to be the most reliable way of getting what we want.
It's not really that difficult and lets you expand it to do other things like creating data sources and folders as required.
A: I strongly recommend RSScripter. As noted in the overview:
Reporting Services Scripter is a .NET
Windows Forms application that enables
scripting and transfer of all
Microsoft SQL Server Reporting
Services catalog items to aid in
transferring them from one server to
another. It can also be used to easily
move items on mass from one Reporting
Services folder to another on the same
server. Depending on the scripting
options chosen, Reporting Services
Scripter can also transfer all catalog
item properties such as Descriptions,
History options, Execution options
(including report specific and shared
schedules), Subscriptions (normal and
data driven) and server side report
parameters.
A: I know you say that you're not in favor of the Business Development Studio to do this, but I've found the built-in tools to be very reliable and easy to use.
A: Have you looked into any Continuous Integration solutions such as CruiseControl.NET? If you are able to deploy Reports using rs.exe then you can setup an automated process in CruiseControl to build and deploy your Reports on a timer or whenever a report is modified.
A: In our environment, we develop in VS with version control then deploy to DEV SSRS. Once the report is validated, we use ReportSync program to deploy reports from ReportServer DEV to ReportServer PROD. The RS.EXE scripts still have their place, but I have found ReportSync to be a much simpler and agile way to promote a report.
ReportSync:
ReportSync is an open source program free to download and use. It works great for downloading reports in bulk, and it can even push a report from one server to another server.
How to get download the program?
*
*Download the source code files from Github: Phires/ReportSynch, Run VS, Open the solution file (.SLN), compile the program, find the executable file (.EXE) from the C:\Temp\reportsync-master\bin\Release folder. Finally, saved the .EXE somewhere for you to use regularly
*How do I copy SSRS reports to a new server if I am not the owner of the reports --> ReportSync answer by nunespascal
How to deploy a report?
*
*Run the executable and the interface will launch.
*Use the SOURCE and DESTINATION dialogues to choose a single report, multiple reports, or an entire folder of reports. You can any target folder you would like. (HINT: You can even target the same server if you are wanting to duplicate a report on the same server.)
*After making your selections press the Sync button
*Go to the target server, and validate the change took effect by reviewing the Changed By Date.
This tool has been very convenient, but I have noticed some quirks. For example when I want to update just one report that already exists in the destination, here is what I have to select-- [Source:Report> Target:Folder> Sync]. WARNING: You might think you would select the target server report to update it, but I have tried this and the report does not get updated.
What else can ReportSync do?
*
*There is also an Export feature, which works marvelously for simply dumping all the RDL files to a folder for me to access. This is helpful in the event you need to migrate the server, add the files to to a VS Solution Project, or do anything else will all the files.
*In my testing this program does not migrate other content-- subscriptions, shared data sources, shared data sets. It is just applicable to the report files.
I know this post is old, but I came across it when researching RS.EXE scripts, so I thought I would provide an answer this question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
}
|
Q: How to concatenate icons into a single image with ImageMagick? I want to use CSS sprites on a web site instead of separate image files, for a large collection of small icons that are all the same size. How can I concatenate (tile) them into one big image using ImageMagick?
A: convert works much better than montage. It arranges images vertically or horizontally and keeps png transparency.
convert *.png -append sprites.png (append vertically)
convert *.png +append sprites.png (append horizontally)
A: I like this script for automatical sprite/css generation.
"Building CSS sprites with Bash & Imagemagick"
*
*article copy in Waybackmashine https://web.archive.org/web/20150529041037/http://jaymz.eu/blog/2010/05/building-css-sprites-with-bash-imagemagick
*script copy http://blog.kupriyanov.com/2011/01/solvedbuilding-css-sprites-with-bash.html
A: From the page you linked, 'montage' is the tool you want. It'll take a bunch of images and concatenate/tile them into a single output. Here's an example image I've made before using the tool:
(source: davr.org)
A: You are looking for:
montage -background transparent -geometry +4+4 *.png sprite.gif
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
}
|
Q: Loading DLLs into a separate AppDomain I want to load one or more DLLs dynamically so that they run with a different security or basepath than my main application. How do I load these DLLs into a separate AppDomain and instantiate objects from them?
A: If you're targeting 3.5, you can take advantage of the new managed extensibility framework to handle all the heavy lifting for you.
A: More specifically
AppDomain domain = AppDomain.CreateDomain("New domain name");
//Do other things to the domain like set the security policy
string pathToDll = @"C:\myDll.dll"; //Full path to dll you want to load
Type t = typeof(TypeIWantToLoad);
TypeIWantToLoad myObject = (TypeIWantToLoad)domain.CreateInstanceFromAndUnwrap(pathToDll, t.FullName);
If all that goes properly (no exceptions thrown) you now have an instance of TypeIWantToLoad loaded into your new domain. The instance you have is actually a proxy (since the actual object is in the new domain) but you can use it just like your normal object.
Note: As far as I know TypeIWantToLoad has to inherit from MarshalByRefObject.
A: You can use the AppDomain.CreateInstance method to do this. You'll need to call the Unwrap method of the ObjectHandle that is returned to get at the actual object.
A: Create a new Appdomain with AppDomain.Create( ... ).
After creating the AppDomain load the DLLs into that AppDomain.
Look into all the methods that Appdomain has with Create*. There are certain things like CreateInstanceAndUnwrap, etc.
A: As previously stated, use AppDomain.CreateDomain to create a new app domain. You can then load an assembly into it using the Load method, or even execute an assembly using the ExecuteAssembly method. You can use GetAssemblies to see if an assembly has already been loaded. Be aware too that you cannot unload an assembly once it's loaded. You will need to unload the domain.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
}
|
Q: CPAN/gem-like repository for Objective-C and Cocoa? Is there any centralized repository of useful Objective-C / Cocoa libraries as there is for Perl, Ruby, Python, etc.?
In building my first iPhone app, I'm finding myself implementing some very basic functions that would be just a quick "gem install" away in Ruby.
A: There's a project for that! It's called CocoaPods!
Homepage: http://cocoapods.org/
Source: https://github.com/CocoaPods/CocoaPods
A: Unfortunately not :(
There are some very useful sites however. I find one of the best is cocoadev.com as it contains lots of useful information about many of the more obscure classes usually including snippets of code to do some really cool things :)
Maybe we (the cocoa community) should look into building something like this!
Oh and I just remembered this site cocoadevcentral.com which is also very good for starting out with cocoa.
A: Daniel mentioned http://cocoadev.com.
More specifically, check out http://www.cocoadev.com/index.pl?ObjectLibrary.
"This page is for tracking re-usable Cocoa classes that can be mixed, matched, and dropped fairly easily into existing Cocoa projects to add useful functionality."
A: I'd be interested in what kind of "basic functions" you're having to implement. There's actually quite a lot already there in the provided libraries, and I wonder if you're just not finding functionality that's already there...
A: There's a new index of reusable code for Mac OS and iOS: Cocoa Objects
A: I might be confused or missing something here... But doesn't apple provide all the Foundation / Cocoa / AppKit / CoreAudio / Qtkit / etc libraries that should provide all of the very basic functions you are looking for?
Other than what xcode comes with or is on the apple dev site, there are no centralized repo's for Cocoa.
A: Google Code also has some objective C things up. It depends on what you are looking for...
A: Also see GitHub, many useful Objective-C projects, especially re iPhone. See activerecord & cocoaoniguruma, for instance.
http://github.com/search?q=objective-c
http://github.com/search?q=objc
A: Google has Google toolbox for mac which got me started unit testing my iPhone application which was the main thing I found missing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Using jmockit expectations with matchers and primitive types I'm using jmockit for unit testing (with TestNG), and I'm having trouble using the Expectations class to mock out a method that takes a primitive type (boolean) as a parameter, using a matcher. Here's some sample code that illustrates the problem.
/******************************************************/
import static org.hamcrest.Matchers.is;
import mockit.Expectations;
import org.testng.annotations.Test;
public class PrimitiveMatcherTest {
private MyClass obj;
@Test
public void testPrimitiveMatcher() {
new Expectations(true) {
MyClass c;
{
obj = c;
invokeReturning(c.getFoo(with(is(false))), "bas");
}
};
assert "bas".equals(obj.getFoo(false));
Expectations.assertSatisfied();
}
public static class MyClass {
public String getFoo(boolean arg) {
if (arg) {
return "foo";
} else {
return "bar";
}
}
}
}
/******************************************************/
The line containing the call to invokeReturning(...) throws a NullPointerException.
If I change this call to not use a matcher, as in:
invokeReturning(c.getFoo(false), "bas");
it works just fine. This is no good for me, because in my real code I'm actually mocking a multi-parameter method and I need to use a matcher on another argument. In this case, the Expectations class requires that all arguments use a matcher.
I'm pretty sure this is a bug, or perhaps it's not possible to use Matchers with primitive types (that would make me sad). Has anyone encountered this issue, and know how to get around it?
A: So the problem appears to be in Expectations.with():
protected final <T> T with(Matcher<T> argumentMatcher)
{
argMatchers.add(argumentMatcher);
TypeVariable<?> typeVariable = argumentMatcher.getClass().getTypeParameters()[0];
return (T) Utilities.defaultValueForType(typeVariable.getClass());
}
The call to typeVariable.getClass() does not do what the author expects, and the call to Utilities.defaultValueFor type returns null. The de-autoboxing back the the primitive boolean value is where the NPE comes from.
I fixed it by changing the invokeReturning(...) call to:
invokeReturning(withEqual(false)), "bas");
I'm no longer using a matcher here, but it's good enough for what I need.
A: the issue is the combination of Expectation usage and that Matchers does not support primitive type.
The Matchers code rely on Generic which basically does not support primitive type. Typically the usage of Matchers is more for matching value; with the auto-boxing/unboxing feater in Java 5, this is usually not a problem.
But JMockit's Expectation is not using it for matching value, it uses it for some kind of parsing to determine the method call signature type..which in this case the Matchers will resulted in Boolean type while your method is primitive type..so it fails to mock it properly.
I'm sorry that I can not tell you any workaround for this. Maybe somebody else can help.
A: I changed JMockit (release 0.982) so that "with(is(false))" and other similar variations now work as expected (it no longer returns null, but the actual argument value inside the inner matcher).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: What Is ASP.Net MVC? When I first heard about StackOverflow, and heard that it was being built in ASP.Net MVC, I was a little confused. I thought ASP.Net was always an example of an MVC architecture. You have the .aspx page that provides the view, the .aspx.vb page that provides the controller, and you can create another class to be the model. The process for using MVC in ASP.Net is described in this Microsoft article.
So my question is. What Does ASP.Net MVC provide that you wouldn't be able to do with regular ASP.Net (even as far back as ASP.Net 1.1)? It is just fancy URLs? Is it just for bragging rights for MS to be able to compare themselves with new technologies like Ruby On Rails, and say, "We can do that too"? Is there something more that ASP.Net MVC actually provides, rather than a couple extra templates in the File->New menu?
I'm probably sounding really skeptical and negative right now, so I'll just stop. But I really want to know what ASP.Net MVC actually provides. Also, if anybody can tell me why it's Model-View-Controller and not in order of the layers of View-Controller-Model or Model-Control-View depending on whether you are going top to bottom, or vice versa, I'd really appreciate that too.
EDIT
Also, it's probably worth pointing out that I've never really cared for the web forms (AKA server controls) model either. I've only used it minimally, and never on the job.
A: Scott Guthrie explained it in this post "ASP.NET MVC Framework"
*
*It enables clean separation of concerns, testability, and TDD by
default. All core contracts within
the MVC framework are interface based
and easily mockable (it includes
interface based
IHttpRequest/IHttpResponse
intrinsics). You can unit test the
application without having to run the
Controllers within an ASP.NET process
(making unit testing fast). You can
use any unit testing framework you
want to-do this testing (including
NUnit, MBUnit, MS Test, etc).
*It is highly extensible and pluggable. Everything in the MVC
framework is designed so that it can
be easily replaced/customized (for
example: you can optionally plug-in
your own view engine, routing policy,
parameter serialization, etc). It
also supports using existing
dependency injection and IOC container
models (Windsor, Spring.Net,
NHibernate, etc).
*It includes a very powerful URL mapping component that enables you to
build applications with clean URLs.
URLs do not need to have extensions
within them, and are designed to
easily support SEO and REST-friendly
naming patterns. For example, I could
easily map the /products/edit/4 URL to
the "Edit" action of the
ProductsController class in my project
above, or map the
/Blogs/scottgu/10-10-2007/SomeTopic/
URL to a "DisplayPost" action of a
BlogEngineController class.
*The MVC framework supports using the existing ASP.NET .ASPX, .ASCX, and
.Master markup files as "view
templates" (meaning you can easily use
existing ASP.NET features like nested
master pages, <%= %> snippets,
declarative server controls,
templates, data-binding, localization,
etc). It does not, however, use the
existing post-back model for
interactions back to the server.
Instead, you'll route all end-user
interactions to a Controller class
instead - which helps ensure clean
separation of concerns and testability
(it also means no viewstate or page
lifecycle with MVC based views).
*The ASP.NET MVC framework fully supports existing ASP.NET features
like forms/windows authentication, URL
authorization, membership/roles,
output and data caching,
session/profile state management,
health monitoring, configuration
system, the provider architecture,
etc.
A: .aspx doesn't fulfill the MVC pattern because the aspx page (the 'view') is called before the code behind (the 'controller').
This means that the controller has a 'hard dependency' on the view, which is very much against MVC principles.
One of the core benefits of MVC is that it allows you to test your controller (which contains a lot of logic) without instantiating a real view. You simply can't do this in the .aspx world.
Testing the controller all by itself is much faster than having to instantiate an entire asp.net pipeline (application, request, response, view state, session state etc).
A: Primarily, it makes it very easy to create testable websites with well defined separations of responsibility. Its also much easier to create valid XHTML UIs using the new MVC framework.
I've used the 2nd CTP (I think they're on five now) to start work on a website and, having created a few web applications before, I have to say its hundreds of times better than using the server control model.
Server controls are fine when you don't know what you're doing. As you start to learn about how web applications should function, you start fighting them. Eventually, you have to write your own to get past the shortcomings of current controls. Its at this point where the MVC starts to shine. And that's not even considering the testability of your website...
A: No more auto-generated html IDs!!! Anyone doing any sort of javascript appreciates this fact.
A: ASP.Net with it's code behind is almost MVC - but not - the one big thing that makes it not is that the codebehinds are tied directly to the aspx's - which is a big component of MVC. If you are thinking of the codebehinds as the controller - the should be completely decoupled from the view. The new .NET MVC rounds this out - and brings a complete MVC framework. Though there are existing ones for .NET already (see Spring.NET).
A: I looked through a couple simple examples such as this one. I can kind of see the difference. However, I don't really see how MVC uncouples the view from the controller. The view still references stuff that's in the controller. I do see how it makes it much easier to test, and that at least in MVC the controller doesn't have any knowledge of the view. And you wouldn't have to process the view to call methods in the controller. I can see that's quite a leap, even though at first glance it may not seem like much.
I do agree with @Will about fighting server controls. I've never worked in a situation where they were actually used, but many people I know who have, have run into quite a few limitations with them.
A: Article about ASP.net MVC Vs ASP.net Web form
http://weblogs.asp.net/shijuvarghese/archive/2008/07/09/asp-net-mvc-vs-asp-net-web-form.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Flatten XML to HTML table There must be a generic way to transform some hierachical XML such as:
<element1 A="AValue" B="BValue">
<element2 C="DValue" D="CValue">
<element3 E="EValue1" F="FValue1"/>
<element3 E="EValue2" F="FValue2"/>
</element2>
...
</element1>
into the flattened XML (html) picking up selected attributes along the way and providing different labels for the attributes that become column headers.
<table>
<tr>
<th>A_Label</th>
<th>D_Label</th>
<th>E_Label</th>
<th>F_Label</th>
</tr>
<tr>
<td>AValue</td>
<td>DValue</td>
<td>EValue1</td>
<td>FValue1</td>
</tr>
<tr>
<td>AValue</td>
<td>DValue</td>
<td>EValue2</td>
<td>FValue2</td>
</tr>
<table>
OK, so there's not generic solution due to the attribute re-labelling but you get what I mean hopefully. I've just started on all the XSLT/XPATH stuff so I'll work it out in good time but any clues would be useful.
A: I'm not 100% sure of what you are trying to do but this solution may work if your element1, element2 and element3 are nested consistently.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<table>
<xsl:apply-templates select="//element3"></xsl:apply-templates>
</table>
</xsl:template>
<xsl:template match="element3">
<tr>
<td><xsl:value-of select="../../@A"/></td>
<td><xsl:value-of select="../../@B"/></td>
<td><xsl:value-of select="../@C"/></td>
<td><xsl:value-of select="../@D"/></td>
<td><xsl:value-of select="@E"/></td>
<td><xsl:value-of select="@F"/></td>
</tr>
<xsl:apply-templates select="*"></xsl:apply-templates>
</xsl:template>
</xsl:stylesheet>
A: I needed a similar XSLT but with unknown depth, here is how I did it.
First, add a wrapper for the resulting HTML table/def list and call the template mode="puke" to flatten our XML tree :
<xsl:element name="div">
<xsl:attribute name="class" select="puke" />
<xsl:apply-templates select="$notice" mode="puke" />
</xsl:element>
Here we match each node to display its content (e.g. text()) and its attributes. We do this recursively. I used dl/dt/dd because my source tree was a complex tree that can't be flatten as a .
<!-- @description:
Display all field from the notice so the customer can tell what he want
-->
<xsl:template match="node()" mode="puke">
<xsl:message>
puking : <xsl:value-of select="local-name( . )" />
</xsl:message>
<xsl:element name="dl">
<xsl:element name="dt">
<xsl:attribute name="class">tagName</xsl:attribute>
<xsl:value-of select="local-name( . )" />
</xsl:element>
<xsl:element name="dd">
<xsl:attribute name="class">tagText</xsl:attribute>
<xsl:value-of select="text()" /></xsl:element>
<xsl:element name="dl">
<xsl:attribute name="class">attr</xsl:attribute>
<!-- display attribute -->
<xsl:apply-templates select="@*" />
</xsl:element>
</xsl:element>
<!-- recursive call on node() -->
<xsl:apply-templates select="./*" mode="puke" />
</xsl:template>
Match attribute of a given node and display them.
The CSS use in to format the resulting HTML :
<style>
.puke {
background-color: #BDD6DE;
clear: both;
}
.tagName, .attrName {
float: left;
}
.tagText, .attrText {
clear: right;
}
</style>
A: We already have a Pro*C program reading from an Oracle database, it calls a perl script which in turn executes some Java to extract data in XML format from the aforementioned database for calling a batch file to execute some vbscript FTPing the file to some other server. I was really hoping for something in Fortran.
A: The original question needs to be clarified:
*
*What happens with BValue and CValue in the original question? Is there a reason why they shouldn't be part of the flattened structure?
*Do all of the elements in the XML doc have 2 attributes or is this completely arbitrary?
*Are there only 3 types of elements and are they always nested as shown in the example?
*Can your element1 be repeated itself or is this the root element of your doc?
In XSLT it is possible to write very generic transformers but it is often much easier to write a stylesheet to transform a document when you can take any known restrictions into account.
A: I have used an expanded version of the template below to flatten structured XML. Warning: There was some case-specific code in the original version (it actually turned the XML into CSV) that I just stripped and I didn't test this version.
The basic way it works should be clear: it prints everything that doesn't have node children and otherwise recursively calls the template on the node() that does have children. I don't think it handles attributes and comments correctly as it is now, but that should not be hard to fix.
<?xml version="1.0" encoding="UTF-8"?>
<!-- XSL template to flatten structured XML, before converting to CSV. -->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" encoding="UTF-8"/>
<xsl:strip-space elements="*" />
<xsl:template match="/">
<xsl:apply-templates select="//yourElementsToFlatten"/>
</xsl:template>
<xsl:template match="//yourElementsToFlatten">
<xsl:apply-templates select="@*|node()"/>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:choose>
<!-- If the element has multiple childs, call this template
on its children to flatten it-->
<xsl:when test="count(child::*) > 0">
<xsl:apply-templates select="@*|node()"/>
</xsl:when>
<xsl:otherwise>
<xsl:copy>
<xsl:value-of select="text()" />
</xsl:copy>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Disable (Politely) a website when the sql server is offline I work at a college and have been developing an ASP.NET site with many, many reports about students, attendance stats... The basis for the data is an MSSQL server DB which is the back end to our student management system. This has a regular maintenance period on Thursday mornings for an unknown length of time (dependent on what has to be done).
Most of the staff are aware of this but the less regular users seem to be forever ringing me up. What is the easiest way to disable the site during maintenance obviously I can just try a DB query to test if it is up but am unsure of the best way to for instance redirect all users to a "The website is down for maintenance" message, bearing in mind they could have started a session prior to the website going down.
Hopefully, something can be implemented globally rather than per page.
A: Drop an html file called "app_offline.htm" into the root of your virtual directory. Simple as that.
Scott Guthrie on the subject and friendly errors.
A: You could display a message to people who have logged in saying "the site will be down for maintenance in xxx minutes" then run a service to log everyone out after xxx minutes. Then set a flag somewhere that every page can access, and at the top of every page(or just the template page) you test if that flag is set, if it is, send a redirect header to a site is down for maintenance page.
A: The "offline.html" page won't work if the user was already navigating within the site, or if he's accessing the site from a bookmark/external link to a specific page.
The solution I use is to create a second web site with the same address (IP or host header(s)), but have it disabled by default. When the website is down, a script deactivates the "real" web site and enables the "maintenance" website instead. When it comes back online, another script switches back to the "real" web site.
The "maintenance" web site is located in a different root directory, with a single page with the message (and any required images/css files)
To have the same message shown on any page, the "maintenance" web site is set up with a 404 error handler that will redirect any request to the same "website is down for maintenance" page.
A: What happens now when the site is down and someone tries to hit it? Does ADO.NET throw a specific exception you could catch and then redirect to the "website down" page?
You could add a "Global.asax" file to the project, and in its code-behind add an "Application_Error" event handler. It would fire whenever an exception is thrown and goes uncaught, from anywhere in your web app. For example, in C#:
protected void Application_Error(object sender, EventArgs e)
{
Exception e = Server.GetLastError().GetBaseException();
if(e is SqlException)
{
Server.ClearError();
Server.Transfer("~/offline.aspx");
}
}
You could also check the Number property on the exception, though I'm not sure which number(s) would indicate it was unable to connect to the database server. You could test this while it's down, find the SQL error number and look it up online to see if it's specifically what you really want to be checking for.
EDIT: I see what you're saying, petebob.
A: I would suggest doing it in Application_PreRequestHandlerExecute instead of after an error occurs. Generally, it'd be best not to enter normal processing if you know your database isn't available. I typically use something like below
void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
string sPage = Request.ServerVariables["SCRIPT_NAME"];
if (!sPage.EndsWith("Maintenance.aspx", StringComparison.OrdinalIgnoreCase))
{
//test the database connection
//if it fails then redirect the user to Maintenance.aspx
string connStr = ConfigurationManager.ConnectionString["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
try
{
conn.Open();
}
catch(Exception ex)
{
Session["DBException"] = ex;
Response.Redirect("Maintenance.aspx");
}
finally
{
conn.Close();
}
}
}
A: Thanks for the replies so far I should point out I'm not the one that does the maintenance nor does I have access all the time to IIS. Also, I prefer options where I do nothing as like all programmers I am a bit lazy.
I know one way is to check a flag on every page but I'm hoping to avoid it. Could I not do something with the global.asax page, in fact, I think posting has engaged my brain:
Think I could put in Application_BeginRequest a bit of code to check the SQL state then redirect:
HttpContext context = HttpContext.Current;
if (!isOnline())
{
context.Response.ClearContent();
context.Response.Write("<script language='javascript'>" +
"top.location='" + Request.ApplicationPath + "/public/Offline.aspx';</scr" + "ipt>");
}
Or something like that may not be perfect not tested yet as I'm not at work. Comments appreciated.
A: A slightly more elegant version of the DB check on every page would be to do the check in the Global.asax file or to create a master page that all the other pages inherit from.
The suggestion of having an online site and an offline site is really good, but only really applicable if you have a limited number of sites to manage on the server.
EDIT: Damn, the other answers with these suggestions came up after I loaded the page. I need to remember to refresh before replying :)
A: James code forgets to close the connection, should probably be:
try
{
conn.Open();
}
catch(Exception ex)
{
Session["DBException"] = ex;
Response.Redirect("Maintenance.aspx");
}
finally
{
conn.Close();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Do you think ASP.NET MVC will compete with ASP.NET Webforms? Do you think ASP.NET MVC will ever have a significant share of the Microsoft web development market? Or will it be more like 10-15% of the market?
A: MVC is great but won't become a real contender as a replacement for Web Forms until it includes it's own rich control set. As you probably already know, some of the existing controls do work with it but many don't. Regardless of this though, I still love using it.
A: Well, .NET has never been able to fully counter the inertia of Visual Basic 6 (I still see a few shops here and there who are just beginning to shift to .NET), so one has to consider the inertia of ASP.NET Webforms and how it is deployed everywhere at the moment.
ASP.NET MVC will reach wide adoption, no doubt, but it will be something that is promoted by architect-conscious types: some managers and less-than-fast-paced devs won't care.
A: I don't think so. The purpose and the goal of both solutions are different, and APS.NET Web Forms is more like a platform while MVC is architecture framework, so the question is a bit odd. In my opinion MVC in combination with good AJAX support and correct server side model structure could be the more convenient way to develop sub-range of Web application, but Web Forms are not going away and they will have further improvements in next versions.
Cheers.
A: I think that eventually, MVC will have a 100% share of the MS-web-market. It's just better.
A: As Ty said, there won't be a lot of adoption until the controls are there. I do think it will surpass webforms once they are. The webform model falls too pieces once you need to do something complicated and it is difficult to test. The ability to unit test MVC is HUGE, but people just don't know what they are missing yet.
I think that ASP.NET MVC is the best of ASP classic (lots of rendering control) and ASP.NET (the ability to have real architectures and lack of spaghetti code).
A: I think it will be a slow start because of the webforms install base. As unit testing and markup control starts to become more important to more people then I think you start to see a migration. I doubt that it will ever reach 100% of the MS install base for a web platform but it will be a steady rise over the next years to come. There will be the fan-boys who will say this will dominate planet sliced bread but that just isn't realistic. With that, I'm hoping not to have to use Webforms for a long, long time.
EDIT: Now that we are at Beta 1 we are starting to see the component vendors start to ship some stuff. Looks like first up to bat is Telerik with their ASP.NET Ajax Controls in ASP.NET MVC
A: My guess is that microsoft would really have to stand up and say "MVC is the only way you should be doing web applications" before businesses bothered with it on a large scale. So no, as it stands now, small user base.
A: Oh yes. It's going to blow web forms out of the water - we've already seen how valuable a true MVC framework can be in the Java world. In the MS world - it's really been a void that has needed to be filled.
As a former Java/Struts dude - I find it pretty frustrating doing current work in web forms - because I know that there are tools out there that would make my life so much easier.
A: I think more people understand the importance of Model View Controller and the limitations of a simple Page Controller, which is what ASP.Net forms really are.
The problem, as someone pointed out, is the Visual Basic guys - you know people that came from classic ASP experience and never seen any Unit Testing and/or MVC-based Java/Ruby/PHP development. I believe that's the bulk of .NET developers out there. I read somewhere that there were 6 million VB developers in the world. Guess, what these are doing now?
People who came from Java/Ruby/PHP shops who already used to MVC apps will certainly adapt MS MVC framework.
A: I think developers who like that development model will adopt it, but I prefer webforms because the lifecycle provides a great way to create re-usable controls.
And you can also maintain an MVC development style with webforms and be able to create unit tests of all your code, so being testable isn't really an argument for MVC being better.
A: My guess is that MVC is an alternative solution to "classic" Webform programming if you are interested in things like TDD, REST, write your own HTML, and so on.
For the moment developers are still fond of D&D development style, because it allows quick development of applications, even then it becomes unmaintainable.
As more people start adopting Agile methodologies and become more interested in writing maintainable sw versus developing quick&dirty apps, MVC will gain more user base.
In a talk I remember ScottH saying that they think MVC will float around a 5-10%,
A: I've only recently begun working with MS's MVC Framework. I started getting into it quite a bit with the release of Preview 5. The biggest hurdle with getting people to use it is the lack of examples and useful reference material out there.
The framework itself has been a great experience to use especially when combined with jQuery and nUnit. The design for your site becomes much more natural from an OO perspective and I think that once the learning curve is reduced with quality primer material widely available then it will move towards becoming the dominant architecture for web development using MS products.
A: I think that the webforms fulfills a security/ comfort need for those who do not have experience outside a code-behind paradigm. I am not saying that is bad, because for many tasks in business the goal is get something done and live with it. Unfortunately business is about results, and many times you are forced to ignore methods.
On the other hand, when the situation does call for complex interaction between pages, webforms introduces so much complexity with all the work arounds. Register script blocks just to be able to fire off javascript? What about when you want to windows to communicate client-side? MS should invest some time beefing up their toolset for javascript debugging, maybe even offer a series on JSON / JQuery on MSDN. Just some thoughts.
A: I think MVC will catch on more in enterprise level applications, where testability and flexibility is more of great importance compared to that of small mom & pop applications.
There are no plans to phase out the classic code-behind model and I feel that since most people are used to that technology that many are most likely stay with it.
If one has no experience with MVC, then it can be quite a paradigm shift. I don't see tons of people flocking to it. I would think the 80% code-behind and 20% MVC percentages would hold true.
Since the code-behind model has been around for such a long time, I bet there are many programmers that only have had experience with the classic code-behind event life cycle.
A: 5 Reasons You Should Take a Closer Look at ASP.NET MVC
A: The place that the MVC really makes sense is if you already understand the underlying concepts of HTTP and Rest. If you are really seeking to leverage custom JavaScript and have a highly domain user optimized experience. If you like your web forms development with all your drag-and-drop controls and are comfortable with your user experience and your Atlas update panels, than you really should stick with it.
MVC is for the rest of us that want to easily leverage .NET server side and a custom client side. It is for those who have web designers and folks who want to build custom HTML as we as have those who are accomplished programmers.
If you are a solitary person (maybe the IT guy) throwing stuff together for your intranet for the front office, you may be better served by webforms. That is really where webforms and .NET shine. Some of the newer tools EF and MVC ad value for teams and larger scale development.
So no, I think they complement each other.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: What do you think of using properties as object initializers in C#; I was wondering what people thought of using properties as object initializers in C#. For some reason it seems to break the fundamentals of what constructors are used for.
An example...
public class Person
{
string firstName;
string lastName;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName= value; }
}
}
Then doing object intialization with.....
Person p = new Person{ FirstName = "Joe", LastName = "Smith" };
Person p = new Person{ FirstName = "Joe" };
A: Object initializers does in no way replace constructors. The constructor defines the contract that you have to adhere to in order to create a instance of a class.
The main motivation for object initializers in the C# language is to support Anonymous Types.
var v = new { Foo = 1, Bar = "Hi" };
Console.WriteLine(v.Bar);
A: IMHO its sweet. Most objects are newed up with the default constructor, and must have some properties set before they are ready to run; so the object initializers make it easier to code against most objects out there.
A: Since you're already using the new C# syntax, might as well use automatic properties as well, just to sweeten up your code a drop more:
instead of this:
string firstName;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
use this:
public string FirstName { get; set; }
A: Constructors should only really have arguments that are required to construct the object. Object initialisers are just a convenient way to assign values to properties. I use object initialisers whenever I can as I think it's a tidier syntax.
A: What you see here is some syntatic sugar provided by the compiler. Under the hood what it really does is something like:
Person p = new Person( FirstName = "Joe", LastName = "Smith" );
Person _p$1 = new Person();
_p$1.FirstName = "Joe";
_p$1.LastName = "Smith";
Person p = _p$1;
So IMHO you are not really breaking any constructor fundamentals but using a nice language artifact in order to ease readability and maintainability.
A: I think overall it is useful, especially when used with automatic properties.
It can be confusing when properties are doing more than get/set.
Hopefully this will lead to more methods, and reduce the abuse of properties.
A: Not your original question, but still...
Your class declaration can be written as:
public class Person
{
public string FirstName { get; set; }
public string LastName {get; set; }
}
and if it were my code, I'd probably have an object for Name with fields First and Last.
A: It's also quite necessary for projected classes returned from a language integrated query (linq)
var qry = from something in listofsomething
select new {
Firstname = something.FirstName,
Lastname = something.Surname
}
A: Object Initializers help to reduce coding complexity in that you don't need to create a half dozen different constructors in order to provide initial values for properties. Anything that reduces redundant code is a positive, in my book.
I believe the primary reason the feature was added to the language is to support anonymous types for LINQ.
A: Adding to Nescio's thoughts - I'd suggest in code reviews actively hunting down expensive transparent operations in property accessors e.g. DB round tripping.
A: If you want to enforce the use of a constructor, you could set your object's default parameterless constructor to private, and leave public only some enforced constructors:
public class SomeObject
{
private SomeObject()
{}
public SomeObject(string someString) //enforced constructor
{}
public string MyProperty { get; set; }
}
Using the above definition, this throws an error:
var myObject = new SomeObject { MyProperty = "foo" } //no method accepts zero arguments for constructor
Of course this can't be done for all cases. Serialization, for example, requires that you have a non-private default constructor.
A: I for one am not happy with them. I don't think they have a place in the constructor, or MS should got back and refactor them to allow you to use them in a private fasion. If I construct an object I want to pass in some PRIVATE data. I want it set from the outside world once and that's it. With Object Initializers you allow the values passed into the constructor to be modifiable.
Maybe in the future they will change this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: VS2008 Crashing on Project Load I am unable to load any existing projects after starting VS2008. When I try to open an existing project VS2008 will crash. It looks like it is crashing when trying to load a floating window in VS but I cant tell which one.
When I launch the debugger on the crashed instance I get the following message which is not very useful.
Unhandled exception at 0x00740078 in devenv.exe: 0xC0000005: Access violation writing location 0x7e429ed9.
I have previously had SP1 installed but have now removed this. I also have used Resharper 4.0 but have uninstalled this as well and am still getting the problem.
Does anyone have tips on how to solve VS2008 crashing problems? I really dont want to have to do a reinstall of the product.
As a work around I have found that if I create a new class library project it will fail because of a write to protected memory error. If i try and create another new class library project it will work and then I can load an existing project.
A: You can also try running devenv.exe with the /ResetSettings argument (which will reset any custom settings you have) or with the /SafeMode flag.
/SafeMode won't help you fix your problem but it will at least narrow down the issue to the things that are different between safe and regular mode.
A: Try renaming the:
projectName.csproj.user file
solutionName.suo file
solutionName.ncb file
... and see if the project opens.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I restore from a drop database command using a mysql binary log? How can I restore a mysql database that was dropped using a "drop database" command? I have access to binary logs which should make this type of rollback possible.
A: Documentation Sucks. It alludes to DROP DATABASE being recoverable, but only in odd conditions i'm not familiar with http://dev.mysql.com/doc/refman/5.0/en/binary-log.html
According to Docs, binlogs are just a sequence of commands executed based on a given reference point. So that when you did "DROP DATABASE", instead of going "Oh, hes droppping the database, we should back up now just in case" it merely wrote a "DROP DATABASE" to the last binlog. Recovery is not as simple as playing the tape backwards.
What you need to do is recover the database from a last-known-good, and apply the binlogs that happened between that recover point and the DROP command.
http://dev.mysql.com/doc/refman/5.0/en/recovery-from-backups.html
How one determines which binlogs to use tho, unclear.
There is nothing better than having full file system backups. And you should at least have these to fall back to.
A: If you don't have a backup of the database, you're out of luck. Droping a database is permanent.
A: Assuming you had a backup, the binary log holds the stuff that has happened since that backup. Using the mysqlbinlog utility you could do something like:
mysqlbinlog the_log_file > update.sql
Though I think you might have to edit that file to remove anything you didn't want to execute again (like the drop database statement).
Good luck!
A: No backup no party.
So I'll answer:
To never be in your situation again install the ultra simple and ultra powerful automysqlbackup (if you're on linux):
sudo apt-get install automysqlbackup
configure it:
sudo nano /etc/default/automysqlbackup
Then upload its content automatically to dropbox, ubuntu one or similar.
Only then live happily :)
A: Just to complement Kent Fredric's answer, you CAN rollback the drop database command if you are using binary logging since the database's creation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Code in PHP for the ceiling function Anyone has ever programmed a PHP (or Perl) function to get the ceiling value Excel style?
A: This should be the answer, from php.net comments:
// MS Excel function: Ceiling( number, significance )
// duplicates m$ excel's ceiling function
if( !function_exists('ceiling') )
{
function ceiling($number, $significance = 1)
{
return ( is_numeric($number) && is_numeric($significance) ) ? (ceil($number/$significance)*$significance) : false;
}
}
echo ceiling(0, 1000); // 0
echo ceiling(1, 1); // 1000
echo ceiling(1001, 1000); // 2000
echo ceiling(1.27, 0.05); // 1.30
A: "Microsoft Excel's ceiling function does not follow the mathematical definition, but rather as with (int) operator in C, it is a mixture of the floor and ceiling function: for x ≥ 0 it returns ceiling(x), and for x < 0 it returns floor(x). This has followed through to the Office Open XML file format. For example, CEILING(-4.5) returns -5. A mathematical ceiling function can be emulated in Excel by using the formula "-INT(-value)" (please note that this is not a general rule, as it depends on Excel's INT function, which behaves differently that most programming languages)." - from wikipedia
If php's built in ceil function isn't working right you could make a new function like
function excel_ceil($num){
return ($num>0)?ceil($num):floor($num);
}
Hope that helps
A: Sorry, not quite clear what 'Excel style' is, but PHP has a ceil function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What are the advantages and disadvantages of the Session Façade Core J2EE Pattern? What are the advantages and disadvantages of the Session Façade Core J2EE Pattern?
What are the assumptions behind it?
Are these assumptions valid in a particular environment?
A: Session Facade is a fantastic pattern - it is really a specific version of the Business Facade pattern. The idea is to tie up business functionality into discrete bundles - such as TransferMoney(), Withdraw(), Deposit()... So that your UI code is accessing things in terms of business operations instead of low level data access or other details that it shouldn't have to be concerned with.
Specifically with the Session Facade - you use a Session EJB to act as the business facade - which is nice cause then you can take advantage of all the J2EE services (authentication/authorization, transactions, etc)...
Hope that helps...
A: The main advantage of the Session Facade pattern is that you can divide up a J2EE application into logical groups by business functionality. A Session Facade will be called by a POJO from the UI (i.e. a Business Delegate), and have references to appropriate Data Access Objects. E.g. a PersonSessionFacade would be called by the PersonBusinessDelegate and then it could call the PersonDAO. The methods on the PersonSessionFacade will, at the very least, follow the CRUD pattern (Create, Retrieve, Update and Delete).
Typically, most Session Facades are implemented as stateless session EJBs. Or if you're in Spring land using AOP for transactions, you can create a service POJO that which can be all the join points for your transaction manager.
Another advantage of the SessionFacade pattern is that any J2EE developer with a modicum of experience will immediately understand you.
Disadvantages of the SessionFacade pattern: it assumes a specific enterprise architecture that is constrained by the limits of the J2EE 1.4 specification (see Rod Johnson's books for these criticisms). The most damaging disadvantage is that it is more complicated than necessary. In most enterprise web applications, you'll need a servlet container, and most of the stress in a web application will be at the tier that handles HttpRequests or database access. Consequently, it doesn't seem worthwhile to deploy the servlet container in a separate process space from the EJB container. I.e. remote calls to EJBs create more pain than gain.
A: Rod Johnson claims that the main reason you'd want to use a Session Facade is if you're doing container managed transactions - which aren't necessary with more modern frameworks (like Spring.)
He says that if you have business logic - put it in the POJO. (Which I agree with - I think its a more object-oriented approach - rather than implementing a session EJB.)
http://forum.springframework.org/showthread.php?t=18155
Happy to hear contrasting arguments.
A: It seems that whenever you talk about anything J2EE related - there are always a whole bunch of assumptions behind the scenes - which people assume one way or the other - which then leads to confusion. (I probably could have made the question clearer too.)
Assuming (a) we want to use container managed transactions in a strict sense through the EJB specification then
Session facades are a good idea - because they abstract away the low-level database transactions to be able to provide higher level application transaction management.
Assuming (b) that you mean the general architectural concept of the session façade - then
Decoupling services and consumers and providing a friendly interface over the top of this is a good idea. Computer science has solved lots of problems by 'adding an additional layer of indirection'.
Rod Johnson writes "SLSBs with remote interfaces provide a very good solution for distributed applications built over RMI. However, this is a minority requirement. Experience has shown that we don't want to use distributed architecture unless forced to by requirements. We can still service remote clients if necessary by implementing a remoting façade on top of a good co-located object model." (Johnson, R "J2EE Development without EJB" p119.)
Assuming (c) that you consider the EJB specification (and in particular the session façade component) to be a blight on the landscape of good design then:
Rod Johnson writes
"In general, there are not many reasons you would use a local SLSB at all in a Spring application, as Spring provides more capable declarative transaction management than EJB, and CMT is normally the main motivation for using local SLSBs. So you might not need th EJB layer at all. " http://forum.springframework.org/showthread.php?t=18155
In an environment where performance and scalability of the web server are the primary concerns - and cost is an issue - then the session facade architecture looks less attractive - it can be simpler to talk directly to the datbase (although this is more about tiering.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: PDF Imposition in PHP I'm looking for a PHP library that will allow me to create a print-ready PDF. The imposition should include 1-up, 4-up, 24-up, etc. layouts, and crop marks.
FPDF, TCPDF and PHP's included PDF libraries allow me to create an image and plop it on a PDF, but the more advanced layouts and crop marks are a bit beyond me.
Thanks in advance!
A: We used DOMPDF http://www.digitaljunkies.ca/dompdf/ successfully - just define what you want printed in regular HTML format, then pass the doc to DOMPDF, and it'll create a PDF from it.
Much more convenient than working with vector-based solutions that require you to essentially lay things out yourself on the page (like FPDF). Use HTML for layout! It's much easier.
A: I'd highly recommend DOMPDF or PDFLib as others have mentioned.
DOMPDF supports XHTML and CSS2.1 and will allow you to render a PDF page from HTML.
PDFlib+PDI will allow you to merge PDF documents or append pages, place images, text, etc.
A: http://www.pdflib.com/download/
Here is a library you didn't mention that will allow the creation of PDFs using php. Hope it's sufficient.
A: phpLiveDocx does exactly what you want. It is dead easy to use and allows you to populate templates created in a word processor with data in PHP. Learn more at http://www.phplivedocx.org/articles/brief-introduction-to-phplivedocx/
A: I've had a lot of success with PDFLib it's a very powerful library with PHP (and C, C#, Perl etc) bindings.
A: FPDF has always worked out for me. There is a lot of robust functionality in there, and you just gotta keep at it to find it.
The ImageEPS class extension is VERY useful for making things print ready, though it is not without its issues (as its a rather old extension and doesn't support .ai and .eps files very well, save as backwards compatible as you can.)
You can use the drawing features to generate crop marks.
Header and footer set up is a bit counter-intuitive but it works. (http://www.fpdf.org/en/tutorial/tuto2.htm)
The orientation of the pages and the sizing are pretty easy to set.(http://www.fpdf.org/en/doc/fpdf.htm)
Multicell is a VERY useful function for dynamically generated content, though there is no way of handling overflow built it. You'll have to have some way of doing character counts and passing the data into blocks for complex layouts.
I believe there is an extension in the forums for pagination. (http://www.fpdf.org/en/script/script86.php)
plus I'm a cheapskate :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to convert Strings to and from UTF8 byte arrays in Java In Java, I have a String and I want to encode it as a byte array (in UTF8, or some other encoding). Alternately, I have a byte array (in some known encoding) and I want to convert it into a Java String. How do I do these conversions?
A: As an alternative, StringUtils from Apache Commons can be used.
byte[] bytes = {(byte) 1};
String convertedString = StringUtils.newStringUtf8(bytes);
or
String myString = "example";
byte[] convertedBytes = StringUtils.getBytesUtf8(myString);
If you have non-standard charset, you can use getBytesUnchecked() or newString() accordingly.
A: I can't comment but don't want to start a new thread. But this isn't working. A simple round trip:
byte[] b = new byte[]{ 0, 0, 0, -127 }; // 0x00000081
String s = new String(b,StandardCharsets.UTF_8); // UTF8 = 0x0000, 0x0000, 0x0000, 0xfffd
b = s.getBytes(StandardCharsets.UTF_8); // [0, 0, 0, -17, -65, -67] 0x000000efbfbd != 0x00000081
I'd need b[] the same array before and after encoding which it isn't (this referrers to the first answer).
A: Convert from String to byte[]:
String s = "some text here";
byte[] b = s.getBytes(StandardCharsets.UTF_8);
Convert from byte[] to String:
byte[] b = {(byte) 99, (byte)97, (byte)116};
String s = new String(b, StandardCharsets.US_ASCII);
You should, of course, use the correct encoding name. My examples used US-ASCII and UTF-8, two commonly-used encodings.
A: For decoding a series of bytes to a normal string message I finally got it working with UTF-8 encoding with this code:
/* Convert a list of UTF-8 numbers to a normal String
* Usefull for decoding a jms message that is delivered as a sequence of bytes instead of plain text
*/
public String convertUtf8NumbersToString(String[] numbers){
int length = numbers.length;
byte[] data = new byte[length];
for(int i = 0; i< length; i++){
data[i] = Byte.parseByte(numbers[i]);
}
return new String(data, Charset.forName("UTF-8"));
}
A: String original = "hello world";
byte[] utf8Bytes = original.getBytes("UTF-8");
A: You can convert directly via the String(byte[], String) constructor and getBytes(String) method. Java exposes available character sets via the Charset class. The JDK documentation lists supported encodings.
90% of the time, such conversions are performed on streams, so you'd use the Reader/Writer classes. You would not incrementally decode using the String methods on arbitrary byte streams - you would leave yourself open to bugs involving multibyte characters.
A: My tomcat7 implementation is accepting strings as ISO-8859-1; despite the content-type of the HTTP request. The following solution worked for me when trying to correctly interpret characters like 'é' .
byte[] b1 = szP1.getBytes("ISO-8859-1");
System.out.println(b1.toString());
String szUT8 = new String(b1, "UTF-8");
System.out.println(szUT8);
When trying to interpret the string as US-ASCII, the byte info wasn't correctly interpreted.
b1 = szP1.getBytes("US-ASCII");
System.out.println(b1.toString());
A: Here's a solution that avoids performing the Charset lookup for every conversion:
import java.nio.charset.Charset;
private final Charset UTF8_CHARSET = Charset.forName("UTF-8");
String decodeUTF8(byte[] bytes) {
return new String(bytes, UTF8_CHARSET);
}
byte[] encodeUTF8(String string) {
return string.getBytes(UTF8_CHARSET);
}
A: If you are using 7-bit ASCII or ISO-8859-1 (an amazingly common format) then you don't have to create a new java.lang.String at all. It's much much more performant to simply cast the byte into char:
Full working example:
for (byte b : new byte[] { 43, 45, (byte) 215, (byte) 247 }) {
char c = (char) b;
System.out.print(c);
}
If you are not using extended-characters like Ä, Æ, Å, Ç, Ï, Ê and can be sure that the only transmitted values are of the first 128 Unicode characters, then this code will also work for UTF-8 and extended ASCII (like cp-1252).
A: Charset UTF8_CHARSET = Charset.forName("UTF-8");
String strISO = "{\"name\":\"א\"}";
System.out.println(strISO);
byte[] b = strISO.getBytes();
for (byte c: b) {
System.out.print("[" + c + "]");
}
String str = new String(b, UTF8_CHARSET);
System.out.println(str);
A: Reader reader = new BufferedReader(
new InputStreamReader(
new ByteArrayInputStream(
string.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));
A: terribly late but i just encountered this issue and this is my fix:
private static String removeNonUtf8CompliantCharacters( final String inString ) {
if (null == inString ) return null;
byte[] byteArr = inString.getBytes();
for ( int i=0; i < byteArr.length; i++ ) {
byte ch= byteArr[i];
// remove any characters outside the valid UTF-8 range as well as all control characters
// except tabs and new lines
if ( !( (ch > 31 && ch < 253 ) || ch == '\t' || ch == '\n' || ch == '\r') ) {
byteArr[i]=' ';
}
}
return new String( byteArr );
}
A: //query is your json
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://my.site/test/v1/product/search?qy=");
StringEntity input = new StringEntity(query, "UTF-8");
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response=response = httpClient.execute(postRequest);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "290"
}
|
Q: Polynomial time algorithm for finding a Hamiltonian walk in a graph Is there a polynomial time algorithm for finding a Hamiltonian walk in a graph?
My algorithm is N factorial and is really slow.
A: It's NP complete. But if you do manage to find a good method, let me know and I'll show you how to get rich.
A: In general, as the (decision version of the) Hamiltonian Path problem is NP-complete, you cannot hope to get a polynomial-time algorithm for finding Hamiltonian paths. You can slightly speed it up with the usual N! → N22N dynamic programming trick (compute hp[v][w][S] = "is there a path that has endpoints v and w and whose vertices are the subset S" for every subset S and every two vertices v and w in it using DP), but that's still exponential.
However, there are many special kinds of graphs for which Hamiltonian paths will always exist, and they can be found easily (see work of Posa, Dirac, Ore, etc.)
For instance, the following is true: If every vertex of the graph has degree at least n/2, then the graph has a Hamiltonian path. You can in fact find one in O(n2), or IIRC even O(n log n) if you do it more cleverly.
[Rough sketch: First, just connect all vertices in some "Hamiltonian" cycle, nevermind if the edges are actually in the graph. Now for every edge (v,w) of your cycle that is not actually in the graph, consider the rest of the cycle: v...w. As deg(v)+deg(w)>=n, there exist consecutive x,y in your list (in that order) such that w is a neighbour of x and v is a neighbour of y. [Proof: Consider {the set of all neighbours of w} and {the set of all successors in your list of neighbours of v}; they must intersect.] Now change your cycle [v...xy...wv] to [vy...wx...v] instead, it has at least one less invalid edge, so you'll need at most n iterations to get a true Hamiltonian cycle. More details here.]
BTW: if what you are looking for is just a walk that includes every edge once, it's called an Eulerian walk and for graphs that have it (number of vertices of odd degree is 0 or 2), one can quite easily be found in polynomial time (fast).
A: Finding a better algorithm for the shortest is unlikely, as it is NP hard. But there are some heuristics that you could try, and perhaps you might want to consult your lecture notes for those ;) .
For less complexity you could find a short(ish) walk using the greedy algorithm.
A: Hmmm.. this depends on what your definitions are. An hamiltonian path is certainly NP-complete. However, an hamiltonian walk which can visit edges and vertices more than once (yes it's still called hamiltonian so long as you add the walk bit at the end) can be calculated in O(p^2logp) or O(max(c^2plogp, |E|)) so long as your graph meets a certain condition which Dirac first conjectured and the Takamizawa proved. See Takamizawa (1980) "An algorithm for finding a short closed spanning walk in a graph".
Paul
A: You just asked the million dollar question. Finding a Hamilton path is an NP-complete problem. Some NP-hard problems can be solved in polynomial time using dynamic programming, but (to my knowledge) this is not one of them.
A: Depending on just how the graphs you're working with are generated you might be able to get expected polynomial time against a random instance by doing greedy path extension and then a random edge swap when that gets stuck.
This works well against randomly generated relatively sparse graphs guaranteed to have a Hamiltonian walk.
A: My Query: Show that a search problem RHAM for finding a Hamiltonian cycle in the graph G is
self-reducible
A search problem R is self-reducible if it is Cook-reducible to a decision problem
SR={ x : R(x) ≠ ∅ }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Does the Java VM move objects in memory, and if so - how? Does the Java virtual machine ever move objects in memory, and if so, how does it handle updating references to the moved object?
I ask because I'm exploring an idea of storing objects in a distributed fashion (ie. across multiple servers), but I need the ability to move objects between servers for efficiency reasons. Objects need to be able to contain pointers to each-other, even to objects on remote servers. I'm trying to think of the best way to update references to moved objects.
My two ideas so far are:
*
*Maintain a reference indirection somewhere that doesn't move for the lifetime of the object, which we update if the object moves. But - how are these indirections managed?
*Keep a list of reverse-references with each object, so we know what has to be updated if the object is moved. Of course, this creates a performance overhead.
I'd be interested in feedback on these approaches, and any suggestions for alternative approaches.
A: The keyword you're after is "compacting garbage collector". JVMs are permitted to use one, meaning that objects can be relocated. Consult your JVM's manual to find out whether yours does, and to see whether there are any command-line options which affect it.
The conceptually simplest way to explain compaction is to assume that the garbage collector freezes all threads, relocates the object, searches heap and stack for all references to that object, and updates them with the new address. Actually it's more complex than that, since for performance reasons you don't want to perform a full sweep with threads stalled, so an incremental garbage collector will do work in preparation for compaction whenever it can.
If you're interested in indirect references, you could start by researching weak and soft references in Java, and also the remote references used by various RPC systems.
A: I'd be curious to know more about your requirements. As another answer suggests, Terracotta may be exactly what you are looking for.
There is a subtle difference however between what Terracotta provides, and what you are asking for, thus my inquiry.
The difference is that as far as you are concerned, Terracotta does not provide "remote" references to objects - in fact the whole "remote" notion of RMI, JMS, etc. is entirely absent when using Terracotta.
Rather, in Terracotta, all objects reside in large virtual heap. Threads, whether on Node 1, or Node 2, Node 3, Node 4, etc all have access to any object in the virtual heap.
There's no special programming to learn, or special APIs, objects in the "virtual" heap have exactly the same behavior as objects in the local heap.
In short, what Terracotta provides is a programming model for multiple JVMs that operates exactly the same as a the programming model for a single JVM. Threads in separate nodes simply behave like threads in a single node - object mutations, synchronized, wait, notify all behave exactly the same across nodes as as across threads - there's no difference.
Furthermore, unlike any solution to come before it, object references are maintained across nodes - meaning you can use ==. It's all a part of maintaining the Java Memory Model across the cluster which is the fundamental requirement to make "regular" Java (e.g. POJOs, synchronized, wait/notify) work (none of that works if you don't / can't preserve object identity across the cluster).
So the question comes back to you to further refine your requiements - for what purpose do you need "remote" pointers?
A: (Practically) Any garbage collected system has to move objects around in memory to pack them more densely and avoid fragmentation problems.
What you are looking at is a very large and complex subject. I'd suggest you read up on existing remote object style API's: .NET remoting and going further back technologies like CORBA
Any solution for tracking the references will be complicated by having to deal with all the failure modes that exist in distributed systems. The JVM doesn't have to worry about suddenly finding it can't see half of its heap because a network switch glitched.
When you drill into the design I think a lot of it will come down to how you want to handle different failure cases.
Response to comments:
Your question talks about storing objects in a distributed fashion, which is exactly what .NET remoting and CORBA address. Admittedly neither technology supports migration of these objects (AFAIK). But they both deal extensively with the concepts of object identity which is a critical part of any distributed object system: how do different parts of the system know which objects they are talking about.
I am not overly familiar with the details of the Java garbage collector, and I'm sure the Java and .NET garbage collectors have a lot of complexity in them to achieve maximum performance with minimum impact on the application.
However, the basic idea for garbage collection is:
*
*The VM stops all threads from running managed code
*It performs a reachability analysis from the set of known 'roots': static variables, local variables on all the threads. For each object it finds it follows all references within the object.
*Any object not identified by the reachability analysis is garbage.
*Objects that are still alive can then be moved down in memory to pack them densely. This means that any references to these objects also have to be updated with the new address. By controlling when a garbage collect can occur the VM is able to guarantee that there are no object references 'in-the-air' (ie. being held in a machine register) that would cause a problem.
*Once the process is complete the VM starts the threads executing again.
As a refinement of this process the VM can perform generational garbage collection, where separate heaps are maintained based on the 'age' of an object. Objects start in heap 0 and if they survive several GCs then the migrate to heap 1 and eventually to heap 2 (and so on - .NET supports 3 generations only though). The advantage of this is that the GC can run heap 0 collections very frequently, and not have to worry about doing the work to prove the long lived objects (which have ended up in heap 2) are still alive (which they almost certainly are).
There are other refinements to support concurrent garbage collection, and details around threads that are actually executing unmanaged code when the GC is scheduled that add a lot more complexity to this area.
A: In reference to the comment above about walking the heap.
Different GC's do it different ways.
Typically copying collectors when they walk the heap, they don't walk all of the objects in the heap. Rather they walk the LIVE objects in the heap. The implication is that if it's reachable from the "root" object, the object is live.
So, at this stage is has to touch all of the live objects anyway, as it copies them from the old heap to the new heap. Once the copy of the live objects is done, all that remains in the old heap are either objects already copied, or garbage. At that point the old heap can be discarded completely.
The two primary benefits of this kind of collector are that it compacts the heap during the copy phase, and that it only copies living objects. This is important to many systems because with this kind of collector, object allocation is dirt cheap, literally little more than incrementing a heap pointer. When GC happens, none of the "dead" objects are copied, so they don't slow the collector down. It also turns out in dynamic systems that there's a lot more little, temporary garbage, than there is long standing garbage.
Also, by walking the live object graph, you can see how the GC can "know" about every object, and keep track of them for any address adjustment purposes performed during the copy.
This is not the forum to talk deeply about GC mechanics, as it's a non-trivial problem, but that's the basics of how a copying collector works.
A generational copying GC will put "older" objects in different heaps, and those end up being collected less often than "newer" heaps. The theory is that the long lasting objects get promoted to older generations and get collected less and less, improving overall GC performance.
A: sounds like you are looking for a distributed cache, something like terracotta or oracle's java objece cache (formerly tangersol).
A: If you are willing to go that deep down, you can take a look to JBoss Cache architecture docs and grab some of its source code as reference.
This is not exactly what you described, but it works very similar.
Here's the link.
http://www.jboss.org/jbosscache/
I hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Maven Jdepend report contains no data I'm running the jdepend maven plugin on my project and whether I run "mvn site:site" or "mvn jdepend:generate" the report that gets generated says "There are no package used." There are no errors in the maven output. Other plugins (cobertura, findbugs, etc.) run fine. My pom is configured like this:
<reporting>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jdepend-maven-plugin</artifactId>
</plugin>
Any ideas?
A: Did you try running "mvn -U -cpu site:site" to update all the maven dependencies?
Maybe this question is better asked in the Maven forum :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: YUI Autocomplete renders under other page elements in IE7 I'm working now on a page that has a column of boxes styled with sexy shadows and corners and whatnot using the example here. I have to admit, I don't fully understand how that CSS works, but it looks great.
Inside the topmost box is a text-type input used for searching. That search box is wired up to a YUI autocomplete widget.
Everything works fine in Firefox3 on Mac, FF2 on Windows, Safari on Mac. In IE7 on WinXP, the autocomplete suggestions render underneath the round-cornered boxes, making all but the first one unreadable (although you can still see enough peeking out between boxes that I'm comfortable IE7 really is getting more than one suggestion).
Where could I start looking to correct the problem?
Here's what success looks like in FF2 on WinXP:
And here's what failure looks like in IE7:
A: Jeremy,
Sorry for this being so late, but hopefully the answer will be of use to you in a future project.
The problem here is that IE creates a new stacking order anytime there is an element with position:relative, meaning that z-index itself is not the only controlling factor. You can read more about this here:
http://therealcrisp.xs4all.nl/meuk/IE-zindexbug.html
To solve the problem, if I'm understanding your problem correctly, apply position:relative to the container that wraps your whole autocomplete implementation (and then position:absolute to your results container). That should create an independent stacking order in IE for those elements that allows them to float over the other position:relative stacks that appear later in the page.
Regards,
Eric
A: The working solution I finally implemented was based on reading this explanation over and over again.
In the underlying HTML, all of the blue rounded corner elements are DIVs, and they're all siblings (all children of the same DIV).
The z-index of the autocomplete div itself (which is the great-great-grandchild of the rounded corner container div) can be arbitrarily high, and it won't fix this issue, because IE was essentially rendering the entire contents of the search box below the entire contents of the "Vital Stats" box, because both had default z-index, and Vital Stats was later in the HTML.
The trick was to give each of these sibling DIVs (the blue rounded corner containers) descending z-indexes, and mark all of them position:relative. So the blue div that contains the search box is z-index:60, the "Vital Stats" box is z-index:50, "Tags" is z-index:40, and so on.
So, more generally, find the common ancestor of both the element that is getting overlapped and the element that is overlapping. On the immediate children of the common ancestor, apply z-indexes in the order you want content to show up.
A: I'm not totally understanding the setup that's leading to the problem, but you might want to explore the useIFrame property of the YUI Autocomplete object -- it layers an iframe object beneath the autocomplete field, which allows the field to then float above the objects that are obscuring it in IE's buggy layout.
http://developer.yahoo.com/yui/docs/YAHOO.widget.AutoComplete.html#property_useIFrame
But the docs say that this matters in 5.5 < IE < 7, so this might not be the issue you're experiencing. So again, without totally understanding the setup you're working with, you might also want to try to experiment with various z-index values for the autocomplete field and the surrounding block-level elements.
A: Make sure the z-index of the auto-complete div is a larger number than the divs that constitute the rounded corner box. Microsoft puts the z-index of the top elements to 20000 or 100000 I believe. Might be wise to do the same.
A: I had a similar problem to this, I fixed it by basically just changing z-index for the different divs. Just setting higher number for each div in the order it should display.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: "Error Creating Window Handle" We're working on a very large .NET WinForms composite application - not CAB, but a similar home grown framework. We're running in a Citrix and RDP environment running on Windows Server 2003.
We're starting to run into random and difficult to reproduct "Error creating window handle" error that seems to be an old fashion handle leak in our application. We're making heavy use of 3rd Party controls (Janus GridEX, Infralution VirtualTree, and .NET Magic docking) and we do a lot of dynamic loading and rendering of content based on metadata in our database.
There's a lot of info on Google about this error, but not a lot of solid guidance about how to avoid issues in this area.
Does the stackoverflow community have any good guidance for me for building handle-friendly winforms apps?
A: I had this error when I subclassed NativeWindow and called CreateHandler manually. The problem was I forgot to add base.WndProc(m) in my overriden version of WndProc. It caused the same error
A: I met this exception because endless loop creating new UI control and set its properties.
After looped many times, this excption was thrown when change control visible property.
I found both User Object and GDI Object (From Task Manager) are quite large.
I guess your issue is similar reason that system resources are exhaust by those UI controls.
A: I am using the Janus Controls at work. They are extremely buggy as far as disposing of themselves go. I would recommend that you make sure that they are getting disposed of correctly. Also, the binding with them sometimes doesn't release, so you have to manually unbind the object to dispose of the control.
A: I have tracked down a lot of issues with UIs not unloading as expected in WinForms.
Here are some general hints:
*
*alot of the time, a control will stay in use because controls events are not properly removed (the tooltip provider caused us really large issues here) or the controls are not properly Disposed.
*use 'using' blocks around all modal dialogs to ensure that they are Disposed
*there are some control properties that will force the creation of the window handle before it is necessary (for example setting the ReadOnly property of a TextBox control will force the control to be realized)
*use a tool like the .Net Memory profiler to get counts of the classes that are created. Newer versions of this tool will also track GDI and USER objects.
*try to minimize your use of Win API calls (or other DllImport calls). If you do need to use interop, try to wrap these calls in such a way that the using/Dispose pattern will work correctly.
A: I faced this exception while adding controls in to the panel, Because in panel child controls not cleared. If dispose the child controls in panel then bug fixed.
For k = 1 To Panel.Controls.Count
Panel.Controls.Item(0).Dispose()
Next
A: Understanding this error
Pushing the Limits of Windows: USER and GDI Objects – Part 1 by Mark Russinovich:
https://blogs.technet.microsoft.com/markrussinovich/2010/02/24/pushing-the-limits-of-windows-user-and-gdi-objects-part-1/
Troubleshooting this error
You need to be able to reproduce the problem. Here is one way of recording the steps to do that https://stackoverflow.com/a/30525957/495455.
The easiest way to work out what is creating so many handles is to have TaskMgr.exe open. In TaskMgr.exe you need to have the USER Object, GDI Object and Handles columns visible as shown, to do this choose View Menu > Select Columns:
Go through the steps to cause the problem and watch the USER Object count increase to around 10,000 or GDI Objects or Handles reach their limits.
When you see the Object or Handles increase (typically dramatically) you can halt the code execution in Visual Studio by clicking the Pause button.
Then just hold down F10 or F11 to cruise through the code watching when the Object/Handle counts increases dramatically.
The best tool I have found so far is GDIView from NirSoft, it breaks up the GDI Handle fields:
I tracked it down to this code used when setting DataGridViews "Filter Combobox" Columns Location and Width:
If Me.Controls.ContainsKey(comboName) Then
cbo = CType(Me.Controls(comboName), ComboBox)
With cbo
.Location = New System.Drawing.Point(cumulativeWidth, 0)
.Width = Me.Columns(i).Width
End With
'Explicitly cleaning up fixed the issue of releasing USER objects.
cbo.Dispose()
cbo = Nothing
End If
In my case (above) the solution was explicitly disposing and cleaning up that fixed the issue of releasing USER objects.
This is the stack trace:
at System.Windows.Forms.Control.CreateHandle() at
System.Windows.Forms.ComboBox.CreateHandle() at
System.Windows.Forms.Control.get_Handle() at
System.Windows.Forms.ComboBox.InvalidateEverything() at
System.Windows.Forms.ComboBox.OnResize(EventArgs e) at
System.Windows.Forms.Control.OnSizeChanged(EventArgs e) at
System.Windows.Forms.Control.UpdateBounds(Int32 x, Int32 y, Int32
width, Int32 height, Int32 clientWidth, Int32 clientHeight) at
System.Windows.Forms.Control.UpdateBounds(Int32 x, Int32 y, Int32
width, Int32 height) at
System.Windows.Forms.Control.SetBoundsCore(Int32 x, Int32 y, Int32
width, Int32 height, BoundsSpecified specified) at
System.Windows.Forms.ComboBox.SetBoundsCore(Int32 x, Int32 y, Int32
width, Int32 height, BoundsSpecified specified) at
System.Windows.Forms.Control.SetBounds(Int32 x, Int32 y, Int32 width,
Int32 height, BoundsSpecified specified) at
System.Windows.Forms.Control.set_Width(Int32 value)
Here is the crux of a helpful article by Fabrice that helped me work out the limits:
"Error creating window handle"
When a big Windows Forms application I'm working on for a client is used actively, users often get "Error creating window handle" exceptions.
Aside from the fact that the application consumes too much resources, which is a separate issue altogether that we are already addressing, we had difficulties with determining what resources were getting exhausted as well as what the limits are for these resources.
We first thought about keeping an eye on the Handles counter in the Windows Task Manager. That was because we noticed that some processes tended to consume more of these resources than they normally should. However, this counter is not the good one because it keeps track of resources such as files, sockets, processes and threads. These resources are named Kernel Objects.
The other kinds of resources that we should keep an eye on are the GDI Objects and the User Objects. You can get an overview of the three categories of resources on MSDN.
User Objects
Window creation issues are directly related to User Objects.
We tried to determine what the limit is in terms of User Objects an application can use.
There is a quota of 10,000 user handles per process. This value can be changed in the registry, however this limit was not the real show-stopper in our case.
The other limit is 66,536 user handles per Windows session. This limit is theoretical. In practice, you'll notice that it can't be reached. In our case, we were getting the dreaded "Error creating window handle" exception before the total number of User Objects in the current session reached 11,000.
Desktop Heap
We then discovered which limit was the real culprit: it was the "Desktop Heap".
By default, all the graphical applications of an interactive user session execute in what is named a "desktop". The resources allocated to such a desktop are limited (but configurable).
Note: User Objects are what consumes most of the Desktop Heap's memory space. This includes windows.
For more information about the Desktop Heap, you can refer to the very good articles published on the NTDebugging MSDN blog:
What's the real solution? Be green!
Increasing the Desktop Heap is an effective solution, but that's not the ultimate one. The real solution is to consume less resources (less window handles in our case). I can guess how disappointed you can be with this solution. Is this really all what I can come up with??
Well, there is no big secret here. The only way out is to be lean. Having less complicated UIs is a good start. It's good for resources, it's good for usability too. The next step is to avoid waste, to preserve resources, and to recycle them!
Here is how we're doing this in my client's application:
We use TabControls and we create the content of each tab on the fly, when it becomes visible;
We use expandable/collapsible regions, and again fill them with controls and data only when needed;
We release resources as soon as possible (using the Dispose method). When a region is collapsed, it's possible to clear it's child controls. The same for a tab when it becomes hidden;
We use the MVP design pattern, which helps in making the above possible because it separates data from views;
We use layout engines, the standard FlowLayoutPanel and TableLayoutPanel ones, or custom ones, instead of creating deep hierarchies of nested panels, GroupBoxes and Splitters (an empty splitter itself consumes three window handles...).
The above are just hints at what you can do if you need to build rich Windows Forms screens. There's not doubt that you can find other approaches.
The first thing you should do in my opinion is building your applications around use cases and scenarios. This helps in displaying only what's needed at a given time, and for a given user.
Of course, another solution would be to use a system that doesn't rely on handles... WPF anyone?
A: I ran into the same .Net runtime error but my solution was different.
My Scenario:
From a popup Dialog that returned a DialogResult, the user would click a button to send an email message. I added a thread so the UI didn't lock up while generating the report in the background. This scenario ended up getting that unusual error message.
The code that resulted in problem:
The problem with this code is that the thread immediately starts and returns which results in the DialogResult being returned which disposes the dialog before the thread can properly grab the values from the fields.
private void Dialog_SendEmailSummary_Button_Click(object sender, EventArgs e)
{
SendSummaryEmail();
DialogResult = DialogResult.OK;
}
private void SendSummaryEmail()
{
var t = new Thread(() => SendSummaryThread(Textbox_Subject.Text, Textbox_Body.Text, Checkbox_IncludeDetails.Checked));
t.Start();
}
private void SendSummaryThread(string subject, string comment, bool includeTestNames)
{
// ... Create and send the email.
}
The fix for this scenario:
The fix is to grab and store the values before passing them into the method which creates the thread.
private void Dialog_SendEmailSummary_Button_Click(object sender, EventArgs e)
{
SendSummaryEmail(Textbox_Subject.Text, Textbox_Body.Text, Checkbox_IncludeDetails.Checked);
DialogResult = DialogResult.OK;
}
private void SendSummaryEmail(string subject, string comment, bool includeTestNames)
{
var t = new Thread(() => SendSummaryThread(subject, comment, includeTestNames));
t.Start();
}
private void SendSummaryThread(string subject, string comment, bool includeTestNames)
{
// ... Create and send the email.
}
A: same error occured when i started using threading in my WinForm App,
i used stack trace to find what is throwing error and found out UltraDesktopAlert component of infragistics was behind this so i invoked it differently and error is now gone.
this.Invoke((MethodInvoker)delegate
{
//call your method here
});
the full code will look like this.
private void ultraButton1_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(() => myMethod1());
}
void myMethod1()
{
//my logic
this.Invoke((MethodInvoker)delegate
{
ultraDesktopAlert1.Show($"my message header", "my message");
});
//my logic
}
also i was unable to use GDI utility to find how many handle my app creates but my app (64bit) was not available in its list.
another solution was to change desktop heap value to SharedSection=1024,20480,768 at following location HKEY
Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\SubSystems
but mine was already with same values. only invoke method delegate worked for me. hope this helped.
A: In my case I was overriding WndProc(ref Message m) but not calling base.WndProc(ref m);
A: I had the same error but in my C# Windows Service. Inside my service, in OnStart() method I was creating a new WinForms Object using a "using" statement. Just after that my service was throwing this error.
My fix was simple, it turned out that if I start my service using a Log On As "Local System" it was throwing that error, but If I start my service using a Account Type it was all good.
I hope someone will find this useful.
A: Greeting,
I facing same problem due to large amount of PictureBox for image processing was added to panel. Original code use Controls.RemoveAt(0) still cause the problem. Just changed to Controls[0].Dispose -> seem like problem away.
while (mGridPanel.Controls.Count > 0)
mGridPanel.Controls[0].Dispose();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
}
|
Q: Zend Framework - ErrorHandler does not seem to be working as expected This is my first experience using the Zend Framework. I am attempting to follow the Quick Start tutorial. Everything was working as expected until I reached the section on the Error Controller and View. When I navigate to a page that does not exist, instead of receiving the error page I get the Fatal Error screen dump (in all it's glory):
Fatal error: Uncaught exception 'Zend_Controller_Dispatcher_Exception'
with message 'Invalid controller specified (error)' in
/home/.fantasia/bcnewman/foo.com/library/Zend/Controller/Dispatcher/Standard.php:249
Stack trace: #0
/home/.fantasia/bcnewman/foo.com/library/Zend/Controller/Front.php(946):
Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http),
Object(Zend_Controller_Response_Http)) #1
/home/.fantasia/bcnewman/foo.com/public/index.php(42):
Zend_Controller_Front->dispatch() #2 {main} thrown in
/home/.fantasia/bcnewman/foo.com/library/Zend/Controller/Dispatcher/Standard.php
on line 249
I do not believe this is caused by a syntax error on my part (a copied and pasted the example file's content from the tutorial) and I believe I have the application directory structure correct:
./application
./application/controllers
./application/controllers/IndexController.php
./application/controllers/ErrorHandler.php
./application/views
./application/views/scripts
./application/views/scripts/index
./application/views/scripts/index/index.phtml
./application/views/scripts/error
./application/views/scripts/error/error.phtml
./application/bootstrap.php
./public
./public/index.php
And finally, the IndexController and index.phtml view does work.
A: You have ErrorHandler.php. It should be ErrorController.php. Controllers all need to be named following the format of NameController.php. Since you don't have it named properly the dispatcher cannot find it.
A: Assuming that you have the ErrorController plugin loaded into your front controller, make sure that in your bootstrap that you do not have the following set:
$frontController->throwExceptions(true);
If this is set then Exceptions will always be thrown, regardless of whether or not you have an error controller set.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What is a heuristic fencepost? And why does gdb seem to "hit" it?
A: According to this page, GDB is searching backward in the object code to find the beginning of a function, and it is hitting an imposed limit. If you can set the fence post limit to 0 or increase it, you might avoid the error, but it will take longer to run.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Using git to grep through a file's previous versions? Is there a command that would allow me to check if the string "xyz" was ever in file foo.c in the repository and print which revisions they were found in?
A: This will print any commits where the diff contains xyz. Note the -- separating the filename from the rest of the command.
git log -Sxyz -- foo.c
Without the --, I get this error:
fatal: ambiguous argument 'foo.c': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
I originally wanted to comment on CaptainPicard's answer to add a correction, but I don't have sufficient reputation yet. If someone would like to edit that answer to mention this correction I'll be happy to take this answer down.
A: This will print any commits where the diff contains xyz
git log -Sxyz foo.c
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
}
|
Q: lining up function parameter lists with vim When defining or calling functions with enough arguments to span multiple lines, I want vim to line them up. For example,
def myfunction(arg1, arg2, arg, ...
argsN-1, argN)
The idea is for argsN-1 to have its 'a' lined up with args1.
Does anyone have a way to have this happen automatically in vim? I've seen the align plugin for lining equal signs (in assignment statements) and such, but I'm not sure if it can be made to solve this problem?
A: I believe you have to issue the command:
:set cino=(0
This is when using cindent of course.
edit: I missed "set"
A: Try the Align http://www.vim.org/scripts/script.php?script_id=294 and AutoAlign http://www.vim.org/scripts/script.php?script_id=884 scripts.
A: The previous poster had it, but forgot the set
:set cino=(0<Enter>
From :help cinoptions-values
The 'cinoptions' option sets how Vim performs indentation. In the list below,
"N" represents a number of your choice (the number can be negative). When
there is an 's' after the number, Vim multiplies the number by 'shiftwidth':
"1s" is 'shiftwidth', "2s" is two times 'shiftwidth', etc. You can use a
decimal point, too: "-0.5s" is minus half a 'shiftwidth'. The examples below
assume a 'shiftwidth' of 4.
...
(N When in unclosed parentheses, indent N characters from the line
with the unclosed parentheses. Add a 'shiftwidth' for every
unclosed parentheses. When N is 0 or the unclosed parentheses
is the first non-white character in its line, line up with the
next non-white character after the unclosed parentheses.
(default 'shiftwidth' * 2).
cino= cino=(0 >
if (c1 && (c2 || if (c1 && (c2 ||
c3)) c3))
foo; foo;
if (c1 && if (c1 &&
(c2 || c3)) (c2 || c3))
{ {
A: you might get some good mileage out of using a language-specific external tool as a Vim filter. for example, if you can write a Perltidy config file to generate the formatting you want (it looks like you would want the -lp -vtc=2 flags), you can then pipe your existing Vim buffer through it with
:!/path/to/tidy -config /path/to/configfile
if you're going to be running this sort of command frequently, you can define an command by putting something like the following in your .vimrc:
command -range=% Tidy <line1>,<line2>!/path/to/tidy -config /path/to/configfile
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Why does PEP-8 specify a maximum line length of 79 characters? Why in this millennium should Python PEP-8 specify a maximum line length of 79 characters?
Pretty much every code editor under the sun can handle longer lines. What to do with wrapping should be the choice of the content consumer, not the responsibility of the content creator.
Are there any (legitimately) good reasons for adhering to 79 characters in this age?
A: I am a programmer who has to deal with a lot of code on a daily basis. Open source and what has been developed in house.
As a programmer, I find it useful to have many source files open at once, and often organise my desktop on my (widescreen) monitor so that two source files are side by side. I might be programming in both, or just reading one and programming in the other.
I find it dissatisfying and frustrating when one of those source files is >120 characters in width, because it means I can't comfortably fit a line of code on a line of screen. It upsets formatting to line wrap.
I say '120' because that's the level to which I would get annoyed at code being wider than. After that many characters, you should be splitting across lines for readability, let alone coding standards.
I write code with 80 columns in mind. This is just so that when I do leak over that boundary, it's not such a bad thing.
A: Since whitespace has semantic meaning in Python, some methods of word wrapping could produce incorrect or ambiguous results, so there needs to be some limit to avoid those situations. An 80 character line length has been standard since we were using teletypes, so 79 characters seems like a pretty safe choice.
A: I believe those who study typography would tell you that 66 characters per a line is supposed to be the most readable width for length. Even so, if you need to debug a machine remotely over an ssh session, most terminals default to 80 characters, 79 just fits, trying to work with anything wider becomes a real pain in such a case. You would also be suprised by the number of developers using vim + screen as a day to day environment.
A: Printing a monospaced font at default sizes is (on A4 paper) 80 columns by 66 lines.
A: I agree with Justin. To elaborate, overly long lines of code are harder to read by humans and some people might have console widths that only accommodate 80 characters per line.
The style recommendation is there to ensure that the code you write can be read by as many people as possible on as many platforms as possible and as comfortably as possible.
A: Much of the value of PEP-8 is to stop people arguing about inconsequential formatting rules, and get on with writing good, consistently formatted code. Sure, no one really thinks that 79 is optimal, but there's no obvious gain in changing it to 99 or 119 or whatever your preferred line length is. I think the choices are these: follow the rule and find a worthwhile cause to battle for, or provide some data that demonstrates how readability and productivity vary with line length. The latter would be extremely interesting, and would have a good chance of changing people's minds I think.
A: Here's why I like the 80-character with: at work I use Vim and work on two files at a time on a monitor running at, I think, 1680x1040 (I can never remember). If the lines are any longer, I have trouble reading the files, even when using word wrap. Needless to say, I hate dealing with other people's code as they love long lines.
A: Keeping your code human readable not just machine readable. A lot of devices still can only show 80 characters at a time. Also it makes it easier for people with larger screens to multi-task by being able to set up multiple windows to be side by side.
Readability is also one of the reasons for enforced line indentation.
A: because if you push it beyond the 80th column it means that either you are writing a very long and complex line of code that does too much (and so you should refactor), or that you indented too much (and so you should refactor).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "306"
}
|
Q: Is there any reason to not ship the pdb's with your application? Since you can use reflector to reverse-engineer a .Net app, is there any reason to NOT ship the pdb files with the app? If you do ship them with it, then your stack trace will include the line number with the problem, which is useful if it crashes.
Please only enter 1 reason per comment for voting.
A: Shipping pdb does not give any additional convenience to an user. So there are no reasons to ship pdb files with the app. Besides pdb file usually has a large size.
Instead of shipping pdb files you should use a local Microsoft Symbol Server for a fast access to pdb files corresponding to error reports. Here you can find the detailed explanation how to use Symbol Server.
A: Shipping PDBs with your application allows easier reverse engineering as it contains local variable/object names, function prototypes, etc.
A: Most people want to ship an optimised build. But if you ship a pdb with an optimised build, the source line numbers you get are likely to be off.
A: Reflectors can get a high-level version of the MSIL code of your .NET application, but that doesn't mean it's necessarily usable/hackable... A lot of the code won't make sense to casual perusal without the names of private variables & functions along with other things that .NET Reflector cannot access without a PDB file.
Obviously if you're using any decent obfuscator (personally I like {smartassembly} but for its lack of cross-obfuscation), then you'll be losing out on all its protections just for the added value of line numbers, which isn't a really fair trade-off.
Anyway, line numbers are overrated!
A: Why would you ship anything more than you need to?
A: Apart from the fact that they are extremely heavy in any serious project? No, there´s no reason if you don't mind people reverse engineering your software.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: What does {0} mean when initializing an object? When {0} is used to initialize an object, what does it mean? I can't find any references to {0} anywhere, and because of the curly braces Google searches are not helpful.
Example code:
SHELLEXECUTEINFO sexi = {0}; // what does this do?
sexi.cbSize = sizeof(SHELLEXECUTEINFO);
sexi.hwnd = NULL;
sexi.fMask = SEE_MASK_NOCLOSEPROCESS;
sexi.lpFile = lpFile.c_str();
sexi.lpParameters = args;
sexi.nShow = nShow;
if(ShellExecuteEx(&sexi))
{
DWORD wait = WaitForSingleObject(sexi.hProcess, INFINITE);
if(wait == WAIT_OBJECT_0)
GetExitCodeProcess(sexi.hProcess, &returnCode);
}
Without it, the above code will crash on runtime.
A: One thing to be aware of is that this technique will not set padding bytes to zero. For example:
struct foo
{
char c;
int i;
};
foo a = {0};
Is not the same as:
foo a;
memset(&a,0,sizeof(a));
In the first case, pad bytes between c and i are uninitialized. Why would you care? Well, if you're saving this data to disk or sending it over a network or whatever, you could have a security issue.
A: I also use it to initialize strings eg.
char mytext[100] = {0};
A: What's happening here is called aggregate initialization. Here is the (abbreviated) definition of an aggregate from section 8.5.1 of the ISO spec:
An aggregate is an array or a class with no user-declared constructors, no private or protected non-static data members, no base classes, and no virtual functions.
Now, using {0} to initialize an aggregate like this is basically a trick to 0 the entire thing. This is because when using aggregate initialization you don't have to specify all the members and the spec requires that all unspecified members be default initialized, which means set to 0 for simple types.
Here is the relevant quote from the spec:
If there are fewer initializers in the list than there are members in the
aggregate, then each member not
explicitly initialized shall be
default-initialized.
Example:
struct S { int a; char* b; int c; };
S ss = { 1, "asdf" };
initializes ss.a with 1, ss.b with
"asdf", and ss.c with the value of an
expression of the form int(), that is,
0.
You can find the complete spec on this topic here
A: It's been awhile since I worked in c/c++ but IIRC, the same shortcut can be used for arrays as well.
A: Note that an empty aggregate initializer also works:
SHELLEXECUTEINFO sexi = {};
char mytext[100] = {};
A: I have always wondered, why you should use something like
struct foo bar = { 0 };
Here is a test case to explain:
check.c
struct f {
int x;
char a;
} my_zero_struct;
int main(void)
{
return my_zero_struct.x;
}
I compile with gcc -O2 -o check check.c and then output the symbol table with readelf -s check | sort -k 2 (this is with gcc 4.6.3 on ubuntu 12.04.2 on a x64 system). Excerpt:
59: 0000000000601018 0 NOTYPE GLOBAL DEFAULT ABS __bss_start
48: 0000000000601018 0 NOTYPE GLOBAL DEFAULT ABS _edata
25: 0000000000601018 0 SECTION LOCAL DEFAULT 25
33: 0000000000601018 1 OBJECT LOCAL DEFAULT 25 completed.6531
34: 0000000000601020 8 OBJECT LOCAL DEFAULT 25 dtor_idx.6533
62: 0000000000601028 8 OBJECT GLOBAL DEFAULT 25 my_zero_struct
57: 0000000000601030 0 NOTYPE GLOBAL DEFAULT ABS _end
The important part here is, that my_zero_struct is after __bss_start. The ".bss" section in a C program is the section of memory which is set to zero before main is called see wikipedia on .bss.
If you change the code above to:
} my_zero_struct = { 0 };
Then the resulting "check" executable looks exactly the same at least with the gcc 4.6.3 compiler on ubuntu 12.04.2; the my_zero_struct is still in the .bss section and thus it will be automatically initialized to zero, before main is called.
Hints in the comments, that a memset might initialize the "full" structure is also not an improvement, because the .bss section is cleared fully which also means the "full" structure is set to zero.
It might be that the C language standard does not mention any of this, but in a real world C compiler I have never seen a different behaviour.
A: In answer to why ShellExecuteEx() is crashing: your SHELLEXECUTEINFO "sexi" struct has many members and you're only initializing some of them.
For example, the member sexi.lpDirectory could be pointing anywhere, but ShellExecuteEx() will still try to use it, hence you'll get a memory access violation.
When you include the line:
SHELLEXECUTEINFO sexi = {0};
before the rest of your structure setup, you're telling the compiler to zero out all structure members before you initialize the specific ones you're interested in. ShellExecuteEx() knows that if sexi.lpDirectory is zero, it should ignore it.
A: {0} is a valid initializer for any (complete object) type, in both C and C++. It's a common idiom used to initialize an object to zero (read on to see what that means).
For scalar types (arithmetic and pointer types), the braces are unnecessary, but they're explicitly allowed. Quoting the N1570 draft of the ISO C standard, section 6.7.9:
The initializer for a scalar shall be a single expression, optionally enclosed in braces.
It initializes the object to zero (0 for integers, 0.0 for floating-point, a null pointer for pointers).
For non-scalar types (structures, arrays, unions), {0} specifies that the first element of the object is initialized to zero. For structures containing structures, arrays of structures, and so on, this is applied recursively, so the first scalar element is set to the zero, as appropriate for the type. As in any initializer, any elements not specified are set to zero.
Intermediate braces ({, }) may be omitted; for example both these are valid and equivalent:
int arr[2][2] = { { 1, 2 }, {3, 4} };
int arr[2][2] = { 1, 2, 3, 4 };
which is why you don't have to write, for example, { { 0 } } for a type whose first element is non-scalar.
So this:
some_type obj = { 0 };
is a shorthand way of initializing obj to zero, meaning that each scalar sub-object of obj is set to 0 if it's an integer, 0.0 if it's floating-point, or a null pointer if it's a pointer.
The rules are similar for C++.
In your particular case, since you're assigning values to sexi.cbSize and so forth, it's clear that SHELLEXECUTEINFO is a struct or class type (or possibly a union, but probably not), so not all of this applies, but as I said { 0 } is a common idiom that can be used in more general situations.
This is not (necessarily) equivalent to using memset to set the object's representation to all-bits-zero. Neither floating-point 0.0 nor a null pointer is necessarily represented as all-bits-zero, and a { 0 } initializer doesn't necessarily set padding bytes to any particular value. On most systems, though, it's likely to have the same effect.
A: It's syntatic sugar to initialize your entire structure to empty/zero/null values.
Long version
SHELLEXECUTEINFO sexi;
sexi.cbSize = 0;
sexi.fMask = 0;
sexi.hwnd = NULL;
sexi.lpVerb = NULL;
sexi.lpFile = NULL;
sexi.lpParameters = NULL;
sexi.lpDirectory = NULL;
sexi.nShow = nShow;
sexi.hInstApp = 0;
sexi.lpIDList = NULL;
sexi.lpClass = NULL;
sexi.hkeyClass = 0;
sexi.dwHotKey = 0;
sexi.hMonitor = 0;
sexi.hProcess = 0;
Short version
SHELLEXECUTEINFO sexi = {0};
Wasn't that much easier?
It's also nice because:
*
*you don't have to hunt down every member and initialize it
*you don't have to worry that you might not initialize new members when they're added later
*you don't have have to call ZeroMemory
A: {0} is an anonymous array containing its element as 0.
This is used to initialize one or all elements of array with 0.
e.g. int arr[8] = {0};
In this case all the elements of arr will be initialized as 0.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "261"
}
|
Q: Preventing bad data input Is it good practice to delegate data validation entirely to the database engine constraints?
Validating data from the application doesn't prevent invalid insertion from another software (possibly written in another language by another team). Using database constraints you reduce the points where you need to worry about invalid input data.
If you put validation both in database and application, maintenance becomes boring, because you have to update code for who knows how many applications, increasing the probability of human errors.
I just don't see this being done very much, looking at code from free software projects.
A: It's best to, where possible, have your validation rules specified in your database and use or write a framework that makes those rules bubble up into your front end. ASP.NET Dynamic Data helps with this and there are some commercial libraries out there that make it even easier.
This can be done both for simple input validation (like numbers or dates) and related data like that constrained by foreign keys.
In summary, the idea is to define the rules in one place (the database most the time) and have code in other layers that will enforce those rules.
A: Validate at input time. Validate again before you put it in the database. And have database constraints to prevent bad input. And you can bet in spite of all that, bad data will still get into your database, so validate it again when you use it.
It seems like every day some web app gets hacked because they did all their validation in the form or worse, using Javascript, and people found a way to bypass it. You've got to guard against that.
Paranoid? Me? No, just experienced.
A: The disadvantage to leaving the logic to the database is then you increase the load on that particular server. Web and application servers are comparatively easy to scale outward, but a database requires special techniques. As a general rule, it's a good idea to put as much of the computational logic into the application layer and keep the interaction with the database as simple as possible.
With that said, it is possible that your application may not need to worry about such heavy scalability issues. If you are certain that database server load will not be a problem for the foreseeable future, then go ahead and put the constraints on the database. You are quite correct that this improves the organization and simplicity of your system as a whole by keeping validation logic in a central location.
A: There are other concerns than just SQL injection with input. You should take the most defensive stance possible whenever accepting user input. For example, a user might be able to enter a link to an image into a textbox, which is actually a PHP script that runs something nasty.
If you design your application well, you should not have to laboriously check all input. For example, you could use a Forms API which takes care of most of the work for you, and a database layer which does much the same.
This is a good resource for basic checking of vulnerabilities:
http://ha.ckers.org/xss.html
A: It's far too late by the time the data gets to your database to provide meaningful validation for your users and applications. You don't want your database doing all the validation since that'll slow things down pretty good, and the database doesn't express the logic as clearly. Similarly, as you grow you'll be writing more application level transactions to complement your database transactions.
A: I would say it's potentially a bad practice, depending on what happens when the query fails. For example, if your database could throw an error that was intelligently handled by an application, then you might be ok.
On the other hand, if you don't put any validation in your app, you might not have any bad data, but you may have users thinking they entered stuff that doesn't get saved.
A: Implement as much data validation as you can at the database end without compromising other goals. For example, if speed is an issue, you may want to consider not using foreign keys, etc. Furthermore, some data validation can only be performed on the application side, e.g., ensuring that email addresses have valid domains.
A: Another disadvantage to doing data validation from the database is that often you dont validate the same way in every case. In fact, it often depends on application logic (user roles), and sometimes you might want to bypass validation altogether (cron jobs and maintenance scripts).
A: I've found that doing validation in the application, rather than in the database, works well. Of course then, all the interaction needs to go through your application. If you have other applications that work with your data, your application will need to support some sort of API (hopefully REST).
A: I don't think there is one right answer, it depends on your use.
If you are going to have a very heavily used system, with the potential that the database performance might become a bottleneck, then you might want to move the responsibility for validation to the front-end where it is easier to scale with multiple servers.
If you have multiple applications interacting with the database, then you might not want to replicate and maintain the validation rules across multiple applications, so then the database might be the better place.
You might want a slicker input screen that doesn't just hit the user with validation warnings when they try to save a record, maybe you want to validate a field after data has been entered and it losses focus; or even as the user types, changing the font colour as validation fails/passes.
Also related to constraints, is warnings of suspect data. In my application I have hard-constraints in the database (e.g. someone can't start a job before their date of birth), but then in the front-end have warnings for data that is possibly correct, but suspect (e.g. an eight year-old starting a job).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Asynchronous file IO in .Net I'm building a toy database in C# to learn more about compiler, optimizer, and indexing technology.
I want to maintain maximum parallelism between (at least read) requests for bringing pages into the buffer pool, but I am confused about how best to accomplish this in .NET.
Here are some options and the problems I've come across with each:
*
*Use System.IO.FileStream and the BeginRead method
But, the position in the file isn't an argument to BeginRead, it is a property of the FileStream (set via the Seek method), so I can only issue one request at a time and have to lock the stream for the duration. (Or do I? The documentation is unclear on what would happen if I held the lock only between the Seek and BeginRead calls but released it before calling EndRead. Does anyone know?) I know how to do this, I'm just not sure it is the best way.
*There seems to be another way, centered around the System.Threading.Overlapped structure and P\Invoke to the ReadFileEx function in kernel32.dll.
Unfortunately, there is a dearth of samples, especially in managed languages. This route (if it can be made to work at all) apparently also involves the ThreadPool.BindHandle method and the IO completion threads in the thread pool. I get the impression that this is the sanctioned way of dealing with this scenario under windows, but I don't understand it and I can't find an entry point to the documentation that is helpful to the uninitiated.
*Something else?
*In a comment, jacob suggests creating a new FileStream for each read in flight.
*Read the whole file into memory.
This would work if the database was small. The codebase is small, and there are plenty of other inefficiencies, but the database itself isn't. I also want to be sure I am doing all the bookkeeping needed to deal with a large database (which turns out to be a huge part of the complexity: paging, external sorting, ...) and I'm worried it might be too easy to accidentally cheat.
Edit
Clarification of why I'm suspicious with solution 1: holding a single lock all the way from BeginRead to EndRead means I need to block anyone who wants to initiate a read just because another read is in progress. That feels wrong, because the thread initiating the new read might be able (in general) to do some more work before the results become available. (Actually, just writing this has led me to think up a new solution, I put as a new answer.)
A: I'm not sure I see why option 1 wouldn't work for you. Keep in mind that you can't have two different threads trying to use the same FileStream at the same time - doing so will definitely cause you problems. BeginRead/EndRead is meant to let your code continue executing while the potentially expensive IO operation takes places, not to enable some sort of multi-threaded access to a file.
So I would suggest that you seek and then do a beginread.
A: What we did was to write a small layer around I/O completion ports, ReadFile, and GetQueuedCompletion status in C++/CLI, and then call back into C# when the operation completed. We chose this route over BeginRead and the c# async operation pattern to provide more control over the buffers used to read from the file (or socket). This was a pretty big performance gain over the purely managed approach which allocates new byte[] on the heap with each read.
Plus, there are alot more complete C++ examples of using IO Completion ports out on the interwebs
A: What if you loaded the resource (file data or whatever) into memory first and then shared it across threads? Since it is a small db. - you won't have as many issues to deal with.
A: Use approach #1, but
*
*When a request comes in, take lock A. Use it to protect a queue of pending read requests. Add it to the queue and return some new async result. If this results in the first addition to the queue, call step 2 before returning. Release lock A before returning.
*When a read completes (or called by step 1), take lock A. Use it to protect popping a read request from the queue. Take lock B. Use it to protect the Seek -> BeginRead -> EndRead sequence. Release lock B. Update the async result created by step 1 for this read operation. (Since a read operation completed, call this again.)
This solves the problem of not blocking any thread that begins a read just because another read is in progress, but still sequences reads so that the file stream's current position doesn't get messed up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Produce conditional compile time error in Java I do not mean the compile errors because I made a syntax mistake or whatever. In C++ we can create compile time errors based on conditions as in the following example:
template<int> struct CompileTimeError;
template<> struct CompileTimeError<true> {};
#define STATIC_CHECK(expr, msg) { CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; }
int main(int argc, char* argv[])
{
STATIC_CHECK(false, Compile_Time_Failure);
return 0;
}
In VS 2005 this will output:
------ Build started: Project: Test, Configuration: Debug Win32 ------
Compiling...
Test.cpp
f:\temp\test\test\test.cpp(17) : error C2079: 'ERROR_Compile_Time_Failure' uses undefined struct 'CompileTimeError<__formal>'
with
[
__formal=0
]
Build log was saved at "file://f:\temp\Test\Test\Debug\BuildLog.htm"
Test - 1 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Is there any way to achieve this in Java?
A: There is no way to produce any actions based on compile-time logic in Java without the use of a separate tool. Technically, it is possible to use the C pre-processor on Java, but you would have to be careful of its built-in assumptions about the underlying language. If I were you, I would find a better way to accomplish whatever it is you're trying to do with this compile-time error. If necessary, you could even write your own pre-processor (possibly using APT) if it is really so unavoidable.
A: There is no way to do this in Java, not in the same way it works for you in C++.
You could perhaps use annotations, and run apt before or after compilation to check your annotations.
For example:
@MyStaticCheck(false, "Compile Time Error, kind-of")
public static void main(String[] args) {
return;
}
And then write your own AnnotationProcessorFactory that looked for @MyStaticCheck annotations, and does something with the arguments.
Note: I haven't played too much with apt, but the documentation makes it looks like this is very do-able.
A: As Matt Quail answered above, annotations, together with XDoclet, are suited to address your needs. That combinations allows for a quite a bit of preprocessing, code generation, etc.
A: Though the question was asked some time ago, I decided to post my answer, because I solved (to a certain degree) a slightly similar problem.
The specific of my task requires two applications with different function set to be built from a single core library (and unused stuff to be not linked in). The selection of function set is made by public static final boolean flags. The problem is that I want to ensure in each of the applications, that it is built with a proper flag set in the core library. And in the case of improper functions are enabled, the application should not compile giving a compile time error.
The only solution I have found so far is to declare in the library final variables along with the flags: public static final int functionSet1 = 0;, etc.
In the application package I added a dummy class with the checkup
ConditionalBuild.functionSet1 = 1;
From all the functionSetX variables only one made non-final at a specific build. So only one application can pass the build process without the error. Is there a better way to achieve this? Please let me know in comments.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/88991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Copyright and Fair Use in Distributable Software At what length of text and/or length of audio snippet does a piece of commercially distributable software pass the threshold of fair use and violate the included work's copyright? Does attribution absolve the developer from infringement? An example would be a quote from a novel used on a start-up screen.
A: Unfortunately, there is no cut and dried answer. Determining what is fair use involves a very subjective and fact-dependent four point test. You're never really going to know for sure if a borderline use is permissible or not unless you end up in court and a judge decides.
The four factors are:
*
*the purpose and character of the use, including whether such use is of a commercial nature or is for nonprofit educational purposes;
*the nature of the copyrighted work;
*the amount and substantiality of the portion used in relation to the copyrighted work as a whole; and
*the effect of the use upon the potential market for or value of the copyrighted work.
Each of these has a specific legal meaning based on previous precedents (which may or may not correspond to what most people would think of as the plain language meaning). If you're doing anything that could get you sued, talk to a lawyer.
Software is even more complicated, since not all code is copyrightable to begin with.
A: Also, keep in mind that laws vary from country to country, and since most software is distributed anywhere in the world over the web... well, it's a huge headache. It's unfortunate because the threat of lawsuit has a chilling effect on interesting, innovative work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Place To get EULA and Other Legalese For Software? I was curious if anyone out there has experience getting the necessary legal documents (user agreements, privacy policies, disclaimers, etc.) for a small software business. For example if you just want to have a software 'company' that sells a few piece of software that you have written, are there cheap solutions for something small scale like that?
A: In Micro-ISV: From Vision to Reality, Bob suggests MegaDox.com and Soft14.com
A: Stationery stores will sell standard boiler plate contracts.
For software specific stuff most companies just copy the ones from bigger companies and change the name!
A: The suggestions by others in other answers are probably fine if you intend to stay small scale, but if your intent is grow, and particularly if you might want to have someone else invest money in the business, then it makes sense to invest in a lawyer, one who has experience in software. It doesn’t have to cost a lot if you can develop a relationship with someone interested in working with you for the long run and not running up fees on those basic documents.
By the way, either route you go, it makes sense to read the documents and make sure they fit what you’re actually doing. If you post a boilerplate privacy policy that says you do x, y and z with customer data, but in fact you do a, b and c instead, you’re creating more potential legal troubles than you’re solving.
A: I'm testing the waters for a crowd funded project to develop user-friendly EULAs. The EULAs themselves would be developed like open source. If a user encounters one of these "open" EULAs, then the user can feel better about agreeing it because
*
*it's been reviewed by an open process, and
*you might encounter this same EULA over and over, so you don't have to read it every time.
https://sites.google.com/a/x2xroads.com/nutshell/open-eula
A: I have recently been looking for the same info as the OP and found a great book which includes standard agreements for software companies which you may use as is or modify with the help of a lawyer.
The IT/Digital Legal Companion: A Comprehensive Business Guide to Software,
Internet, and IP Law Includes Contract and Web Forms
By: Gene K. Landy; Amy J. Mastrobattista
Publisher: Syngress
Print ISBN-10: 1-59749-256-6
Print ISBN-13: 978-1-59749-256-0
It also includes sections explaining issues that you need to consider for different aspects of you software business in regard to contracts, privacy and intellectual property.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Queuing actions (not effects) to execute after an amount of time. What I'd like to know is if there is a nice way to queue jQuery functions to execute after a set amount of time. This wouldn't pause the execution of other functions, just the ones following in the chain. Perhaps an example of what I'd envisage it would look like would illustrate:
$('#alert')
.show()
.wait(5000) // <-- this bit
.hide()
;
I know that it's possible by using timeouts, but it seems like that's a messy way to do it, especially compared to the above example (if it were real).
So, is something like this already built-in to jQuery, and if not, what is the best way to emulate it?
A: You can't do that, and you probably don't want to. While it certainly looks pretty, there is no mechanism in Javascript that will allow you do to that without just looping in "wait" until the time has passed. You could certainly do that but you risk seriously degrading the browser performance and if your timeout is longer than a handful of seconds browsers will show a warning to the user that your javascript seems to be stuck.
The correct way to do this is with timeouts:
var el = $('#alert');
el.show()
setTimeout(function() { el.hide() }, 5000);
Your other option would be to extend jquery to essentially add an effect for actions you want to delay:
jQuery.fn.extend({
delayedHide: function(time) {
var self = this;
setTimeout(function() { self.hide(); }, time);
}
});
$('#alert')
.show()
.delayedHide(5000)
;
You could also extend jquery with a method similar to setTimeout:
jQuery.fn.extend({
delayThis: function(fn, time, args) {
var self = this;
setTimeout(function() { jQuery.fn[fn].apply(self, args); }, time);
}
});
$('#alert')
.show()
.delayThis('hide', 5000)
;
or to call with args pass arguments in an array:
$('#alert')
.show()
.delayThis('css', 5000, [ 'display', 'none' ])
;
A: The jQuery FxQueues plug-in does just what you need:
$('#element').fadeOut({
speed: 'fast',
preDelay: 5000
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How do you read C declarations? I have heard of some methods, but none of them have stuck. Personally I try to avoid complex types in C and try to break them into component typedef.
I'm now faced with maintaining some legacy code from a so called 'three star programmer', and I'm having a hard time reading some of the ***code[][].
How do you read complex C declarations?
A: One word: cdecl
Damnit, beaten by 15 seconds!
A: Cdecl (and c++decl) is a program for encoding and decoding C (or C++) type declarations.
http://gd.tuwien.ac.at/linuxcommand.org/man_pages/cdecl1.html
A: This article explains a relatively simple 7 rules which will let you read any C declaration, if you find yourself wanting or needing to do so manually: http://www.ericgiguere.com/articles/reading-c-declarations.html
*
*Find the identifier. This is your starting point. On a piece of paper, write "declare identifier as".
*Look to the right. If there is nothing there, or there is a right parenthesis ")", goto step 4.
*You are now positioned either on an array (left bracket) or function (left parenthesis) descriptor. There may be a sequence of these, ending either with an unmatched right parenthesis or the end of the declarator (a semicolon or a "=" for initialization). For each such descriptor, reading from left to right:
*
*if an empty array "[]", write "array of"
*if an array with a size, write "array size of"
*if a function "()", write "function returning"
Stop at the unmatched parenthesis or the end of the declarator, whichever comes first.
*Return to the starting position and look to the left. If there is nothing there, or there is a left parenthesis "(", goto step 6.
*You are now positioned on a pointer descriptor, "*". There may be a sequence of these to the left, ending either with an unmatched left parenthesis "(" or the start of the declarator. Reading from right to left, for each pointer descriptor write "pointer to". Stop at the unmatched parenthesis or the start of the declarator, whichever is first.
*At this point you have either a parenthesized expression or the complete declarator. If you have a parenthesized expression, consider it as your new starting point and return to step 2.
*Write down the type specifier. Stop.
If you're fine with a tool, then I second the suggestion to use the program cdecl: http://gd.tuwien.ac.at/linuxcommand.org/man_pages/cdecl1.html
A: Back when I was doing C, I made use of a program called "cdecl". It appears that it's in Ubuntu Linux in the cutils or cdecl package, and it's probably available elsewhere.
A: cdecl offers a command line interface so let's give it a try:
cdecl> explain int ***c[][]
declare c as array of array of pointer to pointer to pointer to int
another example
explain int (*IMP)(ID,SEL)
declare IMP as pointer to function (ID, SEL) returning int
However there is a whole chapter about that in the book "C Deep Secrets", named "Unscrambling declarations in C.
A: I generally use what is sometimes called the 'right hand clockwise rule'.
It goes like this:
*
*Start from the identifier.
*Go to the immediate right of it.
*Then move clockwise and come to the left hand side.
*Move clockwise and come to the right side.
*Do this as long as the declaration has not been parsed fully.
There's an additional meta-rule that has to be taken care of:
*
*If there are parentheses, complete each level of parentheses before moving out.
Here, 'going' and 'moving' somewhere means reading the symbol there. The rules for that are:
*
** - pointer to
*() - function returning
*(int, int) - function taking two ints and returning
*int, char, etc. - int, char, etc.
*[] - array of
*[10] - array of ten
*etc.
So, for example, int* (*xyz[10])(int*, char) is read as:
xyz is an
array of ten
pointer to
function taking an int* and a char and returning
an int*
A: Just came across an illuminating section in "The Development of the C Language":
For each object of such a composed type, there was already a way to mention the underlying object: index the array, call the function, use the indirection operator on the pointer. Analogical reasoning led to a declaration syntax for names mirroring that of the expression syntax in which the names typically appear. Thus,
int i, *pi, **ppi;
declare an integer, a pointer to an integer, a pointer to a pointer to an integer. The syntax of these declarations reflects the observation that i, *pi, and **ppi all yield an int type when used in an expression. Similarly,
int f(), *f(), (*f)();
declare a function returning an integer, a function returning a pointer to an integer, a pointer to a function returning an integer;
int *api[10], (*pai)[10];
declare an array of pointers to integers, and a pointer to an array of integers. In all these cases the declaration of a variable resembles its usage in an expression whose type is the one named at the head of the declaration.
A: There's also a Web-based version of cdecl which is pretty slick.
A: Common readability problems include function pointers and the fact that arrays are really pointers, and that multidimensional arrays are really single dimension arrays (which are really pointers). Hope that helps some.
In any case, whenever you do understand the declarations, maybe you can figure out a way to simplify them to make them more readable for the next guy.
A: Automated solution is cdecl.
In general, you declare a variable the way you use it. For example, you dereference a pointer p as in:
char c = * p
you declare it in a similar looking way:
char * p;
Same goes for hairy function pointers. Let's declare f to be good old "pointer to function returning pointer to int," and an external declaration just to be funny. It's a pointer to a function, so we start with:
extern * f();
It returns a pointer to an int, so somewhere in front there there's
extern int * * f(); // XXX not quite yet
Now which is the correct associativity? I can never remember, so use some parenthesis.
extern (int *)(* f)();
Declare it the way you use it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
}
|
Q: What happens to your time slice if you get pre-empted in vxWorks? If you have round robin enabled in Vxworks and your task gets preempted by a higher priority task, what happens to the remaining time slice?
A: Your task will resume execution and finish the remainder of the time slice.
Note that you will have some jitter that occurs for one time tick, since time slicing has a granularity of 1 clock tick.
For example:
You have round robin enabled with a 10 clock tick time slice. One clock tick is 10 ms. You expect 100 ms per time slice.
You get pre-empted at 5 ms (the middle of your 1st tick). You should run for 95ms more, but VxWorks considers that you still have 10 ticks to go.
If the task gets the cpu back at 11ms, you will execute 99ms more.
If the task gets the cpu back at 19ms, you will execute 91ms more.
Every time you get pre-empted, your task might execute +/- 1 tick in absolute time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What is Microsoft SharePoint? I have heard that Microsoft SharePoint was used by many companies. Could someone tell me briefly what is SharePoint and why is it popular?
A: Previous answers describe what sharepoint is, but don't do a good job describing why it's popular. Yes, it gives you all that neat doc-management stuff out of the box. Yes, it integrates tightly with Office.
The OOB features are 1/10th of the whole story. Sharepoint exposes a comprehensive .Net object model that lets you customize the thing to your hearts content. People are coding amazing things with MOSS 2007. With the object model, you can build and customize sites via code, in response to external events. You can write custom "web-parts" (controls hosted on special pages) that consume both internal (sharepoint) and external data.
Check out Sharepoint Blogs to see what people are doing with it.
A: Very good points so far but I'll try my best to add something. :)
SharePoint is not just 2 technologies. It is a set of products and technologies brought together by Microsoft into one immense product that comes in 2 flavors. The 2 flavors are Windows SharePoint Services (WSS) and Microsoft Office SharePoint Server (MOSS). MOSS does come in standard and enterprise.
[Some of the technologies used in SharePoint: Windows Workflow Foundation, ASP.NET, Web Parts, XML (included XPath, XSLT, etc), SQL, Web Services - to name a few I can think of off the top of my head]
No matter the version you choose, SharePoint allows for web-based capabilities to allow users to create, organize, distribute, and maintain information. Because of this, the most common uses for SharePoint sites are intranets and project/team sites.
SharePoint also has incredible possibilities as an application platform. Looking at the web part and workflow pieces alone you can begin to realize the potential. For example, automation of authorization processes within an organization can quickly be developed without any code using SharePoint Designer. (FYI: more complex workflows would require Visual Studio but many simple workflows can be designed using the point and click functionality of SharePoint Designer)
While MOSS only extends upon the WSS, it does add a large amount of functionality that can be very important and useful to a business. Some of the more important features available in MOSS and not in WSS are: records management, document retention and auditing policies, browser based forms (InfoPath forms without installing InfoPath on client machine), and some of the business intelligence capabilities. Amazingly we're seeing interest in the social networking features of MOSS too. (easy to read list of features not in WSS that MOSS has)
Why is SharePoint used? I was doing some research not to long ago on this exact subject and I found a research study that cited 5 key benefits:
*
*Ease of information access
*Streamlined internal communication
*Increased end-user productivity
*Optimized document management practices
*IT time savings
Sorry if that turned into a bit of a ramble.
A: It's a collaboration website. All of the members on a team can update a single calendar and upload shared documents to a single repository.
A: What is SharePoint?
The latest version of Microsoft SharePoint software is really two different products:
*
*Windows SharePoint Services is a free download for Windows Server. In the latest version, known as WSS v3, collaborative web sites templates include basic blog and wiki services along with list templates for Image Libraries, Document Libraries, Contact lists, Calendars, Tasks and much more.
*Microsoft Office SharePoint Server 2007 or MOSS for short is built on Windows SharePoint Services. As a member of the Office Server product platform, it leverages the Microsoft Office client software to provide content on the web. Integration with Word, PowerPoint, Excel, Access and InfoPath provide rich web content from familiar content creation tools.
Why is it so popular
File Sharing
SharePoint originally became popular because it was an easy way to share documents on the web. Many organizations that adopted SharePoint in the 2003 versions capitalized on the ability to upload documents to Document Libaries and share those documents with others.
Company Extranets
One great example of this web based sharing, is a company extranet where users are not all in one location or authentication domain. Using form based authentication, accounts can be created for people across physical and company boundaries. By allowing one place for shared documents around a task rather than a corporate entity, SharePoint goes way beyond the common file share.
Content Management
There are plenty of other Content Management Systems, but MOSS incorporated the functionality of the previously name Microsoft Content Management System which itself often cost more than MOSS alone.
Search Search is greatly improved in SharePoint 2007 technologies. Search results are security trimmed, relevant and performant unlike the previous 2003 version. Bad search in SharePoint 2003 products lead to a lot of dissatisfaction with the product.
A: I think in this case Wikipedia have it right
Windows SharePoint Services (WSS) is the basic part of Microsoft SharePoint, offering collaboration and document management functionality by means of web portals, by providing a centralized repository for shared documents, as well as browser-based management and administration of them. It allows creation of Document libraries, which are collections of files that can be shared for collaborative editing. SharePoint provides access control and revision control for documents in a library.
In a nutshell Sharepoint is all about corporative management and collaboration features. Your company have a Windows 2003 server? Here you go. WSS 3.0 is here up and running.
A: SharePoint is the reason I'm considering taking advantage of a suicide booth.
In all seriousness, the rest of the answers are spot on. The differences between WSS 3.0 and MOSS 2007 commonly trip people up ("why pay for MOSS when WSS is free?" for example). SharePoint is a very complex and rich product that is integrated into other Microsoft applications, like Project Server 2007 and Team Foundation Server.
Why should you care about it? It depends. There are quite a few opportunities out there for experienced SharePoint developers and administrators. It can very quickly become the singular focus of your career if you decide to put a lot of effort into learning it.
A: Microsoft Office Sharepoint Server (MOSS) is a combination of two previous products, Microsoft SharePoint and Microsoft Content Management System.
It has a large number of features out of the box that are very desirable for any single system, including hosting files with customisable metadata. Page and file publishing that is enabled for end users, excellent search... the list goes on.
Essentially it is designed to enhance and organisations collaboration activities across the entire enterprise, leveraging the organistations existing Office application to create an enterprise system.
A:
what is sharepoint
Sharepoint is really two different technologies: Windows Sharepoint Services (WSS) and Microsoft Office Sharepoint Server (MOSS). WSS is free and it comes with Windows Server 2003. MOSS isn't free.
WSS provides lots of out of the box functionality for managing documents and projects online. It manages documents in "document libraries." These are folders with permissions and different views of your documents. Projects, tasks, issues, or any tabular data, is managed in lists. Lists are similar to document libraries. They have permissions and views as well. It provides some simple search as well.
MOSS provides a better search (it's supposed to at least). It also has more publishing capabilities (WSS doesn't). And you have more control over page layouts. It's meant more for internet style sites while WSS is more for intranet sites.
and why is it popular?
WSS is popular partly because its free and partly because it just does so much out of the box. You can solve many common office requests with WSS. Stuff like issue trackers, project management and document management are trivial in WSS. That said, its a jack of all trades - good at many, master of none.
MOSS is probably less popular because its not free and having used it for a year, I don't see as much value in it as WSS. Search isn't that great. It does do a good job of creating a company directory.
A: I've been working with SharePoint since v.1 and I could tell you that SharePoint is a:
*
*Document management server
*Web content management server
*Portal solution
*Search engine
*List-based repository
*Collaboration site
*Replacement for file shares
*etc etc...
...but if I have to summarize in one sentence what SharePoint is I would say:
Sharepoint is Microsoft's Web OS.
That's real the secret of its success. Many people imagined the Web OS as something like these. A Web OS is not something that is meant to look like a desktop OS. A Web OS should be a WEB PLATFORM in which all sort of applications can be built on and users are able to collaborate with.
Think of SharePoint as the 2.0-era version of Windows :-)
A: Sharepoint, MS OFFICE proxy circa 2003...
remember when you emailed a copy of that word doc out to the whole company, that's what sharepoint is for, but apparently you missed the introductory gotomeeting training course.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "94"
}
|
Q: Diagnosing Deadlocks in Win32 Program What are the steps and techniques to debug an apparent hang due to a deadlock in a Win32 production process. I heard that WinDbg can be used for this purpose but could you please provide clear hints on how this can be accomplished?
A: This post should get you started on the various options..Check the posts tagged with Debugging..
Another useful article on debugging deadlocks..
A: Debugging a true deadlock is actually kind of easy, if you have access to the source and a memory dump (or live debugging session).
All you do is look at the threads, and find the ones that are waiting on some kind of shared resource (for example hung waiting in WaitForSingleObject). Generally speaking from there it is a matter of figuring out which two or more threads have locked each other up, and then you just have to figure out which one broke the lock heirarchy.
If you can't easily figure out which threads are locked up, use the method shown in this post here to trace the lock chain for each thread. When you get into a loop, the threads in the loop are the ones that are deadlocked.
A: If you are very lazy, you can install Application Verifier, then add you module and select just "locks" from the basic test.
then you can run your application under any debugger.
if a critical section deadlock happens you with find the reason right away.
A: What language/IDE are you using?
In .Net you can view the threads of an application: Debug->Windows->Threads or Ctrl+Alt+H
A: The best thing is to start by adding logging statements. Generally I would recommend only around the shared resources that are deadlocking but also adding them in general might point to situations or areas of code you weren't expecting. The much publicized stackoverflow.com database issue actually turned out to be log4net! The stackoverflow team never suspected log4net, and only by examining logging (ironically) showed this. I would initially forgo any complicated tools e.g., WinDgb since using them is not very intuitive IMHO.
A: Debugging deadlocks can be tricky. I usually do some kind of logging and see where the log stops. I either log to a file or to the debug console using OutputDebugString().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives I am getting an 403 access forbidden when attempting to open a page under a vhost where the document root is sitting on a different drive than where apache is sitting. I installed using the apachefriends release. This is my httpd-vhosts.conf file:
NameVirtualHost 127.0.0.1
<VirtualHost 127.0.0.1>
ServerName foo.localhost
DocumentRoot "C:/xampp/htdocs/foo/public"
</VirtualHost>
<VirtualHost 127.0.0.1>
ServerName bar.localhost
DocumentRoot "F:/bar/public"
</VirtualHost>
When opening bar.localhost in my browser, Apache is giving me 403 Access Forbidden. I tried setting lots of different access rights, even full rights to everyone, but nothing I tried helped.
Edit: Thanks! For future reference, add 'Options indexes' within to show directory indexes.
A: You did not need
Options Indexes FollowSymLinks MultiViews Includes ExecCGI
AllowOverride All
Order Allow,Deny
Allow from all
Require all granted
the only thing what you need is...
Require all granted
...inside the directory section.
See Apache 2.4 upgrading side:
http://httpd.apache.org/docs/2.4/upgrading.html
A: Somewhere, you need to tell Apache that people are allowed to see contents of this directory.
<Directory "F:/bar/public">
Order Allow,Deny
Allow from All
# Any other directory-specific stuff
</Directory>
More info
A: For Apache 2.4.2: I was getting 403: Forbidden continuously when I was trying to access WAMP on my Windows 7 desktop from my iPhone on WiFi. On one blog, I found the solution - add Require all granted after Allow all in the <Directory> section. So this is how my <Directory> section looks like inside <VirtualHost>
<Directory "C:/wamp/www">
Options Indexes FollowSymLinks MultiViews Includes ExecCGI
AllowOverride All
Order Allow,Deny
Allow from all
Require all granted
</Directory>
A: I have fixed it with removing below code from
C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf file
<VirtualHost *:80>
ServerAdmin webmaster@dummy-host.example.com
DocumentRoot "c:/Apache24/docs/dummy-host.example.com"
ServerName dummy-host.example.com
ServerAlias www.dummy-host.example.com
ErrorLog "logs/dummy-host.example.com-error.log"
CustomLog "logs/dummy-host.example.com-access.log" common
</VirtualHost>
<VirtualHost *:80>
ServerAdmin webmaster@dummy-host2.example.com
DocumentRoot "c:/Apache24/docs/dummy-host2.example.com"
ServerName dummy-host2.example.com
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>
And added
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot "c:/wamp/www"
ServerName localhost
ErrorLog "logs/localhost-error.log"
CustomLog "logs/localhost-access.log" common
</VirtualHost>
And it has worked like charm
A: Solved 403: Forbidden when visiting localhost. Using ports 80,443,3308 (the later to handle conflict with MySQL Server installation)
Windows 10, XAMPP 7.4.1, Apache 2.4.x My web files are in a separate folder.
httpd.conf - look for these lines and set it up where you have your files, mine is web folder.
DocumentRoot "C:/web"
<Directory "C:/web">
Changed these 2 lines.
<VirtualHost *:80>
ServerAdmin webmaster@localhost.com
DocumentRoot "C:/web/project1"
ServerName project1.localhost
<Directory "C:/web/project1">
Order allow,deny
allow from all
</Directory>
</VirtualHost>
to this
<VirtualHost *:80>
ServerAdmin webmaster@localhost.com
DocumentRoot "C:/web/project1"
ServerName project1.localhost
<Directory "C:/web/project1">
Require all granted
</Directory>
</VirtualHost>
Add your details in your hosts file
C:\Windows\System32\drivers\etc\hosts file
127.0.0.1 localhost
127.0.0.1 project1.localhost
Stop start XAMPP, and click Apache admin (or localhost) and the wonderful XAMPP dashboard now displays! And visit your project at project1.localhost
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "57"
}
|
Q: C#: Why does Settings PropertyValues have 0 items? Assuming there are 5 items in the settings file (MySetting1 to MySetting5), why does PropertyValues have 0 items while Properties has the correct number?
Console.WriteLine( Properties.Settings.Default.PropertyValues.Count); // Displays 0
Console.WriteLine( Properties.Settings.Default.Properties.Count); // Displays 5
A: It appears that PropertyValues refers to the number of PropertyValues that have been set. The default values you specify aren't considered set and won't be stored to the user config if you sall Save().
Console.WriteLine(Settings.Default.PropertyValues.Count.ToString());
Console.ReadLine();
Settings.Default.Setting = "abc";
Console.WriteLine(Settings.Default.PropertyValues.Count.ToString());
Console.ReadLine();
results in the following output:
0
1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Benefits of using short-circuit evaluation boolean a = false, b = true;
if ( a && b ) { ... };
In most languages, b will not get evaluated because a is false so a && b cannot be true. My question is, wouldn't short circuiting be slower in terms of architecture? In a pipeline, do you just stall while waiting to get the result of a to determine if b should be evaluated or not? Would it be better to do nested ifs instead? Does that even help?
Also, does anyone know what short-circuit evaluation is typically called? This question arose after I found out that my programming friend had never heard of short-circuit evaluation and stated that it is not common, nor found in many languages, and is inefficient in pipeline. I am not certain about the last one, so asking you folks!
Okay, I think a different example to perhaps explain where my friend might be coming from. He believes that since evaluating a statement like the following in parallel:
(a) if ( ( a != null ) && ( a.equals(b) ) ) { ... }
will crash the system, an architecture that doesn't have short-circuiting (and thereby not allowing statements like the above) would be faster in processing statements like these:
(b) if ( ( a == 4 ) && ( b == 5 ) )
since if it couldn't do (a) in parallel, it can't do (b) in parallel. In this case, a language that allows short-circuiting is slower than one that does not.
I don't know if that's true or not.
Thanks
A: I honestly wouldn't worry about it. Testing a boolean is really fast. Short-circuiting only gets interesting / useful when the second expression has side effects:
if ( ConfirmAction() && DestroyAllData() )
Reboot();
...or depends on the first test:
if ( myDodgyVar != null && myDodgyVar.IsActive() )
DoSomethingWith(myDodgyVar);
A: Languages supporting short-circuiting:
Ada, Eiffel, ALGOL 68, C1, C++, C#, Java, R, Erlang, Standard ML, Javascript, MATLAB, Lisp, Lua, Scheme, OCaml, Haskell, Pascal,Perl, Ruby, PHP, Python, Smalltalk, Visual Basic .NET
Taken from Short-circuit evaluation
A: VB.Net has a different syntax depending on whether or not you want it to short circuit or not. Because of legacy reasons, the default behaviour is to not short circuit. The syntax is as follows
Non Short Circuit
IF A And B THEN
...
END IF
Short Circuit
IF A AndAlso B THEN
...
END IF
You can use Or / OrElse if you want to short circuit an OR statement. Which is really nice in situations like the following
If MyObj IsNot Nothing AndAlso MyObj.Value < SomeValue Then
....
End If
Personally while I understand that short circuiting can speed things up, it's definitely not something that's obvious from just looking at the code. I could see an inexperienced developer getting confused by the behaviour. It even seems like something that could happen or not depending on compiler flags for level of optimization. I like how VB is verbose about which behaviour you actually want to accomplish.
A: First, your friend is wrong. Short-circuit evaluation (aka minimal evaluation) is available in most languages and is better than nested ifs for parallel languages (in which case the first of the conditions that returns will cause execution to continue)
In any case, even in a straightforward non-parallel language I don't see how nested ifs would be faster as execution would block until the first condition is evaluated.
A: Short circuit evaluation is translated into branches in assembly language in the same way if statements are (branches are basically a goto), which means it is not going to be any slower than if statements.
Branches don't typically stall the pipeline, but the processor will guess whether the branch is taken or not, and if the processor is wrong it will have to flush everything that has happened since it made the wrong guess from the pipeline.
Short circuit evaluation is also the most common name for it, and is found in most languages in some form or another.
A: Short-circuiting boolean expressions are exactly equivalent to some set of nested ifs, so are as efficient as that would be.
If b doesn't have side-effects, it can still be executed in parallel with a (for any value of "in parallel", including pipelining).
If b has side effects which the CPU architecture can't cancel when branch prediction fails then yes, this might require delays which wouldn't be there if both sides were always evaluated. So it's something to look at if you do ever find that short-circuiting operators are creating a performance bottleneck in your code, but not worth worrying about otherwise.
But short-circuiting is used for control flow as much as to save unnecessary work. It's common among languages I've used, for example the Perl idiom:
open($filename) or die("couldn't open file");
the shell idiom:
do_something || echo "that failed"
or the C/C++/Java/etc idiom:
if ((obj != 0) && (obj->ready)) { do_something; } // not -> in Java of course.
In all these cases you need short-circuiting, so that the RHS is only evaluated if the LHS dictates that it should be. In such cases there's no point comparing performance with alternative code that's wrong!
A: How can a nested if not stall? Actually if a and b are both variables and not expressions with side effects, they can be loaded in parallel by a good compiler. There's no benefit to using more ifs except increasing your line count. Really, this would be the worst kind of second guessing a compiler.
It's called short-circuit evaluation.
A: A useful short circuit I use is something like this:
if (a != null && a.equals(somevalue)) {
... do something.
}
This is, in my opinion very readable, and functions quite well. Generally, I try too avoid to much nesting because it leads to ugly code.
All my opinion though.
A: Most languages do short-circuit evaluation of boolean expressions. I have always heard it referred to as short-circuit evaluation.
The example in the question is a pretty simplistic example that doesn't really provide much of a performance benefit. The performance benefit comes when the expressions are complex to evaluate.
As an example of when this would be good imagine a game program that has something like:
if (someObject.isActive() && someOtherObject.isActive() && CollisionDetection.collides(someObject, someOtherObject) {
doSomething();
}
In this case the collision detection is far more expensive than the active checks. There would be a significant performance boost if there were lots of inactive objects in the system.
A: Short-circuit, or minimal evaluation is just syntactic sugar for nested ifs.
To assume it is inefficient, or causes stalls is a case of premature optimization.
At this point, most compilers are intelligent enough to correctly interpret and optimize these statements. Using these statements can greatly reduce nesting, and therefore improve code readability, which should be your number one goal.
A: Regarding whether or not short-circuiting is efficient, pipelining is unlikely to have much of an impact on performance. In situations where it could have an impact, there's nothing to stop the compiler from testing multiple conditions in parallel so long as these tests doesn't have side-effects. Plus, modern CPUs have several mechanisms useful for improving the pipeline performance of branchy code.
Nested ifs will have the same effect as short-circuiting &&.
'Short-circuit evaluation' is the most common name for it, and your friend is wrong about it being uncommon; it's very common.
A: Depending upon the context, it can also be called "Guarding".
And I've seen it in just about every language I've worked in - which pushes close to a dozen.
A: I don't know anything about pipelining, but short-circuit evaluation is a common feature of many languages (and that's also the name I know it by). In C, && and the other operators define a sequence point just like the ; operator does, so I don't see how short-circuit evaluation is any less efficient than just using multiple statements.
A: i've only heard of it as short circuit. in a pipeline doesnt the next op that goes in depend on the outcome of the if statement? if that is the case this would more optimized so it wouldnt have to test two values every time.
A: A single thread is sequential so if you have two ifs the first will of course be evaluated before the second, so I can't see a difference on that. I use the conditional-AND operator (which is what && is called afaik) much more than nested ifs. If I want to check something that may take a while to evaluate, I do the simpler test first then the harder one after the conditional and.
a = obj.somethingQuickToTest() && obj.somethingSlowToTest();
doesn't seem to be any different than
a = false;
if(obj.somethingQuickToTest())
a = obj.somethingSlowToTest();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Autocomplete Textbox on Gridview editing How do you implement autocomplete on ASP.Net Gridview? Can anyone point me where to go to achieve this? I'm willing to use non-.Net ajax controls if that what it takes.
A: You will need to utilise an AJAX framework (JQuery is one i often recommend) which will provide the functionality to display the drop down box. You will then need to create a separate page (or web service) to return all the possible values to display in the auto-complete drop down.
To save on performance i recommend only initiating the auto-complete once the user has typed in 2 or 3 letters. These can then be passed by the JavaScript to the backed to proivde values to show in the drop down list.
The back end can communicate with the JavaScript using either simple CSV, JSON, XML Web service etc. See http://www.pengoworks.com/workshop/jquery/autocomplete.htm for examples.
A: The AJAX Control Toolkit provides an autocomplete but requires a web service to work. You could always write your own asmx if there isn't one you can use.
Otherwise, there are all sorts of JS and jQuery examples:
http://www.javascript-examples.com/autocomplete-demo/
A: Scriptaculous has a nice autocomplete component. It is built on prototype.js.
I've used it to display an autocomplete list with formatted text and images etc. In that sense I think it is more flexible than the ASP.NET AJAX implementation.
Documentation http://wiki.github.com/madrobby/scriptaculous/ajax-autocompleter
Download http://script.aculo.us/downloads
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique *while preserving order*? For example:
>>> x = [1, 1, 2, 'a', 'a', 3]
>>> unique(x)
[1, 2, 'a', 3]
Assume list elements are hashable.
Clarification: The result should keep the first duplicate in the list. For example, [1, 2, 3, 2, 3, 1] becomes [1, 2, 3].
A: Obligatory generator-based variation:
def unique(seq):
seen = set()
for x in seq:
if x not in seen:
seen.add(x)
yield x
A: This may be the simplest way:
list(OrderedDict.fromkeys(iterable))
As of Python 3.5, OrderedDict is now implemented in C, so this was is now the shortest, cleanest, and fastest.
A: Taken from http://www.peterbe.com/plog/uniqifiers-benchmark
def f5(seq, idfun=None):
# order preserving
if idfun is None:
def idfun(x): return x
seen = {}
result = []
for item in seq:
marker = idfun(item)
# in old Python versions:
# if seen.has_key(marker)
# but in new ones:
if marker in seen: continue
seen[marker] = 1
result.append(item)
return result
A: One-liner:
new_list = reduce(lambda x,y: x+[y][:1-int(y in x)], my_list, [])
A: An in-place one-liner for this:
>>> x = [1, 1, 2, 'a', 'a', 3]
>>> [ item for pos,item in enumerate(x) if x.index(item)==pos ]
[1, 2, 'a', 3]
A: This is the fastest one, comparing all the stuff from this lengthy discussion and the other answers given here, refering to this benchmark. It's another 25% faster than the fastest function from the discussion, f8. Thanks to David Kirby for the idea.
def uniquify(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if x not in seen and not seen_add(x)]
Some time comparison:
$ python uniqifiers_benchmark.py
* f8_original 3.76
* uniquify 3.0
* terhorst 5.44
* terhorst_localref 4.08
* del_dups 4.76
A: def unique(items):
found = set()
keep = []
for item in items:
if item not in found:
found.add(item)
keep.append(item)
return keep
print unique([1, 1, 2, 'a', 'a', 3])
A: You can actually do something really cool in Python to solve this. You can create a list comprehension that would reference itself as it is being built. As follows:
# remove duplicates...
def unique(my_list):
return [x for x in my_list if x not in locals()['_[1]'].__self__]
Edit: I removed the "self", and it works on Mac OS X, Python 2.5.1.
The _[1] is Python's "secret" reference to the new list. The above, of course, is a little messy, but you could adapt it fit your needs as necessary. For example, you can actually write a function that returns a reference to the comprehension; it would look more like:
return [x for x in my_list if x not in this_list()]
A: Using:
lst = [8, 8, 9, 9, 7, 15, 15, 2, 20, 13, 2, 24, 6, 11, 7, 12, 4, 10, 18, 13, 23, 11, 3, 11, 12, 10, 4, 5, 4, 22, 6, 3, 19, 14, 21, 11, 1, 5, 14, 8, 0, 1, 16, 5, 10, 13, 17, 1, 16, 17, 12, 6, 10, 0, 3, 9, 9, 3, 7, 7, 6, 6, 7, 5, 14, 18, 12, 19, 2, 8, 9, 0, 8, 4, 5]
And using the timeit module:
$ python -m timeit -s 'import uniquetest' 'uniquetest.etchasketch(uniquetest.lst)'
And so on for the various other functions (which I named after their posters), I have the following results (on my first generation Intel MacBook Pro):
Allen: 14.6 µs per loop [1]
Terhorst: 26.6 µs per loop
Tarle: 44.7 µs per loop
ctcherry: 44.8 µs per loop
Etchasketch 1 (short): 64.6 µs per loop
Schinckel: 65.0 µs per loop
Etchasketch 2: 71.6 µs per loop
Little: 89.4 µs per loop
Tyler: 179.0 µs per loop
[1] Note that Allen modifies the list in place – I believe this has skewed the time, in that the timeit module runs the code 100000 times and 99999 of them are with the dupe-less list.
Summary: Straight-forward implementation with sets wins over confusing one-liners :-)
A: Do the duplicates necessarily need to be in the list in the first place? There's no overhead as far as looking the elements up, but there is a little bit more overhead in adding elements (though the overhead should be O(1) ).
>>> x = []
>>> y = set()
>>> def add_to_x(val):
... if val not in y:
... x.append(val)
... y.add(val)
... print x
... print y
...
>>> add_to_x(1)
[1]
set([1])
>>> add_to_x(1)
[1]
set([1])
>>> add_to_x(1)
[1]
set([1])
>>>
A: Remove duplicates and preserve order:
This is a fast 2-liner that leverages built-in functionality of list comprehensions and dicts.
x = [1, 1, 2, 'a', 'a', 3]
tmpUniq = {} # temp variable used below
results = [tmpUniq.setdefault(i,i) for i in x if i not in tmpUniq]
print results
[1, 2, 'a', 3]
The dict.setdefaults() function returns the value as well as adding it to the temp dict directly in the list comprehension. Using the built-in functions and the hashes of the dict will work to maximize efficiency for the process.
A: Update: on Python3.7+:
>>> list(dict.fromkeys('abracadabra'))
['a', 'b', 'r', 'c', 'd']
old answer:
Here is the fastest solution so far (for the following input):
def del_dups(seq):
seen = {}
pos = 0
for item in seq:
if item not in seen:
seen[item] = True
seq[pos] = item
pos += 1
del seq[pos:]
lst = [8, 8, 9, 9, 7, 15, 15, 2, 20, 13, 2, 24, 6, 11, 7, 12, 4, 10, 18,
13, 23, 11, 3, 11, 12, 10, 4, 5, 4, 22, 6, 3, 19, 14, 21, 11, 1,
5, 14, 8, 0, 1, 16, 5, 10, 13, 17, 1, 16, 17, 12, 6, 10, 0, 3, 9,
9, 3, 7, 7, 6, 6, 7, 5, 14, 18, 12, 19, 2, 8, 9, 0, 8, 4, 5]
del_dups(lst)
print(lst)
# -> [8, 9, 7, 15, 2, 20, 13, 24, 6, 11, 12, 4, 10, 18, 23, 3, 5, 22, 19, 14,
# 21, 1, 0, 16, 17]
Dictionary lookup is slightly faster then the set's one in Python 3.
A: What's going to be fastest depends on what percentage of your list is duplicates. If it's nearly all duplicates, with few unique items, creating a new list will probably be faster. If it's mostly unique items, removing them from the original list (or a copy) will be faster.
Here's one for modifying the list in place:
def unique(items):
seen = set()
for i in xrange(len(items)-1, -1, -1):
it = items[i]
if it in seen:
del items[i]
else:
seen.add(it)
Iterating backwards over the indices ensures that removing items doesn't affect the iteration.
A: This is the fastest in-place method I've found (assuming a large proportion of duplicates):
def unique(l):
s = set(); n = 0
for x in l:
if x not in s: s.add(x); l[n] = x; n += 1
del l[n:]
This is 10% faster than Allen's implementation, on which it is based (timed with timeit.repeat, JIT compiled by psyco). It keeps the first instance of any duplicate.
repton-infinity: I'd be interested if you could confirm my timings.
A: O(n) if dict is hash, O(nlogn) if dict is tree, and simple, fixed. Thanks to Matthew for the suggestion. Sorry I don't know the underlying types.
def unique(x):
output = []
y = {}
for item in x:
y[item] = ""
for item in x:
if item in y:
output.append(item)
return output
A: has_key in python is O(1). Insertion and retrieval from a hash is also O(1). Loops through n items twice, so O(n).
def unique(list):
s = {}
output = []
for x in list:
count = 1
if(s.has_key(x)):
count = s[x] + 1
s[x] = count
for x in list:
count = s[x]
if(count > 0):
s[x] = 0
output.append(x)
return output
A: There are some great, efficient solutions here. However, for anyone not concerned with the absolute most efficient O(n) solution, I'd go with the simple one-liner O(n^2*log(n)) solution:
def unique(xs):
return sorted(set(xs), key=lambda x: xs.index(x))
or the more efficient two-liner O(n*log(n)) solution:
def unique(xs):
positions = dict((e,pos) for pos,e in reversed(list(enumerate(xs))))
return sorted(set(xs), key=lambda x: positions[x])
A: Here are two recipes from the itertools documentation:
def unique_everseen(iterable, key=None):
"List unique elements, preserving order. Remember all elements ever seen."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
seen = set()
seen_add = seen.add
if key is None:
for element in ifilterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element
def unique_justseen(iterable, key=None):
"List unique elements, preserving order. Remember only the element just seen."
# unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
# unique_justseen('ABBCcAD', str.lower) --> A B C A D
return imap(next, imap(itemgetter(1), groupby(iterable, key)))
A: I have no experience with python, but an algorithm would be to sort the list, then remove duplicates (by comparing to previous items in the list), and finally find the position in the new list by comparing with the old list.
Longer answer: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
A: >>> def unique(list):
... y = []
... for x in list:
... if x not in y:
... y.append(x)
... return y
A: If you take out the empty list from the call to set() in Terhost's answer, you get a little speed boost.
Change:
found = set([])
to:
found = set()
However, you don't need the set at all.
def unique(items):
keep = []
for item in items:
if item not in keep:
keep.append(item)
return keep
Using timeit I got these results:
with set([]) -- 4.97210427363
with set() -- 4.65712377445
with no set -- 3.44865284975
A: x = [] # Your list of items that includes Duplicates
# Assuming that your list contains items of only immutable data types
dict_x = {}
dict_x = {item : item for i, item in enumerate(x) if item not in dict_x.keys()}
# Average t.c. = O(n)* O(1) ; furthermore the dict comphrehension and generator like behaviour of enumerate adds a certain efficiency and pythonic feel to it.
x = dict_x.keys() # if you want your output in list format
A: I haven't done any tests, but one possible algorithm might be to create a second list, and iterate through the first list. If an item is not in the second list, add it to the second list.
x = [1, 1, 2, 'a', 'a', 3]
y = []
for each in x:
if each not in y:
y.append(each)
A: One pass.
a = [1,1,'a','b','c','c']
new_list = []
prev = None
while 1:
try:
i = a.pop(0)
if i != prev:
new_list.append(i)
prev = i
except IndexError:
break
A: a=[1,2,3,4,5,7,7,8,8,9,9,3,45]
def unique(l):
ids={}
for item in l:
if not ids.has_key(item):
ids[item]=item
return ids.keys()
print a
print unique(a)
Inserting elements will take theta(n)
retrieving if element is exiting or not will take constant time
testing all the items will take also theta(n)
so we can see that this solution will take theta(n).
Bear in mind that dictionary in python implemented by hash table.
A: >>> x=[1,1,2,'a','a',3]
>>> y = [ _x for _x in x if not _x in locals()['_[1]'] ]
>>> y
[1, 2, 'a', 3]
"locals()['_[1]']" is the "secret name" of the list being created.
A: I don't know if this one is fast or not, but at least it is simple.
Simply, convert it first to a set and then again to a list
def unique(container):
return list(set(container))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
}
|
Q: CVS Checkout to a directory How do i check out a specific directory from CVS and omit the tree leading up to that directory?
EX.
Id like to checkout to this directory
C:/WebHost/MyWebApp/www
My CVS Project directory structure is
MyWebApp/Trunk/www
How do i omit the Trunk and MyWebApp directories?
A: CVS is 'tied' to the repository by files in the .CVS folder. Each folder is 'tied' individually.
This means you can just check out the full thing (or if you already have the full thing), then cut/paste the www directory out to somewhere else, and it will remain linked to the correct CVS location.
A: Use cvs -d/cvsroot checkout -d directory project/path/directory. The first -d can be omitted if you set the root with the environment. This is called "shortening the path" and can be avoided with the -N option to checkout.
A: [Oops, deleted some wrong crap.] yeah, co -d www is what you want.
You can also set up modules in the repository, which will let you check out just www as if it were a top-level directory, but you have to do it for every such directory.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Get Flex app's position on a web page? Is it possible to get the x,y coordinates of a Flex app within an HTML page? I know you can use ExternalInterface.ObjecID to get the "id attribute of the object tag in Internet Explorer, or the name attribute of the embed tag in Netscape" but I can't seem to get past that step. It seems like it should be possible to get a handle on that embed object. Any suggestions?
Thanks.
A: I think the easiest thing to do is to include some kind of JavaScript library on the HTML page, say jQuery, and use it's functions for determining the position and size of DOM nodes. I would do it more or less like this:
var jsCode : String = "function( id ) { return $('#' + id).offset(); }";
var offset : Object = ExternalInterface.call(jsCode, ExternalObject.objectID);
trace(offset.left, offset.top);
Notice that this is ActionScript code, but it runs JavaScript code through ExternalInterface. It uses jQuery and in particular its offset method that returns the left and top offset of a DOM node.
You could do without jQuery if you looked at how the offset method is implemented and included that code in place of the call to jQuery. That way you wouldn't need to load jQuery in the HTML and the Flex app would be self-contained. The reason I suggest to use a library like jQuery is that browsers do these things differently. I'm not sure if calculating offsets is very different from browser to browser, but it doesn't hurt to be insulated from browser differences.
The JavaScript in my example is an anonymous function so that the ID of the embed/object tag can be passed in to it as a parameter to ExternalInterface.call, but you could just use string concatenation if you want:
var jsCode : String = "$('#' +" + ExternalInterface.objectID + ").offset()";
var offset : Object = ExternalInterface.call(jsCode);
That would work too, I just think the first version is more elegant.
A: If you are trying just to measure where it's at within a page as the external user the only thing that pops into my mind is a Firefox extension called MeasureIt I've used it occasionally for various measuring on web pages.
Are you trying to do this programmatically from within the embedded page itself and if so which langauge?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does LINQ-to-SQL Support Composable Queries? Speaking as a non-C# savvy programmer, I'm curious as to the evaluation semantics of LINQ queries like the following:
var people = from p in Person
where p.age < 18
select p
var otherPeople = from p in people
where p.firstName equals "Daniel"
select p
Assuming that Person is an ADO entity which defines the age and firstName fields, what would this do from a database standpoint? Specifically, would the people query be run to produce an in-memory structure, which would then be queried by the otherPeople query? Or would the construction of otherPeople merely pull the data regarding the query from people and then produce a new database-peered query? So, if I iterated over both of these queries, how many SQL statements would be executed?
A: var people = from p in Person
where p.age < 18
select p
Translates to:
SELECT [t0].[PersonId], [t0].[Age], [t0].[FirstName]
FROM [dbo].[Person] AS [t0]
WHERE [t0].[Age] < @p0
where @p0 gets sent through as 18
var otherPeople = from p in people
where p.firstName equals "Daniel"
select p
Translates to:
SELECT [t0].[PersonId], [t0].[Age], [t0].[FirstName]
FROM [dbo].[Person] AS [t0]
WHERE [t0].[FirstName] = @p0
where @p0 gets sent through as "Daniel"
var morePeople = from p1 in people
from p2 in otherPeople
where p1.PersonId == p2.PersonId
select p1;
Translates to:
SELECT [t0].[PersonId], [t0].[Age], [t0].[FirstName]
FROM [dbo].[Person] AS [t0], [dbo].[Person] AS [t1]
WHERE ([t0].[PersonId] = [t1].[PersonId]) AND ([t0].[Age] < @p0) AND ([t1].[FirstName] = @p1)
where @p0 is 18, @p1 is "Daniel"
When in doubt, call the ToString() on your IQueryable or give a TextWriter to the DataContext's Log property.
A: Yes, the resulting query is composed. It includes the full where clause. Turn on SQL profiling and try it to see for yourself.
Linq does this through expression trees. The first linq statement produces an expression tree; it doesn't execute the query. The second linq statement builds on the expression tree created by the first. The statement is only executed when you enumerate the resulting collection.
A: They are composable. This is possible because LINQ queries are actually expressions (code as data), which LINQ providers like LINQ-to-SQL can evaluate and generate corresponding SQL.
Because LINQ queries are lazily evaluated (e.g. won't get executed until you iterate over the elements), the code you showed won't actually touch the database. Not until you iterate over otherPeople or people will SQL get generated and executed.
A: people and otherPeople contain objects of type IQueryable<Person>.
If you iterate over both, separatly, it will run two queries.
If you only iterate over otherPeople, it will run the expected query, with two where clauses.
If you do .ToList() on people and use the returned List<Person> in the second query instead of people, it becomes LINQ-to-Objects and no SQL is executed.
This behavior is referred to as deferred execution. Meaning no query is done until it is needed. Before execution they are just expression trees that get manipulated to formulate the final query.
A: Both these queries will be executes when you'll try to access final results. You can try to view original SQL generated from DataContext object properties.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Difference between Convert.ToDecimal(string) & Decimal.Parse(string) What is the difference in C# between Convert.ToDecimal(string) and Decimal.Parse(string)?
In what scenarios would you use one over the other?
What impact does it have on performance?
What other factors should I be taking into consideration when choosing between the two?
A: There is one important difference to keep in mind:
Convert.ToDecimal will return 0 if it is given a null string.
decimal.Parse will throw an ArgumentNullException if the string you want to parse is null.
A: From bytes.com:
The Convert class is designed to
convert a wide range of Types, so you
can convert more types to Decimal than
you can with Decimal.Parse, which can
only deal with String. On the other
hand Decimal.Parse allows you to
specify a NumberStyle.
Decimal and decimal are aliases and
are equal.
For Convert.ToDecimal(string),
Decimal.Parse is called internally.
Morten Wennevik [C# MVP]
Since Decimal.Parse is called internally by Convert.ToDecimal, if you have extreme performance requirements you might want to stick to Decimal.Parse, it will save a stack frame.
A: One common suggestion related to original topic - please use TryParse() as soon as you not really sure that input string parameter WILL be correct number format representation.
A: One factor that you might not have thought of is the Decimal.TryParse method. Both Convert.ToDecimal and Parse throw exceptions if they cannot convert the string to the proper decimal format. The TryParse method gives you a nice pattern for input validation.
decimal result;
if (decimal.TryParse("5.0", out result))
; // you have a valid decimal to do as you please, no exception.
else
; // uh-oh. error message time!
This pattern is very incredibly awesome for error-checking user input.
A: Major Difference between Convert.ToDecimal(string) and Decimal.Parse(string)
is that Convert handles Null whereas the other throws an exception
Note: It won't handle empty string.
A: Convert.ToDecimal apparently does not always return 0. In my linq statement
var query = from c in dc.DataContext.vw_WebOrders
select new CisStoreData()
{
Discount = Convert.ToDecimal(c.Discount)
};
Discount is still null after converting from a Decimal? that is null. However, outside a Linq statement, I do get a 0 for the same conversion. Frustrating and annoying.
A: Knowing that Convert.ToDecimal is the way to go in most cases because it handles NULL, it, however, does not handle empty string very well. So, the following function might help:
'object should be a string or a number
Function ConvertStringToDecimal(ByVal ValueToConvertToDecimal As Object) As Decimal
If String.IsNullOrEmpty(ValueToConvertToDecimal.ToString) = False Then
Return Convert.ToDecimal(ValueToConvertToDecimal)
Else
Return Convert.ToDecimal(0)
End If
End Function
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
}
|
Q: Functional Programming Architecture I'm familiar with object-oriented architecture, including use of design patterns and class diagrams for visualization, and I know of service-oriented architecture with its contracts and protocol bindings, but is there anything characteristic about a software architecture for a system written in a functional programming language?
I know that FP has been used for medium-size to large scale projects. Paul Graham wrote the first incarnation of Yahoo! Store in Common Lisp. Some lisp development systems are complex. Artifical intelligence and financial systems written in functional languages can get pretty big. They all have at least some kind of inherent architecture, though, I'm wondering if they have anything in common?
What does an architecture based on the evaluation of expressions look like? Are FP architectures more composable?
Update: Kyle reminded me that SICP is a good resource for this subject.
Update 2: I found a good post on the subject: How does functional programming affect the structure of your code?
A: The largest commonality you'll find in functional languages is using functions to store data. It's a bit like using accessor functions on an object without the object. Instead, the function is created in an environment where it has access to the data it needs. Now this function can be passed and used anywhere and still retain the ability to use the data.
Here's a very simple example. This isn't purely functional as it does change state, but it's common enough:
(define (make-counter)
(let ((count 0))
(lambda ()
(set! count (+ count 1))
count)))
(define x (make-counter))
(x) returns 1
(x) returns 2
...etc...
So we have a function, make-counter, that returns another function that has the state of the counter inside. We can call that newly created counter and observe the change inside.
This is how functional programs are structured. You have functions that take functions as arguments, you have functions that return functions with hidden state, etc. It's all a lot cleaner than managing memory yourself.
A: I printed out and looked over Design Patterns in Ocaml, and they use modules and functors (and objects) to recreate the normal design patterns we are used to. It's interesting, but I think they use objects too much to really see the benefit of functional languages. FP is very composable, part of it's nature. I guess my short answer is to use modules and functors.
My current project is pretty big, and we separate each module by files --implicit in ocaml. I've been hunting for a comprehensive resource as well that might have some alternative views or some thoughts on a really successful design that came out of a project.
A: The common thread in the "architecture" of projects that use functional languages is that they tend to be separated into layers of algebras rather than subsystems in the traditional systems architecture sense.
For great examples of such projects, check out XMonad, Yi, and HappS. If you examine how they are structured, you will find that they comprise layers of monadic structure with some combinator glue in between.
Also look at The Scala Experiment paper which outlines an architecture where a system is composed of components that abstract over their dependencies.
A: I have worked with some fairly large functional projects. They usually fall into two camps (at least, the ones I have used):
*
*Extreme scalability/reliability/concurrency. Transactional models can be built very tightly into the language. Concurrent ML is a great example of this, and projects that use it are very hard to get wrong when it comes to concurrency correctness.
*Parsing/modifying frameworks. Many of the design patterns that these frameworks are based on are incredibly easy to formulate/build/modify in functional languages. The visitor pattern is a great example of this.
A: Hopefully not too tangential, but probably interesting for anyone browsing the answers to this question is this presentation Design Patterns in Dynamic Programming by Peter Norvig.
A: I'm currently working on the book "Design and Architecture in Functional Programming". It describes many design patterns and approaches that are exist in pure FP world (primary language is Haskell), but not only. The book teaches you how to build big application from scratch with pure and impure state, multithreading, network, database, GUI, how to divide it into layers and obtain simplicity. It also shows how to model domains and languages, how to organize and describe architecture of the application how to test it, and even more.
The list of topics includes:
*
*Approaches to architecture modeling using diagrams;
*Requirements analysis;
*Embedded DSL domain modeling;
*External DSL design and implementation;
*Monads as subsystems with effects;
*Free monads as functional interfaces;
*Arrowised eDSLs;
*Inversion of Control using Free monadic eDSLs;
*Software Transactional Memory;
*Lenses;
*State, Reader, Writer, RWS, ST monads;
*Impure state: IORef, MVar, STM;
*Multithreading and concurrent domain modeling;
*GUI;
*Applicability of mainstream techiques and approaches such as UML, SOLID, GRASP;
*Interaction with impure subsystems.
The book is based on the Haskell projects I'm researching, especially a SCADA application Andromeda. The code for this book is available here. While the book is under development (it will be done till at the of 2017), I can recommend you to get familiar with my article "Design and Architecture in FP" here (Rus).
UPDATE
I shared my book online (first 5 chapters). See post on Reddit
A: I think this may help;
Some of the patterns disappear -- that
is, they are supported directly by
language features, some patterns are
simpler or have a different focus, and
some are essentially unchanged.
[AIM-2002-005] Gregory T. Sullivan, Advanced Programming Language Features for Executable Design Patterns "Better Patterns Through Reflection
March 22, 2002
The Design Patterns book [GOF95]
presents 24 time-tested patterns that
consistently appear in well-designed
software systems. Each pattern is
presented with a description of the
design problem the pattern addresses,
as well as sample implementation code
and design considerations. This paper
explores how the patterns from the
"Gang of Four'', or "GOF'' book, as it
is often called, appear when similar
problems are addressed using a
dynamic, higher-order, object-oriented
programming language. Some of the
patterns disappear -- that is, they
are supported directly by language
features, some patterns are simpler or
have a different focus, and some are
essentially unchanged.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "43"
}
|
Q: Working with .qr2 reports in .NET? We use an ERP that has a bunch of reports in QuickReport format (.qr2). From what I could search, Quickreports has an interface for Delphi but not for .NET.
Anyone know if there's a (preferably free/OSS) solution for converting .qr2 reports to something I could work with in C#? Or a component for reading these reports directly?
A: There is a .NET version of QuickReports supported in Delphi 2005 and Delphi 2006. You have to get the (non-free) "professional" version of QuickReports to get the .NET support, however. It's not included in the "standard" edition. Delphi 2005 and Delphi 2006 both support C#, but I have never tried the .NET version of QuickReports, with either Delphi for .NET or C#. I can't tell you how well it works.
Also, Qsoft is planning to release a C# version of their tool, though it appears to be behind schedule.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is there a tool to convert a .vim colour definition file to use in VS.NET 2008 If you go to a site such as:
http://www.cs.cmu.edu/~maverick/VimColorSchemeTest/index-c.html
It has a bunch of example colour themes for VI.
Does anyone know of a tool that would take those files and convert them into .vssettings files to use in Visual Studio?
If not, how about some good docs on ether of the formats.
A: Here is a Visual Studio theme generator which may help.
http://frickinsweet.com/tools/Theme.mvc.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I execute a program or call a system command? How do I call an external command within Python as if I had typed it in a shell or command prompt?
A: There are a lot of different ways to run external commands in Python,
and all of them have their own plus sides and drawbacks.
My colleagues and me have been writing Python system administration tools, so we need to run a lot of external commands, and sometimes you want them to block or run asynchronously, time-out, update every second, etc.
There are also different ways of handling the return code and errors,
and you might want to parse the output, and provide new input (in an expect kind of style). Or you will need to redirect standard input, standard output, and standard error to run in a different tty (e.g., when using GNU Screen).
So you will probably have to write a lot of wrappers around the external command. So here is a Python module which we have written which can handle
almost anything you would want, and if not, it's very flexible so you can easily extend it:
https://github.com/hpcugent/vsc-base/blob/master/lib/vsc/utils/run.py
It doesn't work stand-alone and requires some of our other tools, and got a lot of specialised functionality over the years, so it might not be a drop-in replacement for you, but it can give you a lot of information on how the internals of Python for running commands work and ideas on how to handle certain situations.
A: Use subprocess.call:
from subprocess import call
# Using list
call(["echo", "Hello", "world"])
# Single string argument varies across platforms so better split it
call("echo Hello world".split(" "))
A: Use:
import subprocess
p = subprocess.Popen("df -h", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
print p.split("\n")
It gives nice output which is easier to work with:
['Filesystem Size Used Avail Use% Mounted on',
'/dev/sda6 32G 21G 11G 67% /',
'none 4.0K 0 4.0K 0% /sys/fs/cgroup',
'udev 1.9G 4.0K 1.9G 1% /dev',
'tmpfs 387M 1.4M 386M 1% /run',
'none 5.0M 0 5.0M 0% /run/lock',
'none 1.9G 58M 1.9G 3% /run/shm',
'none 100M 32K 100M 1% /run/user',
'/dev/sda5 340G 222G 100G 69% /home',
'']
A: As an example (in Linux):
import subprocess
subprocess.run('mkdir test.dir', shell=True)
This creates test.dir in the current directory.
Note that this also works:
import subprocess
subprocess.call('mkdir test.dir', shell=True)
The equivalent code using os.system is:
import os
os.system('mkdir test.dir')
Best practice would be to use subprocess instead of os, with .run favored over .call.
All you need to know about subprocess is here.
Also, note that all Python documentation is available for download from here. I downloaded the PDF packed as .zip. I mention this because there's a nice overview of the os module in tutorial.pdf (page 81). Besides, it's an authoritative resource for Python coders.
A: For using subprocess in Python 3.5+, the following did the trick for me on Linux:
import subprocess
# subprocess.run() returns a completed process object that can be inspected
c = subprocess.run(["ls", "-ltrh"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(c.stdout.decode('utf-8'))
As mentioned in the documentation, PIPE values are byte sequences and for properly showing them decoding should be considered. For later versions of Python, text=True and encoding='utf-8' are added to kwargs of subprocess.run().
The output of the abovementioned code is:
total 113M
-rwxr-xr-x 1 farzad farzad 307 Jan 15 2018 vpnscript
-rwxrwxr-x 1 farzad farzad 204 Jan 15 2018 ex
drwxrwxr-x 4 farzad farzad 4.0K Jan 22 2018 scripts
.... # Some other lines
A: With the standard library
Use the subprocess module (Python 3):
import subprocess
subprocess.run(['ls', '-l'])
It is the recommended standard way. However, more complicated tasks (pipes, output, input, etc.) can be tedious to construct and write.
Note on Python version: If you are still using Python 2, subprocess.call works in a similar way.
ProTip: shlex.split can help you to parse the command for run, call, and other subprocess functions in case you don't want (or you can't!) provide them in form of lists:
import shlex
import subprocess
subprocess.run(shlex.split('ls -l'))
With external dependencies
If you do not mind external dependencies, use plumbum:
from plumbum.cmd import ifconfig
print(ifconfig['wlan0']())
It is the best subprocess wrapper. It's cross-platform, i.e. it works on both Windows and Unix-like systems. Install by pip install plumbum.
Another popular library is sh:
from sh import ifconfig
print(ifconfig('wlan0'))
However, sh dropped Windows support, so it's not as awesome as it used to be. Install by pip install sh.
A: I always use fabric for doing these things. Here is a demo code:
from fabric.operations import local
result = local('ls', capture=True)
print "Content:/n%s" % (result, )
But this seems to be a good tool: sh (Python subprocess interface).
Look at an example:
from sh import vgdisplay
print vgdisplay()
print vgdisplay('-v')
print vgdisplay(v=True)
A: Check the "pexpect" Python library, too.
It allows for interactive controlling of external programs/commands, even ssh, ftp, telnet, etc. You can just type something like:
child = pexpect.spawn('ftp 192.168.0.24')
child.expect('(?i)name .*: ')
child.sendline('anonymous')
child.expect('(?i)password')
A: If you need the output from the command you are calling,
then you can use subprocess.check_output (Python 2.7+).
>>> subprocess.check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Also note the shell parameter.
If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of ~ to a user’s home directory. However, note that Python itself offers implementations of many shell-like features (in particular, glob, fnmatch, os.walk(), os.path.expandvars(), os.path.expanduser(), and shutil).
A: After some research, I have the following code which works very well for me. It basically prints both standard output and standard error in real time.
stdout_result = 1
stderr_result = 1
def stdout_thread(pipe):
global stdout_result
while True:
out = pipe.stdout.read(1)
stdout_result = pipe.poll()
if out == '' and stdout_result is not None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
def stderr_thread(pipe):
global stderr_result
while True:
err = pipe.stderr.read(1)
stderr_result = pipe.poll()
if err == '' and stderr_result is not None:
break
if err != '':
sys.stdout.write(err)
sys.stdout.flush()
def exec_command(command, cwd=None):
if cwd is not None:
print '[' + ' '.join(command) + '] in ' + cwd
else:
print '[' + ' '.join(command) + ']'
p = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd
)
out_thread = threading.Thread(name='stdout_thread', target=stdout_thread, args=(p,))
err_thread = threading.Thread(name='stderr_thread', target=stderr_thread, args=(p,))
err_thread.start()
out_thread.start()
out_thread.join()
err_thread.join()
return stdout_result + stderr_result
A: Here is calling an external command and return or print the command's output:
Python Subprocess check_output is good for
Run command with arguments and return its output as a byte string.
import subprocess
proc = subprocess.check_output('ipconfig /all')
print proc
A: If you need to call a shell command from a Python notebook (like Jupyter, Zeppelin, Databricks, or Google Cloud Datalab) you can just use the ! prefix.
For example,
!ls -ilF
A: If you're writing a Python shell script and have IPython installed on your system, you can use the bang prefix to run a shell command inside IPython:
!ls
filelist = !ls
A: Update 2015: Python 3.5 added subprocess.run which is much easier to use than subprocess.Popen. I recommend that.
>>> subprocess.run(["ls", "-l"]) # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)
>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
A: Update:
subprocess.run is the recommended approach as of Python 3.5 if your code does not need to maintain compatibility with earlier Python versions. It's more consistent and offers similar ease-of-use as Envoy. (Piping isn't as straightforward though. See this question for how.)
Here's some examples from the documentation.
Run a process:
>>> subprocess.run(["ls", "-l"]) # Doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)
Raise on failed run:
>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
Capture output:
>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')
Original answer:
I recommend trying Envoy. It's a wrapper for subprocess, which in turn aims to replace the older modules and functions. Envoy is subprocess for humans.
Example usage from the README:
>>> r = envoy.run('git config', data='data to pipe in', timeout=2)
>>> r.status_code
129
>>> r.std_out
'usage: git config [options]'
>>> r.std_err
''
Pipe stuff around too:
>>> r = envoy.run('uptime | pbcopy')
>>> r.command
'pbcopy'
>>> r.status_code
0
>>> r.history
[<Response 'uptime'>]
A: This is how I run my commands. This code has everything you need pretty much
from subprocess import Popen, PIPE
cmd = "ls -l ~/"
p = Popen(cmd , shell=True, stdout=PIPE, stderr=PIPE)
out, err = p.communicate()
print "Return code: ", p.returncode
print out.rstrip(), err.rstrip()
A: For Python 3.5+ it is recommended that you use the run function from the subprocess module. This returns a CompletedProcess object, from which you can easily obtain the output as well as return code.
from subprocess import PIPE, run
command = ['echo', 'hello']
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(result.returncode, result.stdout, result.stderr)
A:
How to execute a program or call a system command from Python
Simple, use subprocess.run, which returns a CompletedProcess object:
>>> from subprocess import run
>>> from shlex import split
>>> completed_process = run(split('python --version'))
Python 3.8.8
>>> completed_process
CompletedProcess(args=['python', '--version'], returncode=0)
(run wants a list of lexically parsed shell arguments - this is what you'd type in a shell, separated by spaces, but not where the spaces are quoted, so use a specialized function, split, to split up what you would literally type into your shell)
Why?
As of Python 3.5, the documentation recommends subprocess.run:
The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.
Here's an example of the simplest possible usage - and it does exactly as asked:
>>> from subprocess import run
>>> from shlex import split
>>> completed_process = run(split('python --version'))
Python 3.8.8
>>> completed_process
CompletedProcess(args=['python', '--version'], returncode=0)
run waits for the command to successfully finish, then returns a CompletedProcess object. It may instead raise TimeoutExpired (if you give it a timeout= argument) or CalledProcessError (if it fails and you pass check=True).
As you might infer from the above example, stdout and stderr both get piped to your own stdout and stderr by default.
We can inspect the returned object and see the command that was given and the returncode:
>>> completed_process.args
['python', '--version']
>>> completed_process.returncode
0
Capturing output
If you want to capture the output, you can pass subprocess.PIPE to the appropriate stderr or stdout:
>>> from subprocess import PIPE
>>> completed_process = run(shlex.split('python --version'), stdout=PIPE, stderr=PIPE)
>>> completed_process.stdout
b'Python 3.8.8\n'
>>> completed_process.stderr
b''
And those respective attributes return bytes.
Pass a command list
One might easily move from manually providing a command string (like the question suggests) to providing a string built programmatically. Don't build strings programmatically. This is a potential security issue. It's better to assume you don't trust the input.
>>> import textwrap
>>> args = ['python', textwrap.__file__]
>>> cp = run(args, stdout=subprocess.PIPE)
>>> cp.stdout
b'Hello there.\n This is indented.\n'
Note, only args should be passed positionally.
Full Signature
Here's the actual signature in the source and as shown by help(run):
def run(*popenargs, input=None, timeout=None, check=False, **kwargs):
The popenargs and kwargs are given to the Popen constructor. input can be a string of bytes (or unicode, if specify encoding or universal_newlines=True) that will be piped to the subprocess's stdin.
The documentation describes timeout= and check=True better than I could:
The timeout argument is passed to Popen.communicate(). If the timeout
expires, the child process will be killed and waited for. The
TimeoutExpired exception will be re-raised after the child process has
terminated.
If check is true, and the process exits with a non-zero exit code, a
CalledProcessError exception will be raised. Attributes of that
exception hold the arguments, the exit code, and stdout and stderr if
they were captured.
and this example for check=True is better than one I could come up with:
>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
Expanded Signature
Here's an expanded signature, as given in the documentation:
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None,
shell=False, cwd=None, timeout=None, check=False, encoding=None,
errors=None)
Note that this indicates that only the args list should be passed positionally. So pass the remaining arguments as keyword arguments.
Popen
When use Popen instead? I would struggle to find use-case based on the arguments alone. Direct usage of Popen would, however, give you access to its methods, including poll, 'send_signal', 'terminate', and 'wait'.
Here's the Popen signature as given in the source. I think this is the most precise encapsulation of the information (as opposed to help(Popen)):
def __init__(self, args, bufsize=-1, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=True,
shell=False, cwd=None, env=None, universal_newlines=None,
startupinfo=None, creationflags=0,
restore_signals=True, start_new_session=False,
pass_fds=(), *, user=None, group=None, extra_groups=None,
encoding=None, errors=None, text=None, umask=-1, pipesize=-1):
But more informative is the Popen documentation:
subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None,
stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None,
env=None, universal_newlines=None, startupinfo=None, creationflags=0,
restore_signals=True, start_new_session=False, pass_fds=(), *, group=None,
extra_groups=None, user=None, umask=-1, encoding=None, errors=None,
text=None)
Execute a child program in a new process. On POSIX, the class uses
os.execvp()-like behavior to execute the child program. On Windows,
the class uses the Windows CreateProcess() function. The arguments to
Popen are as follows.
Understanding the remaining documentation on Popen will be left as an exercise for the reader.
A: Use the subprocess module in the standard library:
import subprocess
# for simple commands
subprocess.run(["ls", "-l"])
# for complex commands, with many args, use string + `shell=True`:
cmd_str = "ls -l /tmp | awk '{print $3,$9}' | grep root"
subprocess.run(cmd_str, shell=True)
The advantage of subprocess.run over os.system is that it is more flexible (you can get the stdout, stderr, the "real" status code, better error handling, etc...).
Even the documentation for os.system recommends using subprocess instead:
The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.
On Python 3.4 and earlier, use subprocess.call instead of .run:
subprocess.call(["ls", "-l"])
A: Use subprocess.
...or for a very simple command:
import os
os.system('cat testfile')
A: If you are not using user input in the commands, you can use this:
from os import getcwd
from subprocess import check_output
from shlex import quote
def sh(command):
return check_output(quote(command), shell=True, cwd=getcwd(), universal_newlines=True).strip()
And use it as
branch = sh('git rev-parse --abbrev-ref HEAD')
shell=True will spawn a shell, so you can use pipe and such shell things sh('ps aux | grep python'). This is very very handy for running hardcoded commands and processing its output. The universal_lines=True make sure the output is returned in a string instead of binary.
cwd=getcwd() will make sure that the command is run with the same working directory as the interpreter. This is handy for Git commands to work like the Git branch name example above.
Some recipes
*
*free memory in megabytes: sh('free -m').split('\n')[1].split()[1]
*free space on / in percent sh('df -m /').split('\n')[1].split()[4][0:-1]
*CPU load sum(map(float, sh('ps -ef -o pcpu').split('\n')[1:])
But this isn't safe for user input, from the documentation:
Security Considerations
Unlike some other popen functions, this implementation will never
implicitly call a system shell. This means that all characters,
including shell metacharacters, can safely be passed to child
processes. If the shell is invoked explicitly, via shell=True, it is
the application’s responsibility to ensure that all whitespace and
metacharacters are quoted appropriately to avoid shell injection
vulnerabilities.
When using shell=True, the shlex.quote() function can be used to
properly escape whitespace and shell metacharacters in strings that
are going to be used to construct shell commands.
Even using the shlex.quote(), it is good to keep a little paranoid when using user inputs on shell commands. One option is using a hardcoded command to take some generic output and filtering by user input. Anyway using shell=False will make sure that only the exactly process that you want to execute will be executed or you get a No such file or directory error.
Also there is some performance impact on shell=True, from my tests it seems about 20% slower than shell=False (the default).
In [50]: timeit("check_output('ls -l'.split(), universal_newlines=True)", number=1000, globals=globals())
Out[50]: 2.6801227919995654
In [51]: timeit("check_output('ls -l', universal_newlines=True, shell=True)", number=1000, globals=globals())
Out[51]: 3.243950183999914
A: import subprocess
p = subprocess.run(["ls", "-ltr"], capture_output=True)
print(p.stdout.decode(), p.stderr.decode())
Try online
A: You can try using os.system() for running external commands.
Example:
import os
try:
os.system('ls')
pass
except:
print("Error running command")
pass
In the example, the script imports os and tries to run the command listed in os.system(). If the command was to fail then it would print "Error running command" without the script stopping due to the error.
And yes, it’s just that simple!
A: As of Python 3.7.0 released on June 27th 2018 (https://docs.python.org/3/whatsnew/3.7.html), you can achieve your desired result in the most powerful while equally simple way. This answer intends to show you the essential summary of various options in a short manner. For in-depth answers, please see the other ones.
TL;DR in 2021
The big advantage of os.system(...) was its simplicity. subprocess is better and still easy to use, especially as of Python 3.5.
import subprocess
subprocess.run("ls -a", shell=True)
Note: This is the exact answer to your question - running a command
like in a shell
Preferred Way
If possible, remove the shell overhead and run the command directly (requires a list).
import subprocess
subprocess.run(["help"])
subprocess.run(["ls", "-a"])
Pass program arguments in a list. Don't include \"-escaping for arguments containing spaces.
Advanced Use Cases
Checking The Output
The following code speaks for itself:
import subprocess
result = subprocess.run(["ls", "-a"], capture_output=True, text=True)
if "stackoverflow-logo.png" in result.stdout:
print("You're a fan!")
else:
print("You're not a fan?")
result.stdout is all normal program output excluding errors. Read result.stderr to get them.
capture_output=True - turns capturing on. Otherwise result.stderr and result.stdout would be None. Available from Python 3.7.
text=True - a convenience argument added in Python 3.7 which converts the received binary data to Python strings you can easily work with.
Checking the returncode
Do
if result.returncode == 127: print("The program failed for some weird reason")
elif result.returncode == 0: print("The program succeeded")
else: print("The program failed unexpectedly")
If you just want to check if the program succeeded (returncode == 0) and otherwise throw an Exception, there is a more convenient function:
result.check_returncode()
But it's Python, so there's an even more convenient argument check which does the same thing automatically for you:
result = subprocess.run(..., check=True)
stderr should be inside stdout
You might want to have all program output inside stdout, even errors. To accomplish this, run
result = subprocess.run(..., stderr=subprocess.STDOUT)
result.stderr will then be None and result.stdout will contain everything.
Using shell=False with an argument string
shell=False expects a list of arguments. You might however, split an argument string on your own using shlex.
import subprocess
import shlex
subprocess.run(shlex.split("ls -a"))
That's it.
Common Problems
Chances are high you just started using Python when you come across this question. Let's look at some common problems.
FileNotFoundError: [Errno 2] No such file or directory: 'ls -a': 'ls -a'
You're running a subprocess without shell=True . Either use a list (["ls", "-a"]) or set shell=True.
TypeError: [...] NoneType [...]
Check that you've set capture_output=True.
TypeError: a bytes-like object is required, not [...]
You always receive byte results from your program. If you want to work with it like a normal string, set text=True.
subprocess.CalledProcessError: Command '[...]' returned non-zero exit status 1.
Your command didn't run successfully. You could disable returncode checking or check your actual program's validity.
TypeError: init() got an unexpected keyword argument [...]
You're likely using a version of Python older than 3.7.0; update it to the most recent one available. Otherwise there are other answers in this Stack Overflow post showing you older alternative solutions.
A: os.system is OK, but kind of dated. It's also not very secure. Instead, try subprocess. subprocess does not call sh directly and is therefore more secure than os.system.
Get more information here.
A: Typical implementation:
import subprocess
p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
print line,
retval = p.wait()
You are free to do what you want with the stdout data in the pipe. In fact, you can simply omit those parameters (stdout= and stderr=) and it'll behave like os.system().
A: There is also Plumbum
>>> from plumbum import local
>>> ls = local["ls"]
>>> ls
LocalCommand(<LocalPath /bin/ls>)
>>> ls()
u'build.py\ndist\ndocs\nLICENSE\nplumbum\nREADME.rst\nsetup.py\ntests\ntodo.txt\n'
>>> notepad = local["c:\\windows\\notepad.exe"]
>>> notepad() # Notepad window pops up
u'' # Notepad window is closed by user, command returns
A: Using the Popen function of the subprocess Python module is the simplest way of running Linux commands. In that, the Popen.communicate() function will give your commands output. For example
import subprocess
..
process = subprocess.Popen(..) # Pass command and arguments to the function
stdout, stderr = process.communicate() # Get command output and error
..
A: There are many ways to call a command.
*
*For example:
if and.exe needs two parameters. In cmd we can call sample.exe use this:
and.exe 2 3 and it show 5 on screen.
If we use a Python script to call and.exe, we should do like..
*
*os.system(cmd,...)
*
*os.system(("and.exe" + " " + "2" + " " + "3"))
*os.popen(cmd,...)
*
*os.popen(("and.exe" + " " + "2" + " " + "3"))
*subprocess.Popen(cmd,...)
*
*subprocess.Popen(("and.exe" + " " + "2" + " " + "3"))
It's too hard, so we can join cmd with a space:
import os
cmd = " ".join(exename,parameters)
os.popen(cmd)
A: os.popen() is the easiest and the most safest way to execute a command. You can execute any command that you run on the command line. In addition you will also be able to capture the output of the command using os.popen().read()
You can do it like this:
import os
output = os.popen('Your Command Here').read()
print (output)
An example where you list all the files in the current directory:
import os
output = os.popen('ls').read()
print (output)
# Outputs list of files in the directory
A: Here is a summary of ways to call external programs, including their advantages and disadvantages:
*
*os.system passes the command and arguments to your system's shell. This is nice because you can actually run multiple commands at once in this manner and set up pipes and input/output redirection. For example:
os.system("some_command < input_file | another_command > output_file")
However, while this is convenient, you have to manually handle the escaping of shell characters such as spaces, et cetera. On the other hand, this also lets you run commands which are simply shell commands and not actually external programs.
*os.popen will do the same thing as os.system except that it gives you a file-like object that you can use to access standard input/output for that process. There are 3 other variants of popen that all handle the i/o slightly differently. If you pass everything as a string, then your command is passed to the shell; if you pass them as a list then you don't need to worry about escaping anything. Example:
print(os.popen("ls -l").read())
*subprocess.Popen. This is intended as a replacement for os.popen, but has the downside of being slightly more complicated by virtue of being so comprehensive. For example, you'd say:
print subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE).stdout.read()
instead of
print os.popen("echo Hello World").read()
but it is nice to have all of the options there in one unified class instead of 4 different popen functions. See the documentation.
*subprocess.call. This is basically just like the Popen class and takes all of the same arguments, but it simply waits until the command completes and gives you the return code. For example:
return_code = subprocess.call("echo Hello World", shell=True)
*subprocess.run. Python 3.5+ only. Similar to the above but even more flexible and returns a CompletedProcess object when the command finishes executing.
*os.fork, os.exec, os.spawn are similar to their C language counterparts, but I don't recommend using them directly.
The subprocess module should probably be what you use.
Finally, please be aware that for all methods where you pass the final command to be executed by the shell as a string and you are responsible for escaping it. There are serious security implications if any part of the string that you pass can not be fully trusted. For example, if a user is entering some/any part of the string. If you are unsure, only use these methods with constants. To give you a hint of the implications consider this code:
print subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read()
and imagine that the user enters something "my mama didnt love me && rm -rf /" which could erase the whole filesystem.
A: Use:
import os
cmd = 'ls -al'
os.system(cmd)
os - This module provides a portable way of using operating system-dependent functionality.
For the more os functions, here is the documentation.
A: It can be this simple:
import os
cmd = "your command"
os.system(cmd)
A: I would recommend the following method 'run' and it will help us in getting standard output, standard error and exit status as a dictionary; the caller of this can read the dictionary return by 'run' method to know the actual state of the process.
def run (cmd):
print "+ DEBUG exec({0})".format(cmd)
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True)
(out, err) = p.communicate()
ret = p.wait()
out = filter(None, out.split('\n'))
err = filter(None, err.split('\n'))
ret = True if ret == 0 else False
return dict({'output': out, 'error': err, 'status': ret})
#end
A: Python 3.5+
import subprocess
p = subprocess.run(["ls", "-ltr"], capture_output=True)
print(p.stdout.decode(), p.stderr.decode())
Try online
A: There are a number of ways of calling an external command from Python. There are some functions and modules with the good helper functions that can make it really easy. But the recommended thing among all is the subprocess module.
import subprocess as s
s.call(["command.exe", "..."])
The call function will start the external process, pass some command line arguments and wait for it to finish. When it finishes you continue executing. Arguments in call function are passed through the list. The first argument in the list is the command typically in the form of an executable file and subsequent arguments in the list whatever you want to pass.
If you have called processes from the command line in the windows before, you'll be aware that you often need to quote arguments. You need to put quotations mark around it. If there's a space then there's a backslash and there are some complicated rules, but you can avoid a whole lot of that in Python by using subprocess module because it is a list and each item is known to be a distinct and python can get quoting correctly for you.
In the end, after the list, there are a number of optional parameters one of these is a shell and if you set shell equals to true then your command is going to be run as if you have typed in at the command prompt.
s.call(["command.exe", "..."], shell=True)
This gives you access to functionality like piping, you can redirect to files, you can call multiple commands in one thing.
One more thing, if your script relies on the process succeeding then you want to check the result and the result can be checked with the check call helper function.
s.check_call(...)
It is exactly the same as a call function, it takes the same arguments, takes the same list, you can pass in any of the extra arguments but it going to wait for the functions to complete. And if the exit code of the function is anything other then zero, it will through an exception in the python script.
Finally, if you want tighter control Popen constructor which is also from the subprocess module. It also takes the same arguments as incall & check_call function but it returns an object representing the running process.
p=s.Popen("...")
It does not wait for the running process to finish also it's not going to throw any exception immediately but it gives you an object that will let you do things like wait for it to finish, let you communicate to it, you can redirect standard input, standard output if you want to display output somewhere else and a lot more.
A: You can run any command using Popen from the subprocess module.
from subprocess import Popen
First of all, a command object is created with all arguments which you want to run. For example, in the snippet below, the gunicorm command object has been formed with all the arguments:
cmd = (
"gunicorn "
"-c gunicorn_conf.py "
"-w {workers} "
"--timeout {timeout} "
"-b {address}:{port} "
"--limit-request-line 0 "
"--limit-request-field_size 0 "
"--log-level debug "
"--max-requests {max_requests} "
"manage:app").format(**locals())
Then this command object is used with Popen to instantiate a process:
process = Popen(cmd, shell=True)
This process can be terminated as well based upon any signal, using the code line below:
Popen.terminate(process)
And you can wait till the completion of above command's execution:
process.wait()
A: Here there are a lot of answers, but none fulfilled all my needs.
*
*I need to run the command and capture the output and exit code.
*I need to timeout the executed program and force it to exit if timeout is reached, and kill all its child processes.
*and I need that it works in Windows XP and later, Cygwin and Linux. In Python 2 and 3.
So I created this:
def _run(command, timeout_s=False, shell=False):
### run a process, capture the output and wait for it to finish. if timeout is specified then Kill the subprocess and its children when the timeout is reached (if parent did not detach)
## usage: _run(arg1, arg2, arg3)
# arg1: command + arguments. Always pass a string; the function will split it when needed
# arg2: (optional) timeout in seconds before force killing
# arg3: (optional) shell usage. default shell=False
## return: a list containing: exit code, output, and if timeout was reached or not
# - Tested on Python 2 and 3 on Windows XP, Windows 7, Cygwin and Linux.
# - preexec_fn=os.setsid (py2) is equivalent to start_new_session (py3) (works on Linux only), in Windows and Cygwin we use TASKKILL
# - we use stderr=subprocess.STDOUT to merge standard error and standard output
import sys, subprocess, os, signal, shlex, time
def _runPY3(command, timeout_s=None, shell=False):
# py3.3+ because: timeout was added to communicate() in py3.3.
new_session=False
if sys.platform.startswith('linux'): new_session=True
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=new_session, shell=shell)
try:
out = p.communicate(timeout=timeout_s)[0].decode('utf-8')
is_timeout_reached = False
except subprocess.TimeoutExpired:
print('Timeout reached: Killing the whole process group...')
killAll(p.pid)
out = p.communicate()[0].decode('utf-8')
is_timeout_reached = True
return p.returncode, out, is_timeout_reached
def _runPY2(command, timeout_s=0, shell=False):
preexec=None
if sys.platform.startswith('linux'): preexec=os.setsid
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, preexec_fn=preexec, shell=shell)
start_time = time.time()
is_timeout_reached = False
while timeout_s and p.poll() == None:
if time.time()-start_time >= timeout_s:
print('Timeout reached: Killing the whole process group...')
killAll(p.pid)
is_timeout_reached = True
break
time.sleep(1)
out = p.communicate()[0].decode('utf-8')
return p.returncode, out, is_timeout_reached
def killAll(ParentPid):
if sys.platform.startswith('linux'):
os.killpg(os.getpgid(ParentPid), signal.SIGTERM)
elif sys.platform.startswith('cygwin'):
# subprocess.Popen(shlex.split('bash -c "TASKKILL /F /PID $(</proc/{pid}/winpid) /T"'.format(pid=ParentPid)))
winpid=int(open("/proc/{pid}/winpid".format(pid=ParentPid)).read())
subprocess.Popen(['TASKKILL', '/F', '/PID', str(winpid), '/T'])
elif sys.platform.startswith('win32'):
subprocess.Popen(['TASKKILL', '/F', '/PID', str(ParentPid), '/T'])
# - In Windows, we never need to split the command, but in Cygwin and Linux we need to split if shell=False (default), shlex will split the command for us
if shell==False and (sys.platform.startswith('cygwin') or sys.platform.startswith('linux')):
command=shlex.split(command)
if sys.version_info >= (3, 3): # py3.3+
if timeout_s==False:
returnCode, output, is_timeout_reached = _runPY3(command, timeout_s=None, shell=shell)
else:
returnCode, output, is_timeout_reached = _runPY3(command, timeout_s=timeout_s, shell=shell)
else: # Python 2 and up to 3.2
if timeout_s==False:
returnCode, output, is_timeout_reached = _runPY2(command, timeout_s=0, shell=shell)
else:
returnCode, output, is_timeout_reached = _runPY2(command, timeout_s=timeout_s, shell=shell)
return returnCode, output, is_timeout_reached
Then use it like this:
Always pass the command as one string (it is easier). You do not need to split it; the function will split it when needed.
If your command works in your shell, it will work with this function, so test your command in your shell first cmd/Bash.
So we can use it like this with a timeout:
a=_run('cmd /c echo 11111 & echo 22222 & calc',3)
for i in a[1].splitlines(): print(i)
Or without a timeout:
b=_run('cmd /c echo 11111 & echo 22222 & calc')
More examples:
b=_run('''wmic nic where 'NetConnectionID="Local Area Connection"' get NetConnectionStatus /value''')
print(b)
c=_run('cmd /C netsh interface ip show address "Local Area Connection"')
print(c)
d=_run('printf "<%s>\n" "{foo}"')
print(d)
You can also specify shell=True, but it is useless in most cases with this function. I prefer to choose myself the shell I want, but here it is if you need it too:
# windows
e=_run('echo 11111 & echo 22222 & calc',3, shell=True)
print(e)
# Cygwin/Linux:
f=_run('printf "<%s>\n" "{foo}"', shell=True)
print(f)
Why did I not use the simpler new method subprocess.run()?
*
*because it is supported in Python 3.7+, but the last supported Python version in Windows XP is 3.4.
*and because the timeout argument of this function is useless in Windows, it does not kill the child processes of the executed command.
*if you use the capture_output + timeout argument, it will hang if there is a child process still running. And it is still broken in Windows, for which the issue 31447 is still open.
A: Some hints on detaching the child process from the calling one (starting the child process in background).
Suppose you want to start a long task from a CGI script. That is, the child process should live longer than the CGI script execution process.
The classical example from the subprocess module documentation is:
import subprocess
import sys
# Some code here
pid = subprocess.Popen([sys.executable, "longtask.py"]) # Call subprocess
# Some more code here
The idea here is that you do not want to wait in the line 'call subprocess' until the longtask.py is finished. But it is not clear what happens after the line 'some more code here' from the example.
My target platform was FreeBSD, but the development was on Windows, so I faced the problem on Windows first.
On Windows (Windows XP), the parent process will not finish until the longtask.py has finished its work. It is not what you want in a CGI script. The problem is not specific to Python; in the PHP community the problems are the same.
The solution is to pass DETACHED_PROCESS Process Creation Flag to the underlying CreateProcess function in Windows API.
If you happen to have installed pywin32, you can import the flag from the win32process module, otherwise you should define it yourself:
DETACHED_PROCESS = 0x00000008
pid = subprocess.Popen([sys.executable, "longtask.py"],
creationflags=DETACHED_PROCESS).pid
/* UPD 2015.10.27 @eryksun in a comment below notes, that the semantically correct flag is CREATE_NEW_CONSOLE (0x00000010) */
On FreeBSD we have another problem: when the parent process is finished, it finishes the child processes as well. And that is not what you want in a CGI script either. Some experiments showed that the problem seemed to be in sharing sys.stdout. And the working solution was the following:
pid = subprocess.Popen([sys.executable, "longtask.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
I have not checked the code on other platforms and do not know the reasons of the behaviour on FreeBSD. If anyone knows, please share your ideas. Googling on starting background processes in Python does not shed any light yet.
A: There is another difference here which is not mentioned previously.
subprocess.Popen executes the <command> as a subprocess. In my case, I need to execute file <a> which needs to communicate with another program, <b>.
I tried subprocess, and execution was successful. However <b> could not communicate with <a>.
Everything is normal when I run both from the terminal.
One more:
(NOTE: kwrite behaves different from other applications. If you try the below with Firefox, the results will not be the same.)
If you try os.system("kwrite"), program flow freezes until the user closes kwrite. To overcome that I tried instead os.system(konsole -e kwrite). This time program continued to flow, but kwrite became the subprocess of the console.
Anyone runs the kwrite not being a subprocess (i.e. in the system monitor it must appear at the leftmost edge of the tree).
A: os.system does not allow you to store results, so if you want to store results in some list or something, a subprocess.call works.
A: subprocess.check_call is convenient if you don't want to test return values. It throws an exception on any error.
A: I tend to use subprocess together with shlex (to handle escaping of quoted strings):
>>> import subprocess, shlex
>>> command = 'ls -l "/your/path/with spaces/"'
>>> call_params = shlex.split(command)
>>> print call_params
["ls", "-l", "/your/path/with spaces/"]
>>> subprocess.call(call_params)
A: import os
os.system("your command")
Note that this is dangerous, since the command isn't cleaned. I leave it up to you to google for the relevant documentation on the 'os' and 'sys' modules. There are a bunch of functions (exec* and spawn*) that will do similar things.
A: I wrote a library for this, shell.py.
It's basically a wrapper for popen and shlex for now. It also supports piping commands, so you can chain commands easier in Python. So you can do things like:
ex('echo hello shell.py') | "awk '{print $2}'"
A: Under Linux, in case you would like to call an external command that will execute independently (will keep running after the Python script terminates), you can use a simple queue as task spooler or the at command.
An example with task spooler:
import os
os.system('ts <your-command>')
Notes about task spooler (ts):
*
*You could set the number of concurrent processes to be run ("slots") with:
ts -S <number-of-slots>
*Installing ts doesn't requires admin privileges. You can download and compile it from source with a simple make, add it to your path and you're done.
A: I have written a wrapper to handle errors and redirecting output and other stuff.
import shlex
import psutil
import subprocess
def call_cmd(cmd, stdout=sys.stdout, quiet=False, shell=False, raise_exceptions=True, use_shlex=True, timeout=None):
"""Exec command by command line like 'ln -ls "/var/log"'
"""
if not quiet:
print("Run %s", str(cmd))
if use_shlex and isinstance(cmd, (str, unicode)):
cmd = shlex.split(cmd)
if timeout is None:
process = subprocess.Popen(cmd, stdout=stdout, stderr=sys.stderr, shell=shell)
retcode = process.wait()
else:
process = subprocess.Popen(cmd, stdout=stdout, stderr=sys.stderr, shell=shell)
p = psutil.Process(process.pid)
finish, alive = psutil.wait_procs([p], timeout)
if len(alive) > 0:
ps = p.children()
ps.insert(0, p)
print('waiting for timeout again due to child process check')
finish, alive = psutil.wait_procs(ps, 0)
if len(alive) > 0:
print('process {} will be killed'.format([p.pid for p in alive]))
for p in alive:
p.kill()
if raise_exceptions:
print('External program timeout at {} {}'.format(timeout, cmd))
raise CalledProcessTimeout(1, cmd)
retcode = process.wait()
if retcode and raise_exceptions:
print("External program failed %s", str(cmd))
raise subprocess.CalledProcessError(retcode, cmd)
You can call it like this:
cmd = 'ln -ls "/var/log"'
stdout = 'out.txt'
call_cmd(cmd, stdout)
A: In Windows you can just import the subprocess module and run external commands by calling subprocess.Popen(), subprocess.Popen().communicate() and subprocess.Popen().wait() as below:
# Python script to run a command line
import subprocess
def execute(cmd):
"""
Purpose : To execute a command and return exit status
Argument : cmd - command to execute
Return : exit_code
"""
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(result, error) = process.communicate()
rc = process.wait()
if rc != 0:
print "Error: failed to execute command:", cmd
print error
return result
# def
command = "tasklist | grep python"
print "This process detail: \n", execute(command)
Output:
This process detail:
python.exe 604 RDP-Tcp#0 4 5,660 K
A: Invoke is a Python (2.7 and 3.4+) task execution tool and library. It provides a clean, high-level API for running shell commands:
>>> from invoke import run
>>> cmd = "pip install -r requirements.txt"
>>> result = run(cmd, hide=True, warn=True)
>>> print(result.ok)
True
>>> print(result.stdout.splitlines()[-1])
Successfully installed invocations-0.13.0 pep8-1.5.7 spec-1.3.1
A: You can use Popen, and then you can check the procedure's status:
from subprocess import Popen
proc = Popen(['ls', '-l'])
if proc.poll() is None:
proc.kill()
Check out subprocess.Popen.
A: A simple way is to use the os module:
import os
os.system('ls')
Alternatively, you can also use the subprocess module:
import subprocess
subprocess.check_call('ls')
If you want the result to be stored in a variable try:
import subprocess
r = subprocess.check_output('ls')
A: I'd recommend using the subprocess module instead of os.system because it does shell escaping for you and is therefore much safer.
subprocess.call(['ping', 'localhost'])
A: To fetch the network id from the OpenStack Neutron:
#!/usr/bin/python
import os
netid = "nova net-list | awk '/ External / { print $2 }'"
temp = os.popen(netid).read() /* Here temp also contains new line (\n) */
networkId = temp.rstrip()
print(networkId)
Output of nova net-list
+--------------------------------------+------------+------+
| ID | Label | CIDR |
+--------------------------------------+------------+------+
| 431c9014-5b5d-4b51-a357-66020ffbb123 | test1 | None |
| 27a74fcd-37c0-4789-9414-9531b7e3f126 | External | None |
| 5a2712e9-70dc-4b0e-9281-17e02f4684c9 | management | None |
| 7aa697f5-0e60-4c15-b4cc-9cb659698512 | Internal | None |
+--------------------------------------+------------+------+
Output of print(networkId)
27a74fcd-37c0-4789-9414-9531b7e3f126
A: import os
cmd = 'ls -al'
os.system(cmd)
If you want to return the results of the command, you can use os.popen. However, this is deprecated since version 2.6 in favor of the subprocess module, which other answers have covered well.
A: Very simplest way to run any command and get the result back:
from commands import getstatusoutput
try:
return getstatusoutput("ls -ltr")
except Exception, e:
return None
A: MOST OF THE CASES:
For the most of cases, a short snippet of code like this is all you are going to need:
import subprocess
import shlex
source = "test.txt"
destination = "test_copy.txt"
base = "cp {source} {destination}'"
cmd = base.format(source=source, destination=destination)
subprocess.check_call(shlex.split(cmd))
It is clean and simple.
subprocess.check_call run command with arguments and wait for
command to complete.
shlex.split split the string cmd using shell-like syntax
REST OF THE CASES:
If this do not work for some specific command, most probably you have a problem with command-line interpreters. The operating system chose the default one which is not suitable for your type of program or could not found an adequate one on the system executable path.
Example:
Using the redirection operator on a Unix system
input_1 = "input_1.txt"
input_2 = "input_2.txt"
output = "merged.txt"
base_command = "/bin/bash -c 'cat {input} >> {output}'"
base_command.format(input_1, output=output)
subprocess.check_call(shlex.split(base_command))
base_command.format(input_2, output=output)
subprocess.check_call(shlex.split(base_command))
As it is stated in The Zen of Python: Explicit is better than
implicit
So if using a Python >=3.6 function, it would look something like this:
import subprocess
import shlex
def run_command(cmd_interpreter: str, command: str) -> None:
base_command = f"{cmd_interpreter} -c '{command}'"
subprocess.check_call(shlex.split(base_command)
A: There are lots of different libraries which allow you to call external commands with Python. For each library I've given a description and shown an example of calling an external command. The command I used as the example is ls -l (list all files). If you want to find out more about any of the libraries I've listed and linked the documentation for each of them.
Sources
*
*subprocess: https://docs.python.org/3.5/library/subprocess.html
*shlex: https://docs.python.org/3/library/shlex.html
*os: https://docs.python.org/3.5/library/os.html
*sh: https://amoffat.github.io/sh/
*plumbum: https://plumbum.readthedocs.io/en/latest/
*pexpect: https://pexpect.readthedocs.io/en/stable/
*fabric: http://www.fabfile.org/
*envoy: https://github.com/kennethreitz/envoy
*commands: https://docs.python.org/2/library/commands.html
These are all the libraries
Hopefully this will help you make a decision on which library to use :)
subprocess
Subprocess allows you to call external commands and connect them to their input/output/error pipes (stdin, stdout, and stderr). Subprocess is the default choice for running commands, but sometimes other modules are better.
subprocess.run(["ls", "-l"]) # Run command
subprocess.run(["ls", "-l"], stdout=subprocess.PIPE) # This will run the command and return any output
subprocess.run(shlex.split("ls -l")) # You can also use the shlex library to split the command
os
os is used for "operating system dependent functionality". It can also be used to call external commands with os.system and os.popen (Note: There is also a subprocess.popen). os will always run the shell and is a simple alternative for people who don't need to, or don't know how to use subprocess.run.
os.system("ls -l") # Run command
os.popen("ls -l").read() # This will run the command and return any output
sh
sh is a subprocess interface which lets you call programs as if they were functions. This is useful if you want to run a command multiple times.
sh.ls("-l") # Run command normally
ls_cmd = sh.Command("ls") # Save command as a variable
ls_cmd() # Run command as if it were a function
plumbum
plumbum is a library for "script-like" Python programs. You can call programs like functions as in sh. Plumbum is useful if you want to run a pipeline without the shell.
ls_cmd = plumbum.local("ls -l") # Get command
ls_cmd() # Run command
pexpect
pexpect lets you spawn child applications, control them and find patterns in their output. This is a better alternative to subprocess for commands that expect a tty on Unix.
pexpect.run("ls -l") # Run command as normal
child = pexpect.spawn('scp foo user@example.com:.') # Spawns child application
child.expect('Password:') # When this is the output
child.sendline('mypassword')
fabric
fabric is a Python 2.5 and 2.7 library. It allows you to execute local and remote shell commands. Fabric is simple alternative for running commands in a secure shell (SSH)
fabric.operations.local('ls -l') # Run command as normal
fabric.operations.local('ls -l', capture = True) # Run command and receive output
envoy
envoy is known as "subprocess for humans". It is used as a convenience wrapper around the subprocess module.
r = envoy.run("ls -l") # Run command
r.std_out # Get output
commands
commands contains wrapper functions for os.popen, but it has been removed from Python 3 since subprocess is a better alternative.
A: Often, I use the following function for external commands, and this is especially handy for long running processes. The below method tails process output while it is running and returns the output, raises an exception if process fails.
It comes out if the process is done using the poll() method on the process.
import subprocess,sys
def exec_long_running_proc(command, args):
cmd = "{} {}".format(command, " ".join(str(arg) if ' ' not in arg else arg.replace(' ','\ ') for arg in args))
print(cmd)
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# Poll process for new output until finished
while True:
nextline = process.stdout.readline().decode('UTF-8')
if nextline == '' and process.poll() is not None:
break
sys.stdout.write(nextline)
sys.stdout.flush()
output = process.communicate()[0]
exitCode = process.returncode
if (exitCode == 0):
return output
else:
raise Exception(command, exitCode, output)
You can invoke it like this:
exec_long_running_proc(command = "hive", args=["-f", hql_path])
A: Here are my two cents: In my view, this is the best practice when dealing with external commands...
These are the return values from the execute method...
pass, stdout, stderr = execute(["ls","-la"],"/home/user/desktop")
This is the execute method...
def execute(cmdArray,workingDir):
stdout = ''
stderr = ''
try:
try:
process = subprocess.Popen(cmdArray,cwd=workingDir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
except OSError:
return [False, '', 'ERROR : command(' + ' '.join(cmdArray) + ') could not get executed!']
for line in iter(process.stdout.readline, b''):
try:
echoLine = line.decode("utf-8")
except:
echoLine = str(line)
stdout += echoLine
for line in iter(process.stderr.readline, b''):
try:
echoLine = line.decode("utf-8")
except:
echoLine = str(line)
stderr += echoLine
except (KeyboardInterrupt,SystemExit) as err:
return [False,'',str(err)]
process.stdout.close()
returnCode = process.wait()
if returnCode != 0 or stderr != '':
return [False, stdout, stderr]
else:
return [True, stdout, stderr]
A: Just to add to the discussion, if you include using a Python console, you can call external commands from IPython. While in the IPython prompt, you can call shell commands by prefixing '!'. You can also combine Python code with the shell, and assign the output of shell scripts to Python variables.
For instance:
In [9]: mylist = !ls
In [10]: mylist
Out[10]:
['file1',
'file2',
'file3',]
A: I wrote a small library to help with this use case:
https://pypi.org/project/citizenshell/
It can be installed using
pip install citizenshell
And then used as follows:
from citizenshell import sh
assert sh("echo Hello World") == "Hello World"
You can separate standard output from standard error and extract the exit code as follows:
result = sh(">&2 echo error && echo output && exit 13")
assert result.stdout() == ["output"]
assert result.stderr() == ["error"]
assert result.exit_code() == 13
And the cool thing is that you don't have to wait for the underlying shell to exit before starting processing the output:
for line in sh("for i in 1 2 3 4; do echo -n 'It is '; date +%H:%M:%S; sleep 1; done", wait=False)
print ">>>", line + "!"
will print the lines as they are available thanks to the wait=False
>>> It is 14:24:52!
>>> It is 14:24:53!
>>> It is 14:24:54!
>>> It is 14:24:55!
More examples can be found at https://github.com/meuter/citizenshell
A: Calling an external command in Python
A simple way to call an external command is using os.system(...). And this function returns the exit value of the command. But the drawback is we won't get stdout and stderr.
ret = os.system('some_cmd.sh')
if ret != 0 :
print 'some_cmd.sh execution returned failure'
Calling an external command in Python in background
subprocess.Popen provides more flexibility for running an external command rather than using os.system. We can start a command in the background and wait for it to finish. And after that we can get the stdout and stderr.
proc = subprocess.Popen(["./some_cmd.sh"], stdout=subprocess.PIPE)
print 'waiting for ' + str(proc.pid)
proc.wait()
print 'some_cmd.sh execution finished'
(out, err) = proc.communicate()
print 'some_cmd.sh output : ' + out
Calling a long running external command in Python in the background and stop after some time
We can even start a long running process in the background using subprocess.Popen and kill it after sometime once its task is done.
proc = subprocess.Popen(["./some_long_run_cmd.sh"], stdout=subprocess.PIPE)
# Do something else
# Now some_long_run_cmd.sh exeuction is no longer needed, so kill it
os.system('kill -15 ' + str(proc.pid))
print 'Output : ' proc.communicate()[0]
A: Sultan is a recent-ish package meant for this purpose. It provides some niceties around managing user privileges and adding helpful error messages.
from sultan.api import Sultan
with Sultan.load(sudo=True, hostname="myserver.com") as sultan:
sultan.yum("install -y tree").run()
A: Here is a Python script that will run the command on Ubuntu, while also showing the logs in real-time:
command = 'your command here'
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
output = process.stdout.readline().decode()
if output == '' and process.poll() is not None:
break
if output:
print(output.strip())
rc = process.poll()
if rc == 0:
print("Command succeeded.")
else:
print("Command failed.")
A: I use this for Python 3.6+:
import subprocess
def execute(cmd):
"""
Purpose : To execute a command and return exit status
Argument : cmd - command to execute
Return : result, exit_code
"""
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(result, error) = process.communicate()
rc = process.wait()
if rc != 0:
print ("Error: failed to execute command: ", cmd)
print (error.rstrip().decode("utf-8"))
return result.rstrip().decode("utf-8"), serror.rstrip().decode("utf-8")
# def
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5919"
}
|
Q: How to hide complete volume? Using Windows Server 2003 in a multi-user environment (via Remote Desktop, using it as an application server), how to mount a (preferably encrypted) volume in a way, that won't show up on any other user's desktop?
Tried, and failed approaches:
*
*tweaking user rights -display of mounted volume can not be changed.
*Bestcrypt / truecrypt. Both of them displays the volume for a local administrator
A: You're going to be hard-pressed to find a solution for your exact problem. Drive mount points aren't stored on the user level (afaik). There are a couple of workarounds that you can use that aren't guaranteed to be secure:
*
*hide access to certain drive letters based on group policy. Not very secure, easy to workaround.
*Don't mount a seperate volume: use NTFS encryption and simply set security permissions on certain folders.
Is there any particualr reason it has to be an entire drive? If you're trying to avoid allowing the local-admin having rights to a local drive, you're pretty much out of luck unless you use a third-party-probably-going-to-fail-horribly solution. You can jury-rig something with Group Policy to disallow local admin access, but it's going to be hard and error prone.
If your desired goal is to have separate folders (or volumes) that other users cannot access, store the files on a remote server. That way local administrators on the application server cannot arbitrarily access other peoples folders. (Unless they have Domain Admin or Enterprise Admin rights) You can set up a single big network drive and have different user folders on it, each encrypted using NTFS/other solution and only have read/write rights for that single user.
A: There's a key in the Registry that's used to hide mapped drives.
If you want to stop any combination of drives appearing in My Computer
Add the Binary Value of 'NoDrives' in the registry at
"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer"
Here is the table of all the values (Note that you can add up values to hide multiple drives, also the value is binary type but must be entered in hexadecimal, so if you add up a few drives, get ready for a little hex math. ) :
A 1 00 00 00
B 2 00 00 00
C 4 00 00 00
D 8 00 00 00
E 16 00 00 00
F 32 00 00 00
G 64 00 00 00
H 128 00 00 00
I 00 1 00 00
J 00 2 00 00
K 00 4 00 00
L 00 8 00 00
M 00 16 00 00
N 00 32 00 00
O 00 64 00 00
P 00 128 00 00
Q 00 00 1 00
R 00 00 2 00
S 00 00 4 00
T 00 00 8 00
U 00 00 16 00
V 00 00 32 00
W 00 00 64 00
X 00 00 128 00
Y 00 00 00 1
Z 00 00 00 2
A: Even if the drive letters are hidden - the volumes are still accessible unless you change ACLs on the filesystem itself - why is this so unpalatable?
A: NTFS supports mounting volumes inside directories.
Example - instead of mounting an external drive as D:, you can mount it under C:\mountedVolumes\externalHardDrive
You can then use ACL's on the parent folder (mountedVolumes) to prevent users other than yourself from accessing it. If they can't get into the folder, they can't get into the drive, or see that it's there. It just looks like a folder they can't open.
Note: This assumes that you have administrative rights (at least for when you first set this up), and that other people don't (so they can't just take ownership of mountedVolumes and go into the drive anyway)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do you manage .NET app.config files for large applications? Suppose a large composite application built on several foundation components packaged in their own assemblies: (database reading, protocol handlers, etc.). For some deployments, this can include over 20 assemblies. Each of these assemblies has settings or configuration information. Our team tends to like the VS settings editor (and the easy-to-use code it generates!), and the application vs. user distinction meets most of our needs.
BUT....
It is very tedious to copy & paste the many configuration sections into our application's .xml. Furthermore, for shared components that tend to have similar configurations across applications, this means we need to maintain duplicate settings in multiple .config files.
Microsoft's EntLib solves this problem with an external tool to generate the monster .config file, but this feels klunky as well.
What techniques do you use to manage large .NET .config files with sections from multiple shared assemblies? Some kind of include mechanism? Custom configuration readers?
FOLLOWUP:
Will's answer was exactly what I was getting at, and looks elegant for flat key/value pair sections. Is there a way to combine this approach with custom configuration sections ?
Thanks also for the suggestions about managing different .configs for different build targets. That's also quite useful.
Dave
A: My preferred method is to use MSBuild, if you right click on a project and click 'unload' a new menu option will pop up that says 'edit '. Select that and it'll open up the project file so you can edit it, scroll down until you find a commented out section that is called "AfterBuild".
You can then add something like:
<Target Name="AfterBuild">
<Delete Files="$(TargetDir)$(TargetFileName).config" />
<Copy SourceFiles="$(ProjectDir)$(Configuration).config" DestinationFiles="$(TargetDir)$(TargetFileName).config" />
</Target>
This will replace the application config with one named [Release|Debug]app.exe.config. So you can maintain separate configurations depending on how the project is built.
But a quick and dirty option (if you don't want to play with msbuild) is to just maintain separate config files and then define which one you want to include, like this:
<appSettings configSource="Config\appSettingsDebug.config"/>
<roleManager configSource="Config\roleManagerDebug.config"/>
And if you are doing an asp.net application, microsoft provides a great utility called "Web Deployment Projects" that will allow you to manage all of this easily, click here
A: A great way to manage large sets of configuration is to create custom configuration sections. Phil Haack discusses this very nicely in this article Custom configuration sections in 3 easy steps
A: You use one master config file that points to other config files. Here's an example of how to do this.
In case the link rots, what you do is specify the configSource for a particular configuration section. This allows you to define that particular section within a separate file.
<pages configSource="pages.config"/>
which implies that there is a file called "pages.config" within the same directory that contains the entire <pages /> node tree.
A: Set up build configurations for each of your deployment/testing environment and use separate config files based on each build configuration.
ScottGu has a nice post about this and it works great. The only quirk we have is that we need to make sure that the config files (web.config) are checked out for edit from TFS before each build so that it can be copied over.
A: We created an AssemblySettingsConfig class that acts like ConfigurationManager, but loads a .config for each individual assembly. So the application has a .config, and any DLLs it references have their own .config files. Has worked out well so far.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: naming columns in excel with Complex sql I’m trying to run this SQL using get external.
It works, but when I try to rename the sub-queries or anything for that matter it remove it.
I tried as, as and the name in '', as then the name in "",
and the same with space. What is the right way to do that?
Relevant SQL:
SELECT list_name, app_name,
(SELECT fname + ' ' + lname
FROM dbo.d_agent_define map
WHERE map.agent_id = tac.agent_id) as agent_login,
input, CONVERT(varchar,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970'))
FROM dbo.maps_report_list list
JOIN dbo.report_tac_agent tac ON (tac.list_id = list.list_id)
WHERE input = 'SYS_ERR'
AND app_name = 'CHARLOTT'
AND convert(VARCHAR,DATEADD(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008'
AND list_name LIKE 'NRBAD%'
ORDER BY agent_login,CONVERT(VARCHAR,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970'))
A: You could get rid of your dbo.d_agent_define subquery and just add in a join to the agent define table.
Would this code work?
select list_name, app_name,
map.fname + ' ' + map.lname as agent_login,
input,
convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970')) as tac_seconds
from dbo.maps_report_list list
join dbo.report_tac_agent tac
on (tac.list_id = list.list_id)
join dbo.d_agent_define map
on (map.agent_id = tac.agent_id)
where input = 'SYS_ERR'
and app_name = 'CHARLOTT'
and convert(varchar,dateadd(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008'
and list_name LIKE 'NRBAD%'
order by agent_login,convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970'))
Note that I named your dateadd column because it did not have a name. I also tried to keep your convention of how you do a join. There are a few things that I would do different with this query to make it more readable, but I only focused on getting rid of the subquery problem.
I did not do this, but I would recommend that you qualify all of your columns with the table from which you are getting them.
A: To remove the sub query in the SELECT statement I suggest the following:
SELECT list_name, app_name, map.fname + ' ' + map.lname as agent_login, input, convert(varchar,dateadd(ss, TAC_BEG_tstamp, '01/01/1970))
FROM dbo.maps_report_list inner join
(dbo.report_tac_agent as tac inner join dbo.d_agent_define as map ON (tac.agent_id=map.agent_id)) ON list.list_id = tac.list_id
WHERE input = 'SYS_ERR' and app_name = 'CHARLOTT' and convert(varchar,dateadd(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008'
and list_name LIKE 'NRBAD%' order by agent_login,convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970'))
I used parentheses to create the inner join between dbo.report_tac_agent and dbo.d_agent_define first. This is now a set of join data.
The combination of those tables are then joined to your list table, which I am assuming is the driving table here. If I am understand what you are trying to do with your sub select, this should work for you.
As stated by the other poster you should use table names on your columns (e.g. map.fname), it just makes things easy to understand. I didn't in my example because I am note 100% sure which columns go with which tables. Please let me know if this doesn't do it for you and how the data it returns is wrong. That will make it easier to solve in needed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Perl: variable scope issue with CGI & DBI modules I've run into what appears to be a variable scope issue I haven't encountered before. I'm using Perl's CGI module and a call to DBI's do() method. Here's the code structure, simplified a bit:
use DBI;
use CGI qw(:cgi-lib);
&ReadParse;
my $dbh = DBI->connect(...............);
my $test = $in{test};
$dbh->do(qq{INSERT INTO events VALUES (?,?,?)},undef,$in{test},"$in{test}",$test);
The #1 placeholder variable evaluates as if it is uninitialized. The other two placeholder variables work.
The question: Why is the %in hash not available within the context of do(), unless I wrap it in double quotes (#2 placeholder) or reassign the value to a new variable (#3 placeholder)?
I think it's something to do with how the CGI module's ReadParse() function assigns scope to the %in hash, but I don't know Perl scoping well enough to understand why %in is available at the top level but not from within my do() statement.
If someone does understand the scoping issue, is there a better way to handle it? Wrapping all the %in references in double quotes seems a little messy. Creating new variables for each query parameter isn't realistic.
Just to be clear, my question is about the variable scoping issue. I realize that ReadParse() isn't the recommended method to grab query params with CGI.
I'm using Perl 5.8.8, CGI 3.20, and DBI 1.52. Thank you in advance to anyone reading this.
@Pi & @Bob, thanks for the suggestions. Pre-declaring the scope for %in has no effect (and I always use strict). The result is the same as before: in the db, col1 is null while cols 2 & 3 are set to the expected value.
For reference, here's the ReadParse function (see below). It's a standard function that's part of CGI.pm. The way I understand it, I'm not meant to initialize the %in hash (other than satisfying strict) for purposes of setting scope, since the function appears to me to handle that:
sub ReadParse {
local(*in);
if (@_) {
*in = $_[0];
} else {
my $pkg = caller();
*in=*{"${pkg}::in"};
}
tie(%in,CGI);
return scalar(keys %in);
}
I guess my question is what is the best way to get the %in hash within the context of do()? Thanks again! I hope this is the right way to provide additional info to my original question.
@Dan: I hear ya regarding the &ReadParse syntax. I'd normally use CGI::ReadParse() but in this case I thought it was best to stick to how the CGI.pm documentation has it exactly.
A: It doesn't actually look like you're using it as described in the docs:
https://metacpan.org/pod/CGI#COMPATIBILITY-WITH-CGI-LIB.PL
If you must use it, then CGI::ReadParse(); seems more sensible and less crufty syntax. Although I can't see it making much difference in this situation, but then it is a tied variable, so who the hell knows what it's doing ;)
Is there a particular reason you can't use the more-common $cgi->param('foo') syntax? It's a little bit cleaner, and filths up your namespace in a considerably more predictable manner..
A: use strict;. Always.
Try declaring
our %in;
and seeing if that helps. Failing that, strict may produce a more useful error.
A: I don't know what's wrong, but I can tell you some things that aren't:
*
*It's not a scoping issue. If it were then none of the instances of $in{test} would work.
*It's not the archaic & calling syntax. (It's not "right" but it's harmless in this case.)
ReadParse is a nasty bit of code. It munges the symbol table to create the global variable %in in the calling package. What's worse is that it's a tied variable, so accessing it could (theoretically) do anything. Looking at the source code for CGI.pm, the FETCH method just invokes the params() method to get the data. I have no idea why the fetch in the $dbh->do() isn't working.
A: Firstly, that is not in the context/scope of do. It is still in the context of main or global. You dont leave context until you enter {} in some way relating to subroutines or different 'classes' in perl. Within () parens you are not leaving scope.
The sample you gave us is of an uninitialized hash and as Pi has suggested, using strict will certainly keep those from occuring.
Can you give us a more representative example of your code? Where are you setting %IN and how?
A: Something's very broken there. Perl's scoping is relatively simple, and you're unlikely to stumble upon anything odd like that unless you're doing something daft. As has been suggested, switch on the strict pragma (and warnings, too. In fact you should be using both anyway).
It's pretty hard to tell what's going on without being able to see how %in is defined (is it something to do with that nasty-looking ReadParse call? why are you calling it with the leading &, btw? that syntax has been considered dead and gone for a long time). I suggest posting a bit more code, so we can see what's going on..
A: What version of DBI are you using? From looking at the DBI changelog it appears that versions prior to 1.00 didn't support the attribute argument. I suspect that the "uninitialized" $in{test} is actually the undef that you're passing to $dbh->do().
A: From the example you gave, this is not a scoping issue, or none of the parameters would work.
Looks like DBI (or a DBD, not sure where bind parameters are used) isn't honoring tie magic.
The workaround would be to stringize or copy what you pass to it, like your second and third parameters do.
A simple test using SQLite and DBI 1.53 shows it working ok:
$ perl -MDBI -we'sub TIEHASH { bless {} } sub FETCH { "42" } tie %x, "main" or die; my $dbh = DBI->connect("dbi:SQLite:dbname=dbfile","",""); $dbh->do("create table foo (bar char(80))"); $dbh->do("insert into foo values (?)", undef, $x{foo}); print "got: " . $dbh->selectrow_array("select bar from foo") . "\n"; $dbh->do("drop table foo")'
got: 42
Care to share what database you are using?
A: Per the DBI documentation: Binding a tied variable doesn't work, currently.
DBI is pretty complicated under the hood, and unfortunately goes through some gyrations to be efficient that are causing your problem. I agree with everyone else who says to get rid of the ugly old cgi-lib style code. It's unpleasant enough to do CGI without a nice framework (go Catalyst), let alone something that's been obsolete for a decade.
A: Okay, try this:
use CGI;
my %in;
CGI::ReadParse(\%in);
That might help as it's actually using a variable that you've declared, and therefore can control the scope of (plus it'll let you use strict without other nastiness that could be muddying the waters)
A: As this is starting to look like a tie() problem, try the following experiment. Save this as a foo.pl and run it as perl foo.pl "x=1"
use CGI;
CGI::ReadParse();
p($in{x}, "$in{x}");
sub p { my @a = @_; print "@a\n" }
It should print 1 1. If it doesn't, we've found the culprit.
A: I just tried your test codce from http://www.carcomplaints.com/test/test.pl.txt, and it works right away on my computer, no problems. I get three values as expected. I didn't run it as CGI, but using:
...
use CGI qw/-debug/;
...
I write a variable on the console (test=test) and your scripts inserts without a problem.
If however your leave this out, tt will insert an empty string and two NULLs. This is a because you interpolate a value into a string. This will makes a string with value of $in{test} which is undef at the moment. undef stringifies to an empty string, which is what is inserted into database.
A: Try this
%in = ReadParse();
but i doubt that. Are you trying to get query parameters or something?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to implement closures without gc? I'm designing a language. First, I want to decide what code to generate. The language will have lexical closures and prototype based inheritance similar to javascript. But I'm not a fan of gc and try to avoid as much as possible. So the question: Is there an elegant way to implement closures without resorting to allocate the stack frame on the heap and leave it to garbage collector?
My first thoughts:
*
*Use reference counting and garbage collect the cycles (I don't really like this)
*Use spaghetti stack (looks very inefficient)
*Limit forming of closures to some contexts such a way that, I can get away with a return address stack and a locals' stack.
I won't use a high level language or follow any call conventions, so I can smash the stack as much as I like.
(Edit: I know reference counting is a form of garbage collection but I am using gc in its more common meaning)
A: This thread might help, although some of the answers here reflect answers there already.
One poster makes a good point:
It seems that you want garbage collection for closures
"in the absence of true garbage collection". Note that
closures can be used to implement cons cells. So your question
seem to be about garbage collection "in the absence of true
garbage collection" -- there is rich related literature.
Restricting problem to closures does not really change it.
So the answer is: no, there is no elegant way to have closures and no real GC.
The best you can do is some hacking to restrict your closures to a particular type of closure. All this is needless if you have a proper GC.
So, my question reflects some of the other ones here - why do you not want to implement GC? A simple mark+sweep or stop+copy takes about 2-300 lines of (Scheme) code, and isn't really that bad in terms of programming effort. In terms of making your programs slower:
*
*You can implement a more complex GC which has better performance.
*Just think of all the memory leaks programs in your language won't suffer from.
*Coding with a GC available is a blessing. (Think C#, Java, Python, Perl, etc... vs. C++ or C).
A: I understand that I'm very late, but I stumbled upon this question by accident.
I believe that full support of closures indeed requires GC, but in some special cases stack allocation is safe. Determining these special cases requires some escape analysis. I suggest that you take a look at the BitC language papers, such as Closure Implementation in BitC. (Although I doubt whether the papers reflect the current plans.) The designers of BitC had the same problem you do. They decided to implement a special non-collecting mode for the compiler, which denies all closures that might escape. If turned on, it will restrict the language significantly. However, the feature is not implemented yet.
I'd advise you to use a collector - it's the most elegant way. You should also consider that a well-built garbage collector allocates memory faster than malloc does. The BitC folks really do value performance and they still think that GC is fine even for the most parts of their operating system, Coyotos. You can migitate the downsides by simple means:
*
*create only a minimal amount of garbage
*let the programmer control the collector
*optimize stack/heap use by escape analysis
*use an incremental or concurrent collector
*if somehow possible, divide the heap like Erlang does
Many fear garbage collectors because of their experiences with Java. Java has a fantastic collector, but applications written in Java have performance problems because of the sheer amount of garbage generated. In addition, a bloated runtime and fancy JIT compilation is not really a good idea for desktop applications because of the longer startup and response times.
A: The C++ 0x spec defines lambdas without garbage collection. In short, the spec allows non-deterministic behavior in cases where the lambda closure contains references which are no longer valid. For example (pseudo-syntax):
(int)=>int create_lambda(int a)
{
return { (int x) => x + a }
}
create_lambda(5)(4) // undefined result
The lambda in this example refers to a variable (a) which is allocated on the stack. However, that stack frame has been popped and is not necessarily available once the function returns. In this case, it would probably work and return 9 as a result (assuming sane compiler semantics), but there is no way to guarantee it.
If you are avoiding garbage collection, then I'm assuming that you also allow explicit heap vs. stack allocation and (probably) pointers. If that is the case, then you can do like C++ and just assume that developers using your language will be smart enough to spot the problem cases with lambdas and copy to the heap explicitly (just like you would if you were returning a value synthesized within a function).
A:
Use reference counting and garbage collect the cycles (I don't really like this)
It's possible to design your language so there are no cycles: if you can only make new objects and not mutate old ones, and if making an object can't make a cycle, then cycles never appear. Erlang works essentially this way, though in practice it does use GC.
A: If you have the machinery for a precise copying GC, you could allocate on the stack initially and copy to the heap and update pointers if you discover at exit that a pointer to this stack frame has escaped. That way you only pay if you actually do capture a closure that includes this stack frame. Whether this helps or hurts depends on how often you use closures and how much they capture.
You might also look into C++0x's approach (N1968), though as one might expect from C++ it consists of counting on the programmer to specify what gets copied and what gets referenced, and if you get it wrong you just get invalid accesses.
A: Or just don't do GC at all. There can be situations where it's better to just forget the memory leak and let the process clean up after it when it's done.
Depending on your qualms about GC, you might be afraid of the periodic GC sweeps. In this case you could do a selective GC when an item falls out of scope or the pointer changes. I'm not sure how expensive this would be though.
@Allen
What good is a closure if you can't use them when the containing function exits? From what I understand that's the whole point of closures.
A: You could work with the assumption that all closures will be called eventually and exactly one time. Now, when the closure is called you can do the cleanup at the closure return.
How do you plan on dealing with returning objects? They have to be cleaned up at some point, which is the exact same problem with closures.
A:
So the question: Is there an elegant way to implement closures without resorting to allocate the stack frame on the heap and leave it to garbage collector?
GC is the only solution for the general case.
A: This would be a better question if you can explain what you're trying to avoid by not using GC. As I'm sure you're aware, most languages that provide lexical closures allocate them on the heap and allow them to retain references to variable bindings in the activation record that created them.
The only alternative to that approach that I'm aware of is what gcc uses for nested functions: create a trampoline for the function and allocate it on the stack. But as the gcc manual says:
If you try to call the nested function through its address after the containing function has exited, all hell will break loose. If you try to call it after a containing scope level has exited, and if it refers to some of the variables that are no longer in scope, you may be lucky, but it's not wise to take the risk. If, however, the nested function does not refer to anything that has gone out of scope, you should be safe.
Short version is, you have three main choices:
*
*allocate closures on the stack, and don't allow their use after their containing function exits.
*allocate closures on the heap, and use garbage collection of some kind.
*do original research, maybe starting from the region stuff that ML, Cyclone, etc. have.
A: Better late than never?
You might find this interesting: Differential Execution.
It's a little-known control stucture, and its primary use is in programming user interfaces, including ones that can change dynamically while in use. It is a significant alternative to the Model-View-Controller paradigm.
I mention it because one might think that such code would rely heavily on closures and garbage-collection, but a side effect of the control structure is that it eliminates both of those, at least in the UI code.
A: Create multiple stacks?
A: I've read that the last versions of ML use GC only sparingly
A: I guess if the process is very short, which means it cannot use much memory, then GC is unnecessary. The situation is analogous to worrying about stack overflow. Don't nest too deeply, and you cannot overflow; don't run too long, and you cannot need the GC. Cleaning up becomes a matter of simply reclaiming the large region that you pre-allocated. Even a longer process can be divided into smaller processes that have their own heaps pre-allocated. This would work well with event handlers, for example. It does not work well, if you are writing compiler; in that case, a GC is surely not much of a handicap.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Best C++ IDE or Editor for Windows What is the best C++ IDE or editor for using on Windows? I use Notepad++, but am missing IntelliSense from Visual Studio.
A: I think the debugger in Visual Studio (Express) is the killer thing that prevents me from using another IDE.
A: Visual Studio + Visual Assist X (http://www.wholetomato.com/)
A: There are some features in an IDE that are so transformative that you don't know how you lived without them. Integrated help was one. IntelliSense-like functionality was another. VS 6.0's Debug and Continue was absolutely killer. Visual Studio kicked butt for quite a while. Not bad, given the awful NeXTstep rip-off it all started as. (Or is it that memories of NeXTstep has faded until VS seems okay?)
Sure, there are much better EDITORS that VS, but as a complete package for Win32 development nothing seems to come close.
There are free Express editions now, but they seem pretty crippled.
I am quite enjoying Eclipse under Linux (and derivatives of it on Windows used in some FPGA vendor toolchains). I -really- don't like the lack of integrated MSDN-style help, though.
I think it's basically down to those two choices.
A: The Zeus editor has support for C/C++ and it also has a form of intellisensing.
It does its intellisensing using the tags information produced by ctags:
alt text http://www.zeusedit.com/images/_lookmain.jpg
A: Emacs. Xemacs works fine under Windows. For using it as an IDE, I recommend running it under Cygwin.
A: Visual studio is the most up to date and probably "best" free ide. Dev C++ is a little dated, and mingw doesn't compile most of boost, (except regex). Most of the other compilers are dated and fading, like mars and borland. But you can use whatever you like!
A: One that hasn't been mentioned is CodeLite, a powerful open-source, cross platform IDE. It has code completion amongst other features.
A: I've found the latest release of NetBeans, which includes C/C++ support, to be excellent.
http://www.netbeans.org/features/cpp/index.html
A: I will quote myself from this question:
https://stackoverflow.com/questions/780837/what-is-a-good-linux-ide-for-code-completion/917854#917854
Someone already said this before me,
but QtCreator is really good for Qt4
development.
Not only it has a really good code
completion support. It also knows a
little more about the code and what to
complete then I thought I needed. For
example it knows about slots/signals.
This means that connecting
slots/signals via code is much easier
then before.
The code editing is really nice. I
remember that when refactoring code,
(a few variables starting with
underscore) it remembered the cursor
position between lines and this made
the refactoring much easier. The code
indentation is smart enough to not get
in my way (KDevelop was configurable,
but QtCreator learns how I code. At
least it feels like it does).
Then there are the cool key
combinations. Most of the
functionality of the IDE can be
accessed using shortcuts. The
"control+k" thingie is a nice thing,
which some command line users would
like, but I am more GUI oriented. I
don't use it.
What I really like, is the split
window command. Yes, KDevelop3 does
it, but not as nice as QtCreator. My
favorite is control+e,3 which I use to
display the header and implementations
of my classes. Once again, the
navigation here is the best I have
seen (control+e,o).
It also has a nice SCM integration. I
usually use SVN, and quite frankly
it's not as good as I need: no
shortcut to diff the project, no diff
to commit the whole project, no option
to commit several files.
I also don't like the "total
integration of external tools". I
still like the external QtAssistant -
control+tab is easier to read large
articles. But.... when you define a
QString s, and 3 lines bellow you want
to read the interface of QString, you
put your cursor on "s" and press F1 -
the assistant comes as a sidebar with
QString's documentation. A huge
advantage.
Want to follow a definition? F2 to the
help. F4? Changes
header/implementation (yes, eclipse
does this better...).
The debugger is good. It's not as good
as VisualStudio but ... it has support
for Qt4 internals (you can see the
value of QString and QList!).
I can continue... but IMHO you will
need to give it a second and third
try. It really is a good product. Not
as flexible as Eclipse (hi
ryansstack), but it's a really small,
fast and young project. I stopped
developing QDevelop because I really
found what I was looking for.
ps: yes, I mean stopped developing
QDevelop. I was in the development
team.
My response is for Qt4 development only. Be warned.
A: I personally like Visual Studio combined with a third party add-in such as Visual Assist (http://www.wholetomato.com/). I've tried a few of the others and always ended up back with Visual Studio. Plus, Visual Studio is a widely used product in development industries, so having experience using it can only be a plus.
A: SlickEdit is very cool, and does support something like intellisense. At my current company I now use Visual Studio, and I've mostly gotten used to it - but there are still some SlickEdit features I miss.
A: As a complete all-in one package, Visual Studio 2008 is the best IDE for C++ development with Windows
A: Visual studio is great, but there are few tricks you can enhance it with. SonicFileFinder is one - helps you to search source files by partial match. You can map solution-tree to Alt+1, partial filename search to alt+2, and properties-window to alt+3. These are the three most used windows.
Another great tool that is ofter misunderstood is ctrl+shift+F shortcut for searching file contents. People dont use because it's so slow, but my advice is - deal with it. Searching the whole solution (or even all files in project folder) is only slow the first time you use it. Consequitive searches are as fast as jump-to-definition-feature.
A: I've tried SlickEdit, Notepad++, emacs, jEdit and Visual Studio. VS wins hands-down for Best Windows IDE.
jEdit is probably the best GUI cross-platform editor/almost-IDE, and emacs is probably the best terminal cross-platform editor/almost-IDE. The advantage with using these is that when you jump to a Mac or Linux box, you know how they work.
I tried Eclipse, but it ran like a no-legged dog it was so slow, so I didn't use it much. Maybe tech is better now, but eh.
A: With Intellisense, code folding, edit and continue, and a whole host of other features, Visual Studio is certainly the best IDE. However, for simple code editing, I often use UltraEdit. It has some great features not found in Visual Studio. One surprisingly useful feature is being able to select a column in the editor. You can find and replace within the column (useful for tabs vs. spaces wars...) delete the column, etc...
A: How about CodeBlocks, i find it so fine with me, especially the new 10.05 version.
A: The Eclipse CDT works well for me. It supports MinGW and Cygwin as targets. It also integrates well with CVS and Subversion.
The latest build, Ganymede, is available here.
A: Um, that's because Visual Studio is the best IDE. Come back to the darkside.
A: I would recommend C++Builder, from Embarcadero, for C++ work and there is also a free version available. If you prefer Visual Studio, download one of free express editions.
A: Here's another vote for Visual Studio. The debugger and Intellisense are definitely it's hallmarks. While other IDE's offer code-completion, I've often found them to be somewhat sluggish in this area for some reason (sluggish being a reference to the speed at which code-completion occurs and offers selections).
Other than VS, NetBeans is a good polished IDE and is updated on a very regular cycle.
A: I think it's largely a matter of taste, but I would recommend begginers to stick to a pure editor (vi, emacs...) instead of a full fledged IDE so they can figure out the whole toolchain that modern IDEs hide.
Just for the record, my weapon of choice is Emacs.
A: personally i dont like microsoft......I hate to admit that visual studio is the best IDE i ever use.....Netbeans is gud but drasticaly slow....other free IDEs are useless..
so people try to stick with VS....
A: M$ VS2008 is a better IDE for this.
A: The question says specifically IDE so I am guessing thats what you want. In that case, the main options are Visual Studio and Eclipse CDT as stated above. Of those, I personally prefer Eclipse. However, don't necessarily limit yourself to an IDE. I prefer to use vim as my editor and WinDbg as my debugger. For compilation, your project will probably dictate this. I currently use NMAke on the command line.
A: Use Visual Studio 2010. You can get the full version free with DreamSpark
A: There are the free "Express" versions of Visual Studio. Given that you like Visual Studio and that the "Express" editions are free, there is no reason to use any other editor.
A: I vote for Visual Studio, but it seems that C++ is treated like second class citizen (not the compiler and stuff but IDE support) compared to .NET languages like C#, but hopefully MS will do something about it by the next version of Visual Studio (new standard is coming and they promised that 10 should be new 6).
A: VIsual studio is by far the best IDE but you can also take a look at Code::Blocks
A: I prefer to use Microsoft Visual C++ express on windows. Though the 2008 ide is fine, the 2005 express has better support for many of the open projects which you might want to participate in. It's a pain to compile Firefox or a half life 2 mod on 2008. Also as a general tip when looking for software, I like to search wikipedia for "comparison of " In this case you would search comparison of Integrated Development Environments.
Hope that was helpful.
A: If you are interested in doing Qt development, then Qt Creator works fine and is free.
A: vi or gvim if you don't like terminals.
A: Personally, I have found Bloodshed's Dev-C++ to be very good. However, I do not recall an update in a very long time. I have, because of this, switched over to NetBeans for everything.
A: notepad++ or codeblocks for large projects
A: I think the anwser to this question depends on following question:
Do you want to develop cross-platform applications ?
If the anwser to this question is a clear YES, than you should start right away with some IDE that support cross-platform compilers like gcc/mingw.
Personally ive tried CodeBlocks and QtCreator beside VS...
If developing cross-platform software using Qt, surely QtCreator is the best choice.
Since QtCreator is still a quite new IDE, it still has some bugs... for example it's "intelli-sense" doesnt support namespace aliaces yet.. but i think it will evolve pretty fast, to a very good and complete IDE.
Codeblocks is a quite "small" IDE, but has everything an IDE needs. Still its "Intelli-Sense" (especially when dealing with meta-programming stuff like boost), and debugger is less powerful than VS's.
A: QT and NetBeans are the best cpp IDE's that I've ever used.
A: My favorite IDE was good old msdev.exe, a.k.a., Microsoft Development Studio, a.k.a., Microsoft Visual C++ 6. It was the last version of Visual C++ that didn't require me to get new hardware just to run it.
However, the compiler wasn't standard-compliant. Not even remotely.
A: Visual Studio BUT...
Go get ReSharper plugin from http://www.jetbrains.com/resharper/index.html. I'm a Java developer who uses IntelliJ and ReSharper gives a lot of the IntelliJ functionality to Visual Studio.
A: It looks like you did not mention Ultimate++ iDE.
It is quite fast. It is not perfect as Visual Studio but it has several useful features such as function list, it shows which function you are in,searches, multiple releases, package system, a gui designer a faster container library. Code completion...
A: I'm a bit surprised because nobody has mentioned Codeblocks: http://codeblocks.org
I think it is probably one of the best IDE's for C++. It is specially useful if you do multiplatform programming, since it is available for Linux, Mac and Windows, and it uses the same project files for all versions. It works perfectly with mingw, allowing you to even perform cross-compiling. It also directly supports wxWidgets visual development.
A: c++ IDE for MSWindows
1-Visual Studio
2-CodeBlocks (nighitly build)
others (devcpp, netbeans, eclips,...) just sucks, dont waste your time
A: I have used Netbeans for java, and it works great. Not sure how it works with C++, though.
A: Dev-C++ is a complete stand alone debugger compiler and linker, and also offers "IntelliSense". If you want to break away from VS (that also includes VS express) i suggest using this tool.
A: Ultimate++ if you want to program for both Linux and C++ also you have the choice to choose your compiler.
A: Dev C++ is also a nice IDE. It's not so user friendly, but it's usefull.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "74"
}
|
Q: Whats a good way to trim the GUI of a ASP.NET website? I've been trimming the UI of our website by doing the following in the onload event of that control:
btnDelete.isVisible = user.IsInRole("can delete");
This has become very tedious because there are so many controls to check again and again. As soon as I get it all working, designers request to change the UI and then it starts all over.
Any suggestions?
A: One simple suggestion would be to group controls into panels based on access rights
A: Something I have done before has been to create a custom page class (Actually, I do this part on every project) that each ASP.NET Page inherits.
This page class contains an IsAdmin property.
I then subclass the commonly used controls that may or may not be visible between modes into custom controls, and add code to check the Pages IsAdmin property.
All this is maybe an hour of work, but if you build pages using these controls, they manage their mode automatically.
Another fun timesaving tip is if you need to flip the page in and out of readonly mode. I added a property to the main base class, and then added a custom control that renders a textbox in one mode, and a label in the other.
Again, a little bit of time on the components, but then you can create a readonly version of the page in 2 lines of code...Very worth it.
A: You may be thinking of the situation in the wrong way. Instead of thinking of individual controls, think of it in terms of business roles and what they have the ability to do. This goes along with grouping controls into panels for access rights. For example, maybe only managers have the ability to delete and do other things, and you have a role for managers that you check. This way if there are changes, you can just move users into different roles. Business rules should not change drastically. There will always be tweaking as new positions gain more responsibility, but thinking of it in this way should minimize the number of changes to be made.
A: A quick and dirty option is using the asp:loginview controls, which can be wired up to user roles.
Not as elegant as the custom page class option suggested by Jonathan, and can be a bit of a performance hit if they are all over the page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Two Phase Commit/Shared Transaction The scenario is this
We have two applications A and B, both which are running in separate database (Oracle 9i ) transactions
Application A - inserts some data into the database, then calls Application B
Application B - inserts some data into the database, related (via foreign keys) to A's data. Returns an "ID" to Application A
Application A - uses ID to insert further data, including the ID from B
Now, because these are separate transactions, but both rely on data from each others transactions, we need to commit between the calls to each application. This of course makes it very difficult to rollback if anything goes wrong.
How would you approach this problem, with minimal refactoring of the code. Surely this kind of this is a common problem in the SOA world?
------ Update --------
I have not been able to find anything in Oracle 9i, however Oracle 11g provides DBMS_XA, which does exactly what I was after.
A: A few suggestions:
*
*Use Compensating transactions. Basically, you make it possible to undo the transaction you did earlier. The hard part is figuring out which transactions to rollback.
*Commit the data of applications A and B to the database using a flag indicating that it is only temporary. Then, after everything checks out fine, modify the flag to indicate that the data is final. During the night, run a batch job to flush out data that has not been finalized.
A: You could probably insert the data from Application A into a 'temporary' area so that Application B can do the inserts of both A and B without changing much in either appplications. It's not particularly elegant but it might do the trick.
In another scenario you could add a 'confirmation' flag field to your data which is updated after the entire process has run successfully. It if fails at one point, it might be easier to track down the records you need to rollback (in effect, delete).
A: You have three options:
*
*Redesign the application so that you don't have two different processes (both with database connections) writing to the database and roll it into a single app.
*Create application C that handles all the database transactions for A and B.
*Roll your own two phase commit. Application C acts as the coordinator. C signals A and B to ask if they're ready to commit. A and B do their processing, and respond to C with either a "ready" or a "fail" reply (note that there should be a timeout on C to avoid an infinite wait if one process hangs or dies). If both reply ready then C tells them to commit. Otherwise it sends a rollback signal.
Note that you may run into issues with option 3 if app A is relying on foreign keys from app B (which you didn't state, so this may not be an issue). Oracle's read consistency would probably prevent this from being allowed, since app A's transaction will begin before app B. Just a warning.
A: I like both solutions presented, so I avoided posting this for a while. But you could also make an update to the main table, having saved the state of the affected rows in some cache before hand.
This could be combined with the two-tier (The traffic cop system Zathrus proposed)--because it really wouldn't be needed for neonski's solution of using a "sketchpad" table or tables. The drawback of this is that you would have to have your procs/logic consult the main table from the workarea or the workarea from the main table--or perhaps store your flag in the main table and set it back when you commit the data to the main table.
A lady on our team is designing something like that for our realtime system, using permanent work tables.
A: App_A =={0}=> database # App_A stores information for App_B
App_A ------> App_B # App_A starts App_B
App_B <={0}== database # App_B retrieves the information
App_B =={1}=> database # App_B stores more informaion
App_A <={2}== App_B # App_B returns 'ID' to App_A
App_A ={2,3}> database # App_A stores 'ID' and additional data
Is it just me or does it seem like Application B is essentially just a subroutine of A. I mean Application B doesn't do anything until A asks it, and Application A doesn't do anything until B returns an ID. Which means it makes little sense to have them in different applications, or even separate threads.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How do I recover a dropped stash in Git? I frequently use git stash and git stash pop to save and restore changes in my working tree. Yesterday, I had some changes in my working tree that I had stashed and popped, and then I made more changes to my working tree. I'd like to go back and review yesterday's stashed changes, but git stash pop appears to remove all references to the associated commit.
I know that if I use git stash then .git/refs/stash contains the reference of the commit used to create the stash. And .git/logs/refs/stash contains the whole stash. But those references are gone after git stash pop. I know that the commit is still in my repository somewhere, but I don't know what it was.
Is there an easy way to recover yesterday's stash commit reference?
A: I just constructed a command that helped me find my lost stash commit:
for ref in `find .git/objects | sed -e 's#.git/objects/##' | grep / | tr -d /`; do if [ `git cat-file -t $ref` = "commit" ]; then git show --summary $ref; fi; done | less
This lists all the objects in the .git/objects tree, locates the ones that are of type commit, then shows a summary of each one. From this point it was just a matter of looking through the commits to find an appropriate "WIP on work: 6a9bb2" ("work" is my branch, 619bb2 is a recent commit).
I note that if I use "git stash apply" instead of "git stash pop" I wouldn't have this problem, and if I use "git stash save message" then the commit might have been easier to find.
Update: With Nathan's idea, this becomes shorter:
for ref in `git fsck --unreachable | grep commit | cut -d' ' -f3`; do git show --summary $ref; done | less
A: This worked for me (in 2022) with recovering my accidently deleted stash in git from a windows environment.
These steps outline how to recover any deleted git stashes or branches (assuming it has not been permanently delete by garbage collection).
*
*Navigate to the directory where your project located.
*Enter the command: git fsck --no-reflogs | find "dangling commit"
*A list of hashes for dangling commits will appear. These will consist of branches and stashes that were deleted. Start with copy and pasting the hashes near the end of the list to find your stash or branch. For example, use the command: git log -1 [hash]
*If the corresponding hash matches what you are trying to recover, use the following command to restore it"
git stash apply [hash]
A: Windows PowerShell equivalent using gitk:
gitk --all $(git fsck --no-reflog | Select-String "(dangling commit )(.*)" | %{ $_.Line.Split(' ')[2] })
There is probably a more efficient way to do this in one pipe, but this does the job.
A: If you didn't close the terminal, just look at the output from git stash pop and you'll have the object ID of the dropped stash. It normally looks like this:
$ git stash pop
[...]
Dropped refs/stash@{0} (2ca03e22256be97f9e40f08e6d6773c7d41dbfd1)
(Note that git stash drop also produces the same line.)
To get that stash back, just run git branch tmp 2cae03e, and you'll get it as a branch. To convert this to a stash, run:
git stash apply tmp
git stash
Having it as a branch also allows you to manipulate it freely; for example, to cherry-pick it or merge it.
A: To see the commits in terminal, only filtering the ones we care about we can use:
git log --oneline --all --grep="^WIP on .*: [a-f0-9]\+" --grep="^On [^ ]*:" --grep="^index on [^ ]*:" $( env LANG=C git fsck --no-reflog | awk '/dangling commit/ {print $3}' )
This is based on Aristotle Pagaltzis answer.
A: git fsck --unreachable | grep commit should show the sha1, although the list it returns might be quite large. git show <sha1> will show if it is the commit you want.
git cherry-pick -m 1 <sha1> will merge the commit onto the current branch.
A: What I came here looking for is how to actually get the stash back, regardless of what I have checked out. In particular, I had stashed something, then checked out an older version, then poped it, but the stash was a no-op at that earlier time point, so the stash disappeared; I couldn't just do git stash to push it back on the stack. This worked for me:
$ git checkout somethingOld
$ git stash pop
...
nothing added to commit but untracked files present (use "git add" to track)
Dropped refs/stash@{0} (27f6bd8ba3c4a34f134e12fe69bf69c192f71179)
$ git checkout 27f6bd8ba3c
$ git reset HEAD^ # Make the working tree differ from the parent.
$ git stash # Put the stash back in the stack.
Saved working directory and index state WIP on (no branch): c2be516 Some message.
HEAD is now at c2be516 Some message.
$ git checkout somethingOld # Now we are back where we were.
In retrospect, I should have been using git stash apply not git stash pop. I was doing a bisect and had a little patch that I wanted to apply at every bisect step. Now I'm doing this:
$ git reset --hard; git bisect good; git stash apply
$ # Run tests
$ git reset --hard; git bisect bad; git stash apply
etc.
A: Recovered it by using following steps:
*
*Identify the deleted stash hash code:
gitk --all $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' )
*Cherry Pick the Stash:
git cherry-pick -m 1 $stash_hash_code
*Resolve Conflicts if any using:
git mergetool
Additionally you might be having issues with commit message if you are using gerrit. Please Stash your changes before following next alternatives:
*
*Use hard reset to previous commit and then recommit this change.
*You may also stash the change, rebase and recommit.
A: If you want to restash a lost stash, you need to find the hash of your lost stash first.
As Aristotle Pagaltzis suggested a git fsck should help you.
Personally I use my log-all alias which show me every commit (recoverable commits) to have a better view of the situation :
git log --graph --decorate --pretty=oneline --abbrev-commit --all $(git fsck --no-reflogs | grep commit | cut -d' ' -f3)
You can do an even faster search if you're looking only for "WIP on" messages.
Once you know your sha1, you simply change your stash reflog to add the old stash :
git update-ref refs/stash ed6721d
You'll probably prefer to have an associated message so a -m
git update-ref -m "$(git log -1 --pretty=format:'%s' ed6721d)" refs/stash ed6721d
And you'll even want to use this as an alias :
restash = !git update-ref -m $(git log -1 --pretty=format:'%s' $1) refs/stash $1
A: Once you know the hash of the stash commit you dropped, you can apply it as a stash:
git stash apply $stash_hash
Or, you can create a separate branch for it with
git branch recovered $stash_hash
After that, you can do whatever you want with all the normal tools. When you’re done, just blow the branch away.
Finding the hash
If you have only just popped it and the terminal is still open, you will still have the hash value printed by git stash pop on screen (thanks, Dolda).
Otherwise, you can find it using this for Linux, Unix or Git Bash for Windows:
git fsck --no-reflog | awk '/dangling commit/ {print $3}'
...or using PowerShell for Windows:
git fsck --no-reflog | select-string 'dangling commit' | foreach { $_.ToString().Split(" ")[2] }
This will show you all the commits at the tips of your commit graph which are no longer referenced from any branch or tag – every lost commit, including every stash commit you’ve ever created, will be somewhere in that graph.
The easiest way to find the stash commit you want is probably to pass that list to gitk:
gitk --all $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' )
...or see the answer from emragins if using PowerShell for Windows.
This will launch a repository browser showing you every single commit in the repository ever, regardless of whether it is reachable or not.
You can replace gitk there with something like git log --graph --oneline --decorate if you prefer a nice graph on the console over a separate GUI app.
To spot stash commits, look for commit messages of this form:
WIP on somebranch: commithash Some old commit message
Note: The commit message will only be in this form (starting with "WIP on") if you did not supply a message when you did git stash.
A: Just wanted to mention this addition to the accepted solution. It wasn't immediately obvious to me the first time I tried this method (maybe it should have been), but to apply the stash from the hash value, just use "git stash apply ":
$ git stash apply ad38abbf76e26c803b27a6079348192d32f52219
When I was new to git, this wasn't clear to me, and I was trying different combinations of "git show", "git apply", "patch", etc.
A: My favorite is this one-liner:
git log --oneline $( git fsck --no-reflogs | awk '/dangling commit/ {print $3}' )
This is basically the same idea as this answer but much shorter. Of course, you can still add --graph to get a tree-like display.
When you have found the commit in the list, apply with
git stash apply THE_COMMIT_HASH_FOUND
For me, using --no-reflogs did reveal the lost stash entry, but --unreachable (as found in many other answers) did not.
Run it on git bash when you are under Windows.
Credits: The details of the above commands are taken from https://gist.github.com/joseluisq/7f0f1402f05c45bac10814a9e38f81bf
A: You can list all unreachable commits by writing this command in terminal -
git fsck --unreachable
Check unreachable commit hash -
git show hash
Finally apply if you find the stashed item -
git stash apply hash
A: I liked Aristotle's approach, but didn't like using GITK... as I'm used to using GIT from the command line.
Instead, I took the dangling commits and output the code to a DIFF file for review in my code editor.
git show $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' ) > ~/stash_recovery.diff
Now you can load up the resulting diff/txt file (its in your home folder) into your txt editor and see the actual code and resulting SHA.
Then just use
git stash apply ad38abbf76e26c803b27a6079348192d32f52219
A: To get the list of stashes that are still in your repository, but not reachable any more:
git fsck --unreachable | grep commit | cut -d" " -f3 | xargs git log --merges --no-walk --grep=WIP
If you gave a title to your stash, replace "WIP" in -grep=WIP at the end of the command with a part of your message, e.g. -grep=Tesselation.
The command is grepping for "WIP" because the default commit message for a stash is in the form WIP on mybranch: [previous-commit-hash] Message of the previous commit.
When you have found the commit, apply it with git stash apply <commit_hash>
A: In OSX with git v2.6.4, I just run git stash drop accidentally, then I found it by going trough below steps
If you know name of the stash then use:
$ git fsck --unreachable | grep commit | cut -c 20- | xargs git show | grep -B 6 -A 2 <name of the stash>
otherwise you will find ID from the result by manually with:
$ git fsck --unreachable | grep commit | cut -c 20- | xargs git show
Then when you find the commit-id just hit the git stash apply {commit-id}
Hope this helps someone quickly
A: To see only stash commits, where they attached, and what their contents are
result sample
Checking object directories: 100% (256/256), done.
2022-08-31 10:20:46 +0900 8d02f61 WIP on master: 243b594 add css
A favicon.ico
command
git fsck --dangling | awk '/dangling commit/ {print $3}' | xargs -L 1 git --no-pager show -s --format="%ct %h" | sort | awk '{print $2}' | { while read hash; do status=$(git stash show $hash --name-status 2>/dev/null); if (( $? == 0 )); then git show $hash -s --format="%C(green)%ci %C(yellow)%h %C(blue)%B"; echo "$status"; fi; done; }
*
*To see full hash, change %h to %H
*To reduce time, tail fsck like git fsck --dangling | tail -100 | awk ...
recover sample
A: Why do people ask this question? Because they don't yet know about or understand the reflog.
Most answers to this question give long commands with options almost nobody will remember. So people come into this question and copy paste whatever they think they need and forget it almost immediately after.
I would advise everyone with this question to just check the reflog (git reflog), not much more than that. Once you see that list of all commits there are a hundred ways to find out what commit you're looking for and to cherry-pick it or create a branch from it. In the process you'll have learned about the reflog and useful options to various basic git commands.
A: I couldn't get any of the answers to work on Windows in a simple command window (Windows 7 in my case). awk, grep and Select-string weren't recognized as commands. So I tried a different approach:
*
*first run: git fsck --unreachable | findstr "commit"
*copy the output to notepad
*find replace "unreachable commit" with start cmd /k git show
will look something like this:
start cmd /k git show 8506d235f935b92df65d58e7d75e9441220537a4
start cmd /k git show 44078733e1b36962571019126243782421fcd8ae
start cmd /k git show ec09069ec893db4ec1901f94eefc8dc606b1dbf1
start cmd /k git show d00aab9198e8b81d052d90720165e48b287c302e
*
*save as a .bat file and run it
*the script will open a bunch of command windows, showing each commit
*if you found the one you're looking for, run: git stash apply (your hash)
may not be the best solution, but worked for me
A: I want to add to the accepted solution another good way to go through all the changes, when you either don't have gitk available or no X for output.
git fsck --no-reflog | awk '/dangling commit/ {print $3}' > tmp_commits
for h in `cat tmp_commits`; do git show $h | less; done
Then you get all the diffs for those hashes displayed one after another. Press 'q' to get to the next diff.
A: The accepted answer by Aristotle will show all reachable commits, including non-stash-like commits. To filter out the noise:
git fsck --no-reflog | \
awk '/dangling commit/ {print $3}' | \
xargs git log --no-walk --format="%H" \
--grep="WIP on" --min-parents=3 --max-parents=3
This will only include commits which have exactly 3 parent commits (which a stash will have), and whose message includes "WIP on".
Keep in mind, that if you saved your stash with a message (e.g. git stash save "My newly created stash"), this will override the default "WIP on..." message.
You can display more information about each commit, e.g. display the commit message, or pass it to git stash show:
git fsck --no-reflog | \
awk '/dangling commit/ {print $3}' | \
xargs git log --no-walk --format="%H" \
--grep="WIP on" --min-parents=3 --max-parents=3 | \
xargs -n1 -I '{}' bash -c "\
git log -1 --format=medium --color=always '{}'; echo; \
git stash show --color=always '{}'; echo; echo" | \
less -R
A: Knowing the approximate file name and it's location, and was able to find dropped stash files grepping dangling commits for path
for i in $(git fsck --no-reflogs | awk '/dangling commit/ {print $3}'); do
if git log -5 --name-only -u $i | grep -q "<path-to-files>/.*<partial-file-name>.*"; then
echo "found something in commit $i";
fi;
done
A: You can follow the below process step by step:
1- use below to list all unreachable commits
git fsck --unreachable
2- to show unreachable commit hash by
git show hash
3- copy all log, you can see log like, unreachable blob, commit, tree.
4- apply git stash with log having commit hash
git stash apply [replace hash]
A: Not exactly an answer to get a stash but if the goal is to get uncommited changes that were first stashed and then popped in another branch but meant for both and done in the following way:
*
*Make changes in branch_a
*git stash
*Make branch_b from branch_a
*git stash apply
Then to restore the uncommited changes to branch_a:
*
*git checkout branch_a
*git merge branch_b
*git reset HEAD~1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2345"
}
|
Q: Is it possible to store and retrieve a boolean value in a varchar field using Java JDBC? quick question: my customer has a situation where he has his database with a varchar field and the corresponding jdbc code is storing/retrieving a boolean.
I guess that the boolean values false and true are going to be translated to "0" and "1" but I would like to have a confirmation of this (I can't find the precise behavior specification online, maybe it depends on each driver, Oracle in this case).
I know I could experiment by myself, but I want to have a try at stackoverflow.com!
Thanks for your answer,
Eric.
A: I agree with the answer that the semantics are highly database specific, which is why I think the important answer is that you shouldn't do this. A change in JDBC driver or something similar could cause the implicit behaviour to break.
Instead, If using raw JDBC, have the code take the boolean and convert it to an appropriate String ('true' or 'false' are obvious choices) and then set this value to the VARCHAR column. On read from the VARCHAR column do the reverse, throwing or handling the exception case where the String is not one of the boolean values as expected.
A: It works with MySQL, the table holds 0 for false and 1 for true.
The output:
123 => true
456 => false
The source code:
package com.lurz.jdbc;
import java.sql.*;
// Test using Varchar for Boolean
public class BoolTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/booltest", "booltest", "booltest");
conn.prepareStatement("create table booltest (id bigint, truefalse varchar(10));").execute();
PreparedStatement stmt = conn.prepareStatement("insert into booltest (id, truefalse) values (?, ?);");
stmt.setLong(1, (long)123);
stmt.setBoolean(2, true);
stmt.execute();
stmt.setLong(1, (long)456);
stmt.setBoolean(2, false);
stmt.execute();
ResultSet rs = conn.createStatement().executeQuery("select id, truefalse from booltest");
while (rs.next()) {
System.out.println(rs.getLong(1)+ " => " + rs.getBoolean(2));
}
}
}
A: Thanks for all your answers,
After a bit of experimentation I saw that Oracle was indeed using the values 0 and 1 to store boolean values in varchar2 columns without any mapping in the JDBC code.
That said, if I can give a bit of context, we're going to fix that situation where things would just work "by accident". I just wanted to know if, in the meantime, the application would blow up.
And, as I said, I wanted to see how effective the stackoverflow community was after having listened to the Joel/Jeff podcasts since the beginning!
It is indeed effective!
A: Unfortunately, BOOLEAN semantics are highly database-specific. I'm guessing that the Oracle driver is going to translate boolean values to a VARCHAR field into "true" and "false", rather than 0 and 1, but you should verify this yourself.
A: It is possible to use VARCHAR(2) for representing a Java Boolean in Oracle. However, I would advise against it and suggest you use a NUMBER(1) instead. If the Boolean column has an index on it and you use it in a WHERE clause Oracle will apply the to_number numeric function on it to turn the "0" into a 0 or the "1" into a 1. Application of that function negates the use of the index on that column and will cause you to incur a full table scan.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Windows workflow Can anyone explain what is windows workflow and how can we use in the work organization.
A: Windows Workflow Foundation is a fascinating concept. It allows you to create powerful applications (or just parts of them) using a combination of flowchart-like concepts and normal code.
The deeper value of this may not be immediately obvious. Say you're building a large e-commerce site. Over time, your workflows for processes such as fulfillment will change radically. The code will eventually become a horrid cludge of ideas shoehorned over old ideas. You will be forced to work up reams of documentation and in time it will become difficult to maintain.
So, workflow is ultimately about creating highly maintainable code with the idea that code will change. When you look at it, you're looking at a flowchart. Double-click on a node and it takes you to a code editor where you can write some business logic.
It's a lot more involved than that of course.
I have a book on this sitting on my desk right now. I am trying to determine whether the .NET implementation is ready for prime time or if it's still too new and complicated - and it is complicated, moreso than I expected.
At this point, I think the idea has the potential to be a game changer... We will see if the current generation is actually usable! The fact the Microsoft is not pushing it that hard is probably telling.
A: WF is a framework for creating workflows. It consists of a type of workflow (state machine or sequential), hosting different "activities" and logic controlling how application flow travels from one activity to another.
You can use it for describing business processes, from page flow in an ASP.NET application to the steps required to submit a vacation request.
Here's a great article about WF.
A: The Workflow Way: Understanding Windows Workflow Foundation
A: Windows Workflow Foundation puts the inner core concepts of development part right in front of you. So it becomes a little complex but a very powerful way of working and creating builds.
The basic Idea of development using the flowchart like concepts makes it very intuitive, it becomes very easy to trace the complete code without going through the code as it was previously done in traditional way of programming.
There are different other features of using workflow like parallel running of execution, drag and drop facilities of activities, using built-in activities as well as we can write our own custom activities and we can use those activities wherever we want in any other project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to import variable record length CSV file using SSIS? Has anyone been able to get a variable record length text file (CSV) into SQL Server via SSIS?
I have tried time and again to get a CSV file into a SQL Server table, using SSIS, where the input file has varying record lengths. For this question, the two different record lengths are 63 and 326 bytes. All record lengths will be imported into the same 326 byte width table.
There are over 1 million records to import.
I have no control of the creation of the import file.
I must use SSIS.
I have confirmed with MS that this has been reported as a bug.
I have tried several workarounds. Most have been where I try to write custom code to intercept the record and I cant seem to get that to work as I want.
A: I had a similar problem, and used custom code (Script Task), and a Script Component under the Data Flow tab.
I have a Flat File Source feeding into a Script Component. Inside there I use code to manipulate the incomming data and fix it up for the destination.
My issue was the provider was using '000000' as no date available, and another coloumn had a padding/trim issue.
A: You should have no problem importing this file. Just make sure when you create the Flat File connection manager, select Delimited format, then set SSIS column length to maximum file column length so it can accomodate any data.
It appears like you are using Fixed width format, which is not correct for CSV files (since you have variable length column), or maybe you've incorrectly set the column delimiter.
A: Same issue. In my case, the target CSV file has header & footer records with formats completely different than the body of the file; the header/footer are used to validate completeness of file processing (date/times, record counts, amount totals - "checksum" by any other name ...). This is a common format for files from "mainframe" environments, and though I haven't started on it yet, I expect to have to use scripting to strip off the header/footer, save the rest as a new file, process the new file, and then do the validation. Can't exactly expect MS to have that out-of-the box (but it sure would be nice, wouldn't it?).
A: You can write a script task using C# to iterate through each line and pad it with the proper amount of commas to pad the data out. This assumes, of course, that all of the data aligns with the proper columns.
I.e. as you read each record, you can "count" the number of commas. Then, just append X number of commas to the end of the record until it has the correct number of commas.
Excel has an issue that causes this kind of file to be created when converting to CSV.
If you can do this "by hand" the best way to solve this is to open the file in Excel, create a column at the "end" of the record, and fill it all the way down with 1s or some other character.
Nasty, but can be a quick solution.
If you don't have the ability to do this, you can do the same thing programmatically as described above.
A: Why can't you just import it as a test file and set the column delimeter to "," and the row delimeter to CRLF?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Using Merb for Facebook Application Since Rails is not multithreaded (yet), it seems like a threaded web framework would be a better choice for a Facebook application. (reason being is cuz each Rails process can only handle one request at a time, and facebook actions tend to be slow, because there is a lot of network communication between your app and facebook)
Has anyone used Merb to write a Facebook application? Is there a port of Facebooker (the Facebook plugin for Rails) to Merb?
A: We've used merb_facebooker in one of our projects (Rock the Vote), and it worked out pretty well. Testing Facebook apps is quite annoying, as you don't have control of the middleware, so watch out for your expectations of the FB API and make sure you validate as much of them as possible early in the development stages (not trying out all the things we needed to do with fbML early on brought a few headaches).
A: Behold, merb_facebooker.
In addition, if you want to use Facebooker directly (like for a desktop app,) just install the gem:
gem install facebooker
A: Have you looked at Starling? It's the server used by twitter to handle their messages. It's a persistent queue server that allows you to delegate jobs to workers.
A: You can run passenger on Apache which will start up as many Rails instances as it needs up to a certain limit (I think the default is 30). It will also kill them as required, so if you're not getting as many hits as you were 5 minutes ago, it will release the system resources back to the system.
Learn more about passenger at http://modrails.com
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Help with algorithm for merging vectors I need a very fast algorithm for the following task. I have already implemented several algorithms that complete it, but they're all too slow for the performance I need. It should be fast enough that the algorithm can be run at least 100,000 times a second on a modern CPU. It will be implemented in C++.
I am working with spans/ranges, a structure that has a start and an end coordinate on a line.
I have two vectors (dynamic arrays) of spans and I need to merge them. One vector is src and the other dst. The vectors are sorted by span start coordinates, and the spans do not overlap within one vector.
The spans in the src vector must be merged with the spans in the dst vector, such that the resulting vector is still sorted and has no overlaps. Ie. if overlaps are detected during the merging, the two spans are merged into one. (Merging two spans is just a matter of changing the coordinates in the structure.)
Now, there is one more catch, the spans in the src vector must be "widened" during the merge. This means that a constant will be added to the start and another (larger) constant to the end coordinate of every span in src. This means that after the src spans are widened they might overlap.
What I have arrived at so far is that it cannot be done fully in-place, some kind of temporary storage is needed. I think it should be doable in linear time over the number of elements of src and dst summed.
Any temporary storage can probably be shared between multiple runs of the algorithm.
The two primary approaches I have tried, which are too slow, are:
*
*Append all elements of src to dst, widening each element before appending it. Then run an in-place sort. Finally iterate over the resulting vector using a "read" and "write" pointer, with the read pointer running ahead of the write pointer, merging spans as they go. When all elements have been merged (the read pointer reaches end) dst is truncated.
*Create a temporary work-vector. Do a naive merge as described above by repeatedly picking the next element from either src or dst and merging into the work-vector. When done, copy the work-vector to dst, replacing it.
The first method has the problem that sorting is O((m+n)*log(m+n)) instead of O(m+n) and has somewhat overhead. It also means the dst vector has to grow much larger than it really needs.
The second has the primary problem of a lot of copying around and again allocation/deallocation of memory.
The data structures used for storing/managing the spans/vectors can be altered if you think that's needed.
Update: Forgot to say how large the datasets are. The most common cases are between 4 and 30 elements in either vector, and either dst is empty or there is a large amount of overlap between the spans in src and dst.
A: We know that the absolute best case runtime is O(m+n) this is due to the fact that you at least have to scan over all of the data in order to be able to merge the lists. Given this, your second method should give you that type of behavior.
Have you profiled your second method to find out what the bottlenecks are? It is quite possible that, depending on the amount of data you are talking about it is actually impossible to do what you want in the specified amount of time. One way to verify this is to do something simple like sum up all the start and end values of the spans in each vector in a loop, and time that. Basically here you are doing a minimal amount of work for each element in the vectors. This will provide you with a baseline for the best performance you can expect to get.
Beyond that you can avoid copying the vectors element by element by using the stl swap method, and you can preallocate the temp vector to a certain size in order to avoid triggering the expansion of the array when you are merging the elements.
You might consider using 2 vectors in your system and whenever you need to do a merge you merge into the unused vector, and then swap (this is similar to double buffering used in graphics). This way you don't have to reallocate the vectors every time you do the merge.
However, you are best off profiling first and finding out what your bottleneck is. If the allocations are minimal compared to the actual merging process than you need to figure out how to make that faster.
Some possible additional speedups could come from accessing the vectors raw data directly which avoids the bounds checks on each access the data.
A: How about the second method without repeated allocation--in other words, allocate your temporary vector once, and never allocate it again? Or, if the input vectors are small enough (But not constant size), just use alloca instead of malloc.
Also, in terms of speed, you may want to make sure that your code is using CMOV for the sorting, since if the code is actually branching for every single iteration of the mergesort:
if(src1[x] < src2[x])
dst[x] = src1[x];
else
dst[x] = src2[x];
The branch prediction will fail 50% of the time, which will have an enormous hit on performance. A conditional move will likely do much much better, so make sure the compiler is doing that, and if not, try to coax it into doing so.
A: The sort you mention in Approach 1 can be reduced to linear time (from log-linear as you describe it) because the two input lists are already sorted. Just perform the merge step of merge-sort. With an appropriate representation for the input span vectors (for example singly-linked lists) this can be done in-place.
http://en.wikipedia.org/wiki/Merge_sort
A: i don't think a strictly linear solution is possible, because widening the src vector spans may in the worst-case cause all of them to overlap (depending on the magnitude of the constant that you are adding)
the problem may be in the implementation, not in the algorithm; i would suggest profiling the code for your prior solutions to see where the time is spent
reasoning:
for a truly "modern" CPU like the Intel Core 2 Extreme QX9770 running at 3.2GHz, one can expect about 59,455 MIPS
for 100,000 vectors, you would have to process each vector in 594,550 instuctions. That's a LOT of instructions.
ref: wikipedia MIPS
in addition, note that adding a constant to the src vector spans does not de-sort them, so you can normalize the src vector spans independently, then merge them with the dst vector spans; this should reduce the workload of your original algorithm
A: 1 is right out - a full sort is slower than merging two sorted lists.
So you're looking at tweaking 2 (or something entirely new).
If you change the data structures to doubly linked lists, then you can merge them in constant working space.
Use a fixed-size heap allocator for the list nodes, both to reduce memory use per node and to improve the chance that the nodes are close together in memory, reducing page misses.
You might be able to find code online or in your favourite algorithm book to optimise a linked list merge. You'll want to customise this in order to do span coalescing at the same time as the list merge.
To optimise the merge, first note that for each run of values coming off the same side without one coming from the other side, you can insert the whole run into the dst list in one go, instead of inserting each node in turn. And you can save one write per insertion over a normal list operation, by leaving the end "dangling", knowing that you'll patch it up later. And provided that you don't do deletions anywhere else in your app, the list can be singly-linked, which means one write per node.
As for 10 microsecond runtime - kind of depends on n and m...
A: If your most recent implementation still isn't fast enough, you might end up having to look at alternative approaches.
What are you using the outputs of this function for?
A: I wrote a new container class just for this algorithm, tailored to the needs. This also gave me a chance to adjust other code around my program which got a little speed boost at the same time.
This is significantly faster than the old implementation using STL vectors, but which was otherwise basically the same thing. But while it's faster it's still not really fast enough... unfortunately.
Profiling doesn't reveal what is the real bottleneck any longer. The MSVC profiler seems to sometimes place the "blame" on the wrong calls (supposedly identical runs assign widely different running times) and most calls are getting coalesced into one big chink.
Looking at a disassembly of the generated code shows that there's a very large amount of jumps in the generated code, I think that might be the main reason behind the slowness now.
class SpanBuffer {
private:
int *data;
size_t allocated_size;
size_t count;
inline void EnsureSpace()
{
if (count == allocated_size)
Reserve(count*2);
}
public:
struct Span {
int start, end;
};
public:
SpanBuffer()
: data(0)
, allocated_size(24)
, count(0)
{
data = new int[allocated_size];
}
SpanBuffer(const SpanBuffer &src)
: data(0)
, allocated_size(src.allocated_size)
, count(src.count)
{
data = new int[allocated_size];
memcpy(data, src.data, sizeof(int)*count);
}
~SpanBuffer()
{
delete [] data;
}
inline void AddIntersection(int x)
{
EnsureSpace();
data[count++] = x;
}
inline void AddSpan(int s, int e)
{
assert((count & 1) == 0);
assert(s >= 0);
assert(e >= 0);
EnsureSpace();
data[count] = s;
data[count+1] = e;
count += 2;
}
inline void Clear()
{
count = 0;
}
inline size_t GetCount() const
{
return count;
}
inline int GetIntersection(size_t i) const
{
return data[i];
}
inline const Span * GetSpanIteratorBegin() const
{
assert((count & 1) == 0);
return reinterpret_cast<const Span *>(data);
}
inline Span * GetSpanIteratorBegin()
{
assert((count & 1) == 0);
return reinterpret_cast<Span *>(data);
}
inline const Span * GetSpanIteratorEnd() const
{
assert((count & 1) == 0);
return reinterpret_cast<const Span *>(data+count);
}
inline Span * GetSpanIteratorEnd()
{
assert((count & 1) == 0);
return reinterpret_cast<Span *>(data+count);
}
inline void MergeOrAddSpan(int s, int e)
{
assert((count & 1) == 0);
assert(s >= 0);
assert(e >= 0);
if (count == 0)
{
AddSpan(s, e);
return;
}
int *lastspan = data + count-2;
if (s > lastspan[1])
{
AddSpan(s, e);
}
else
{
if (s < lastspan[0])
lastspan[0] = s;
if (e > lastspan[1])
lastspan[1] = e;
}
}
inline void Reserve(size_t minsize)
{
if (minsize <= allocated_size)
return;
int *newdata = new int[minsize];
memcpy(newdata, data, sizeof(int)*count);
delete [] data;
data = newdata;
allocated_size = minsize;
}
inline void SortIntersections()
{
assert((count & 1) == 0);
std::sort(data, data+count, std::less<int>());
assert((count & 1) == 0);
}
inline void Swap(SpanBuffer &other)
{
std::swap(data, other.data);
std::swap(allocated_size, other.allocated_size);
std::swap(count, other.count);
}
};
struct ShapeWidener {
// How much to widen in the X direction
int widen_by;
// Half of width difference of src and dst (width of the border being produced)
int xofs;
// Temporary storage for OverlayScanline, so it doesn't need to reallocate for each call
SpanBuffer buffer;
inline void OverlayScanline(const SpanBuffer &src, SpanBuffer &dst);
ShapeWidener(int _xofs) : xofs(_xofs) { }
};
inline void ShapeWidener::OverlayScanline(const SpanBuffer &src, SpanBuffer &dst)
{
if (src.GetCount() == 0) return;
if (src.GetCount() + dst.GetCount() == 0) return;
assert((src.GetCount() & 1) == 0);
assert((dst.GetCount() & 1) == 0);
assert(buffer.GetCount() == 0);
dst.Swap(buffer);
const int widen_s = xofs - widen_by;
const int widen_e = xofs + widen_by;
size_t resta = src.GetCount()/2;
size_t restb = buffer.GetCount()/2;
const SpanBuffer::Span *spa = src.GetSpanIteratorBegin();
const SpanBuffer::Span *spb = buffer.GetSpanIteratorBegin();
while (resta > 0 || restb > 0)
{
if (restb == 0)
{
dst.MergeOrAddSpan(spa->start+widen_s, spa->end+widen_e);
--resta, ++spa;
}
else if (resta == 0)
{
dst.MergeOrAddSpan(spb->start, spb->end);
--restb, ++spb;
}
else if (spa->start < spb->start)
{
dst.MergeOrAddSpan(spa->start+widen_s, spa->end+widen_e);
--resta, ++spa;
}
else
{
dst.MergeOrAddSpan(spb->start, spb->end);
--restb, ++spb;
}
}
buffer.Clear();
}
A: I would always keep my vector of spans sorted. That makes implementing algorithms a LOT easier -- and possible to do in linear time.
OK, so I'd sort the spans based on:
*
*span minimum in increasing order
*then span maximum in decreasing order
You need to create a function to do that.
Then I'd use std::set_union to merge the vectors (you can merge more than one before continuing).
Then for each consecutive sets of spans with identical minimums, you keep the first and remove the rest (they're sub-spans of the first span).
Then you need to merge your spans. That should be pretty doable now and feasible in linear time.
OK, here's the trick now. Don't try to do this in-place. Use one or more temporary vectors (and reserve enough space ahead of time). Then at the end, call std::vector::swap to put the results in the input vector of your choice.
I hope that's enough to get you going.
A: What is your target system? Is it multi-core? If so you could consider multithreading this algorithm
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Reference app relative virtual paths in .css file Assume I have an "images" folder directory under the root of my application. How can I, from within a .css file, reference an image in this directory using an ASP.NET app relative path.
Example:
When in development, the path of ~/Images/Test.gif might resolve to /MyApp/Images/Test.gif while, in production, it might resolve to /Images/Test.gif (depending on the virtual directory for the application). I, obviously, want to avoid having to modify the .css file between environments.
I know you can use Page.ResolveClientUrl to inject a url into a control's Style collection dynamically at render time. I would like to avoid doing this.
A: In case you didn't know you could do this...
If you give a relative path to a resource in a CSS it's relative to the CSS file, not file including the CSS.
background-image: url(../images/test.gif);
So this might work for you.
A: Make you life easy, just put images used in your CSS in the /css/ folder alongside /css/style.css. Then when you reference your images, use relative paths (e.g. url(images/image.jpg)).
I still keep images that are displayed with a <img> in an /images/ folder. Photos for example are content, they are not part of the website's skin/theme. Thus, they do not belong in the /css/ folder.
A: Marcel Popescu's solution is using Request.ApplicationPath in the css file.
Never use Request.ApplicationPath - it is evil! Returns different results depending on the path!
Use the following instead.
background-image: url(<%= Page.ResolveUrl("~/images/bg_content.gif") %>);
A: Put your dynamic CSS in a user control in an .ascx file and then you do not need to run all your css files through the asp.net page processer.
<%@ Control %>
<style type="text/css>
div.content
{
background-image:(url(<%= Page.ResolveUrl("~/images/image.png") %>);
}
</style>
But the easiest way to solve the ~ problem is to not use a ~ at all. In Visual Studio, in Solution Explorer, right click your application, select Properties Window and change the Virtual Path to /.
A: Unfortunately Firefox has a stupid bug here... the paths are relative to the path of the page, instead of being relative to the position of the CSS file. Which means if you have pages in different positions in the tree (like having Default.aspx in the root and Information.aspx in the View folder) there's no way to have working relative paths. (IE will correctly solve the paths relative to the location of the CSS file.)
The only thing I could find is this comment on http://www.west-wind.com/weblog/posts/269.aspx but, to be honest, I haven't managed to make it work yet. If I do I'll edit this comment:
re: Making sense of ASP.Net Paths by
Russ Brooks February 25, 2006 @ 8:43
am
No one fully answered Brant's question
about the image paths inside the CSS
file itself. I've got the answer. The
question was, "How do we use
application-relative image paths
INSIDE the CSS file?" I have long been
frustrated by this very problem too,
so I just spent the last 3 hours
working out a solution.
The solution is to run your CSS files
through the ASPX page handler, then
use a small bit of server-side code in
each of the paths to output the root
application path. Ready?
*
*Add to web.config:
<compilation debug="true">
<!-- Run CSS files through the ASPX handler so we can write code in them. -->
<buildProviders>
<add extension=".css" type="System.Web.Compilation.PageBuildProvider" />
</buildProviders>
</compilation>
<httpHandlers>
<add path="*.css" verb="GET" type="System.Web.UI.PageHandlerFactory" validate="true" />
</httpHandlers>
*Inside your CSS, use the Request.ApplicationPath property
wherever a path exists, like this:
#content {
background: url(<%= Request.ApplicationPath
%>/images/bg_content.gif) repeat-y;
}
*.NET serves up ASPX pages with a MIME type of "text/html" by default,
consequently, your new server-side CSS
pages are served up with this MIME
type which causes non-IE browsers to
not read the CSS file correctly. We
need to override this to be
"text/css". Simply add this line as
the first line of your CSS file:
<%@ ContentType="text/css" %>
A: On Windows 7, IIS 7.5:
Not only do you have to do the steps mentionned by Marcel Popescu.
You also need to add a handler mapping in IIS 7.5 handler mappings. So that IIS knows that *.css must be used with the System.Web.UI.PageHandlerFactory
It's not enough to just set the stuff in the web.config file.
A: I was having difficulty in getting background images to display for content containers and have tried many solutions similar to other posted here. I had set the relative path in the CSS file, set it as a style on the aspx page I wanted the background to display - nothing worked. I tried Marcel Popescu's solution and it still didn't work.
I did end up getting it to work following a combination of Marcel's solution and trial and error. I inserted the code into the web.config, inserted the text/css line into my CSS file but I removed the background property in the CSS file altogether and set it as a style on the content container in the aspx page I wanted the background to display.
It does mean that for each or any other pages that I want to display the background I will need to set the style background property but it works beautifully.
A: Inside of the .css file you can use relative paths; so in your example, say you put your css file in ~/Styles/mystyles.css. You can use url(../Images/Test.gif) as an example.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: Bypass GeneratedValue in Hibernate Is it possible to bypass @GeneratedValue for an ID in Hibernate, we have a case where, most of the time we want the ID to be set using GeneratedValue, but in certain cases would like to set the ID manually.
Is this possible to do?
A: I know you can do this in the JPA spec, so you should be able to in Hibernate (using JPA+ annotations).
If you just fill in the ID field of the new persistent model you're creating, then when you "Merge" that model into the EntityManager, it will use the ID you've set.
This does have ramifications, though. You've just used up that ID, but the sequence specified by the GeneratedValue annotation doesn't know that. Unless you're specifying an ununsed ID that's LESS than the current sequence value, you're going to get a problem once the sequence catches up to the value you just used.
So, maybe I can see where you might want the user to be able to specify an ID, but then you need to catch the possible Exception (duplicate ID) that may come in the future.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: How do I get my Visual Studio Test Suite web test to iterate over my data source? I have Visual Studio web test attached nicely to a data source, but I need to be able to iterate over each entry in the data source. How should I do this?
A: The trick is to select "Run test(pause before starting)"
Then when the test opens up, click the little link that says "Edit run settings"
A dialog boxes opens allowing you to choose "One run per datasource row"
A: This article seems to Discuss something quite like what you're talking about.
Good luck.
Ola
EDIT: From the linked article, your DataSource is exposed to your test via an attribute.
[DataSource("System.Data.SqlClient",
"Data Source=VSTS;Initial Catalog=ContactManagerWebTest;
Integrated Security=True", "ValidContactInfo",
DataAccessMethod.Sequential), TestMethod()]
There are several other DataSources you can link to, for example CSV, or even Parameters of a Test Case in TFS. Be sure to include the DataAccessMethod.Sequential. If there are multiple rows in the table indicated by the DataSourceAttribute, then each test run will have TestContext.DataRow pointing to the current row/iteration for the test.
A: Open Local.testsettings file from solution explorer and go to Web Test -> Select "One run per data source now" option. That's it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/89441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.