qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
192,641 |
<p>I recently wrote a DLL in C# (.Net 2.0) which contains a class that requires an IP address. A co-worker of mine altered the class to retrieve the IP from a ".dll.config" (XML) file -- This apparently is automatically generated by the "Application Settings" file he created (Settings1.settings). The benefit of this was to allow the end-user to change the IP address in the XML/config file at will.</p>
<p>Unfortunately, when I check his code out of the tree and try to compile (or use) this new code, any application calling this DLL only gets the default value, rather than the value from the file.</p>
<p>The constructor that calls the config file looks like this:</p>
<pre><code> public class form : System.Windows.Forms.Form
{
public form()
{
// This call is required by the Windows Form Designer.
InitializeComponent();
IP = IPAddress.Parse(Settings1.Default.IPAddress);
}
}
</code></pre>
<p>I found <a href="http://social.msdn.microsoft.com/Forums/en-US/clr/thread/f3a4b138-6e6c-42e3-86e8-1f86c90f8fb4/" rel="noreferrer">a reference to this problem on the MSDN forums</a> where a user said:</p>
<blockquote>
<p>the 'old' values (the ones you define at development time) are hard coded. If the franework isn't able to access or open the config file it will use the defaults instead. This will always happen if you use settings in a dll.</p>
</blockquote>
<ol>
<li><p>Does this mean that I cannot store an external value for a DLL in a config file? (My co-worker has somehow made this work...)</p></li>
<li><p>Since my framework appears to be unable to access or open the config file, how do I figure out why it's failing? Or even detect when this happens?</p></li>
</ol>
<p><b>Decker</b>: That helps a bit. Unfortunately, I am writing this DLL to a specification, so I don't actually have access to the Application's config file. As you'll note above, my co-worker created a "Settings<b>1</b>.settings" file. I didn't understand this at the time, but it seems now that adding the "1" keeps it out of the settings space of any application that calls it. </p>
<p>I guess what I'm trying to figure out is why the DLL doesn't seem to find the config file sitting next to it in the same directory. Tracing thru the code step-by-step reveals nothing.</p>
<p>As an aside, I can change the "Output Type" of my assembly from "Class Library" to "Windows Application" and add the following lines at the beginning of my DLL code:</p>
<pre><code> [STAThread]
public static void Main(string[] args)
{
System.Windows.Forms.Application.Run(new form());
}
</code></pre>
<p>When I run this, it generates a different config file (a ".exe.config") and that one I can alter and have it pull the new data from the file. So I'm a bit confused. Any ideas?</p>
|
[
{
"answer_id": 192673,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 1,
"selected": false,
"text": "<p>Apparently your application is trying to read from the default config file (which is probably the application's config file). To make sure, add the key-value pair in the dll's config file to the application's config file, run the application and see if it is read this time.</p>\n"
},
{
"answer_id": 192819,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I've seen a similar problem when using app.config. Try running your application from the .exe instead of from Visual Studio & see if it then behaves as expected.</p>\n"
},
{
"answer_id": 192828,
"author": "Howard Pinsley",
"author_id": 7961,
"author_profile": "https://Stackoverflow.com/users/7961",
"pm_score": 3,
"selected": false,
"text": "<p>I use this technique all time time. Often I have a library assembly that requires certain settings, and I need them set both by testing projects as well as the primary \"executable\" assemblies -- be they web projects or Windows service projects.</p>\n\n<p>You're correct in that when you create a settings file for any project, it adds an application config file. The value you enter for any setting is stored in two places -- the config file AND in attributes on the classes created by the settings infrastructure. When a config file is not found, the values embedded in the attributes are used.</p>\n\n<p>Here is a snippet that shows such an attribute:</p>\n\n<p>Here is a snippet that shows the default value of the ConcordanceServicesEndpointName in the generated class:</p>\n\n<pre><code> [global::System.Configuration.ApplicationScopedSettingAttribute()]\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n [global::System.Configuration.DefaultSettingValueAttribute(\"InternalTCP\")]\n\n public string ConcordanceServicesEndpointName {\n get {\n return ((string)(this[\"ConcordanceServicesEndpointName\"]));\n }\n }\n</code></pre>\n\n<p>What you want to do is copy the configuration section out of the app.config file from the library assembly project and merge it (carefully) into the applicable web.config or app.config for the main assembly. At runtime, that's the only config file that is used.</p>\n\n<p>Here is an example:\n<pre><code><code><configSections>\n <sectionGroup name=\"applicationSettings\" type=\"System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" >\n <section name=\"LitigationPortal.Documents.BLL.DocumentsBLLSettings\" type=\"System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" requirePermission=\"false\" />\n </sectionGroup>\n </configSections>\n <applicationSettings>\n <LitigationPortal.Documents.BLL.DocumentsBLLSettings>\n <setting name=\"ConcordanceServicesEndpointName\" serializeAs=\"String\">\n <value>InternalTCP</value>\n </setting>\n </KayeScholer.LitigationPortal.Documents.BLL.DocumentsBLLSettings>\n </applicationSettings>\n</code></pre></code></p>\n\n<p>You should copy these sections into the \"true\" config file. </p>\n"
},
{
"answer_id": 192897,
"author": "bouvard",
"author_id": 24608,
"author_profile": "https://Stackoverflow.com/users/24608",
"pm_score": 3,
"selected": true,
"text": "<p>I'm addressing this exact issue in an application I'm in the midst of prototyping. Although Decker's suggestion of hacking the config files together should work I think this is a pretty inconvenient manual hack to perform as part of a build cycle. Instead of that I've decided that the cleanest solution is to just have each library parse its own library.dll.config file. Its still not perfect and it requires some extra boiler-plate code, but it seems to be the only way to get around the byzantine way that .Net handles these app.config files.</p>\n"
},
{
"answer_id": 193058,
"author": "Pretzel",
"author_id": 21244,
"author_profile": "https://Stackoverflow.com/users/21244",
"pm_score": 1,
"selected": false,
"text": "<p>I think I just found an explanation of why this isn't working for my DLL and my test application. Here is the concluding exception from <a href=\"http://blogs.interknowlogy.com/robinsanner/archive/2006/05/10/2335.aspx\" rel=\"nofollow noreferrer\">some guy's blog</a>:</p>\n\n<blockquote>\n <p>The fix for this is to either make sure your application and the support assemblies have the same namespace or to make sure you merge the contents of AppName.exe.config and DllName.dll.config (yes when you compile a .dll now it generates this file, however it is ignored if you copy it to the application directory and is not automatically merged)</p>\n</blockquote>\n\n<p>So either I have to keep the DLL and Application in the same namespace -or- I have to merge the contents of the DLL config file with the Application's config file.</p>\n\n<p>(Doesn't this sort of defeat the purpose of the DLL? I thought a DLL was supposed to be an independent library.)</p>\n\n<p>Perhaps this is why it works for my co-worker. The production application shares the same namespace as the DLL. (My test app clearly does not...)</p>\n\n<p><strong>UPDATE:</strong> I just sat down with my co-worker recently and talked about this problem again and it seems that it was never working for him either, but he hadn't realized it because he had set the initial value to be the same as the device we were trying to use. So of course it appeared to work at first, but as soon as we deployed it elsewhere with slightly different settings it was broken again.</p>\n"
},
{
"answer_id": 284582,
"author": "Sam Schutte",
"author_id": 146,
"author_profile": "https://Stackoverflow.com/users/146",
"pm_score": 2,
"selected": false,
"text": "<p>I have had this same problem for a long time - it's annoying.</p>\n\n<p>I like the idea of making your own config file and having each DLL parse it, though it still might be easy to miss having to change the config.</p>\n\n<p>One thing I have done in the past to at least make this a little easier is to make sure that any config values that the Setting1.Settings file are invalid.</p>\n\n<p>For instance, I have a class that uses LINQ-To-SQL to talk to the DB. So it has a Setting1.settings file that it stores the connection string to database in. The default value that is entered (upon dragging and dropping the database tables into the designer) is the connection string of the dev database.</p>\n\n<p>Once I have the DBML file created based off of the test database, I can go in and edit the Settings file and type in a database name like \"FAKE_DATABASE\".</p>\n\n<p>That way, if you use the DLL in another project, and then forget to merge the config files to add in the proper config value for the DLL, at least you'll get an error saying something like \"Cannot connect to FAKE_DATABASE\".</p>\n\n<p>Of course, if you have to work with the designer again, you'll have to change the value back to the value of your dev database.</p>\n\n<p>Huge pain. They've gotta change this somehow.</p>\n"
},
{
"answer_id": 417391,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible that in your DLL you have the access modifier (for the Settings1.Settings) set to Internal (Friend for VB). Try changing the Access MOdifier to Public and see if that lets your application read/write values from dll's config.</p>\n"
},
{
"answer_id": 11991195,
"author": "MRHIMAN",
"author_id": 1603772,
"author_profile": "https://Stackoverflow.com/users/1603772",
"pm_score": -1,
"selected": false,
"text": "<p>The mistake I think you all make is that you apparently make referece to the DLL Settings via <code>Settings1.Default.IPAddress</code> while you are simply suppossed to do this <code>Settings1.IPAddress</code>.</p>\n\n<p>The difference is that when you use <code>Settings1.Default.IPAddress</code> the values are gotten from the hardcoded values imbeded in the assembly file (.dll or .exe) as Attribute [global::System.Configuration.DefaultSettingValueAttribute(...)]. </p>\n\n<p>While <code>Settings1.IPAddress</code> is the value that is editable in the file <code>.dll.config</code> (XML file)**. so any changes you make to the XML file, it is not reflected in hardcoded default value in the assembly.</p>\n\n<p>Not this:</p>\n\n<pre><code>IP = IPAddress.Parse(Settings1.Default.IPAddress);\n</code></pre>\n\n<p>But try this:</p>\n\n<pre><code>*IP = IPAddress.Parse(Settings1.IPAddress);\n</code></pre>\n"
},
{
"answer_id": 42715640,
"author": "Kflexior",
"author_id": 1290233,
"author_profile": "https://Stackoverflow.com/users/1290233",
"pm_score": 0,
"selected": false,
"text": "<p>The answer from Howard covers the theory.</p>\n\n<p>One quick and dirty way of solving this is to parse the xml config file manually.</p>\n\n<pre><code> string configFile = Assembly.GetExecutingAssembly().Location + \".config\";\n XDocument.Load(configFile).Root.Element(\"appSettings\")....\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21244/"
] |
I recently wrote a DLL in C# (.Net 2.0) which contains a class that requires an IP address. A co-worker of mine altered the class to retrieve the IP from a ".dll.config" (XML) file -- This apparently is automatically generated by the "Application Settings" file he created (Settings1.settings). The benefit of this was to allow the end-user to change the IP address in the XML/config file at will.
Unfortunately, when I check his code out of the tree and try to compile (or use) this new code, any application calling this DLL only gets the default value, rather than the value from the file.
The constructor that calls the config file looks like this:
```
public class form : System.Windows.Forms.Form
{
public form()
{
// This call is required by the Windows Form Designer.
InitializeComponent();
IP = IPAddress.Parse(Settings1.Default.IPAddress);
}
}
```
I found [a reference to this problem on the MSDN forums](http://social.msdn.microsoft.com/Forums/en-US/clr/thread/f3a4b138-6e6c-42e3-86e8-1f86c90f8fb4/) where a user said:
>
> the 'old' values (the ones you define at development time) are hard coded. If the franework isn't able to access or open the config file it will use the defaults instead. This will always happen if you use settings in a dll.
>
>
>
1. Does this mean that I cannot store an external value for a DLL in a config file? (My co-worker has somehow made this work...)
2. Since my framework appears to be unable to access or open the config file, how do I figure out why it's failing? Or even detect when this happens?
**Decker**: That helps a bit. Unfortunately, I am writing this DLL to a specification, so I don't actually have access to the Application's config file. As you'll note above, my co-worker created a "Settings**1**.settings" file. I didn't understand this at the time, but it seems now that adding the "1" keeps it out of the settings space of any application that calls it.
I guess what I'm trying to figure out is why the DLL doesn't seem to find the config file sitting next to it in the same directory. Tracing thru the code step-by-step reveals nothing.
As an aside, I can change the "Output Type" of my assembly from "Class Library" to "Windows Application" and add the following lines at the beginning of my DLL code:
```
[STAThread]
public static void Main(string[] args)
{
System.Windows.Forms.Application.Run(new form());
}
```
When I run this, it generates a different config file (a ".exe.config") and that one I can alter and have it pull the new data from the file. So I'm a bit confused. Any ideas?
|
I'm addressing this exact issue in an application I'm in the midst of prototyping. Although Decker's suggestion of hacking the config files together should work I think this is a pretty inconvenient manual hack to perform as part of a build cycle. Instead of that I've decided that the cleanest solution is to just have each library parse its own library.dll.config file. Its still not perfect and it requires some extra boiler-plate code, but it seems to be the only way to get around the byzantine way that .Net handles these app.config files.
|
192,648 |
<p>OK, so I'm trying to teach myself the CakePHP framework, and I'm trying to knock up a simple demo app for myself.</p>
<p>I have the controllers, views and models all set up and working, but I want to do something slightly more than the basic online help shows.</p>
<p>I have a guitars_controller.php file as follows...</p>
<pre><code><?php
class GuitarsController extends AppController {
var $name = 'Guitars';
function index() {
$this->set('Guitars', $this->Guitar->findAll());
$this->pageTitle = "All Guitars";
}
function view($id = null) {
$this->Guitar->id = $id;
$this->set('guitar', $this->Guitar->read());
// Want to set the title here.
}
}
?>
</code></pre>
<p>The 'Guitar' object contains an attribute called 'Name', and I'd like to be able to set that as the pageTitle for the individual page views. </p>
<p>Can anyone point out how I'd do that, please? </p>
<p><strong>NB</strong>: I know that there is general disagreement about where in the application to set this kind of data, but to me, it is data related.</p>
|
[
{
"answer_id": 192657,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$this->pageTitle = $this->Guitar->Name;\n</code></pre>\n\n<p>It should go in the View though, I don't PHP, or cakePHP, but thats something a view should do, not the controller.</p>\n"
},
{
"answer_id": 192722,
"author": "Gaurav",
"author_id": 13492,
"author_profile": "https://Stackoverflow.com/users/13492",
"pm_score": 0,
"selected": false,
"text": "<p>It should go in the controller. See <a href=\"http://book.cakephp.org/view/314/Views\" rel=\"nofollow noreferrer\">this</a></p>\n"
},
{
"answer_id": 192737,
"author": "Paolo Bergantino",
"author_id": 16417,
"author_profile": "https://Stackoverflow.com/users/16417",
"pm_score": 2,
"selected": false,
"text": "<p>You can set this in the controller:</p>\n\n<pre><code>function view($id = null) {\n $guitar = $this->Guitar->read(null, $id);\n $this->set('guitar', $guitar);\n $this->pageTitle = $guitar['Guitar']['name'];\n}\n</code></pre>\n\n<p>Or in the view:</p>\n\n<pre><code><? $this->pageTitle = $guitar['Guitar']['name']; ?>\n</code></pre>\n\n<p>The value set in the view will override any value that may have already been set in the controller.</p>\n\n<p>For security, you must ensure that your layout / view that displays the pageTitle html-encodes this arbitrary data to avoid injection attacks and broken html</p>\n\n<pre><code><?php echo h( $title_for_layout ); ?>\n</code></pre>\n"
},
{
"answer_id": 192883,
"author": "rg88",
"author_id": 11252,
"author_profile": "https://Stackoverflow.com/users/11252",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>\"but I want to do something slightly more than the basic online help shows.\"</p>\n</blockquote>\n\n<p>Isn't that always the rub? So much documentation is geared towards a bare minimum that it really does not help much. You can complete many of the tutorials available but as soon as you take 1 step off the reservation the confusion sets in. Well, it's either bare minimum or pro developer maximum but rarely hits that sweet spot of ease, clarity and depth.</p>\n\n<p>I'm currently rewriting some Zend Framework documentation for my own use simply so I can smooth out the inconsistencies, clarify glossed over assumptions and get at the core, \"best practice\" way of understanding it. My mantra: Ease, clarity, depth. Ease, clarity, depth.</p>\n"
},
{
"answer_id": 192916,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 0,
"selected": false,
"text": "<p>Ah, the none-obvious answer is as follows...</p>\n\n<pre><code>$this->pageTitle = $this->viewVars['guitar']['Guitar']['Name'];\n</code></pre>\n\n<p>I found this by placing the following code in the controller (was a long shot that paid off, to be honest)</p>\n\n<pre><code>echo \"<pre>\"; print_r($this);echo \"</pre>\";\n</code></pre>\n\n<p>Thanks to all those that tried to help.</p>\n"
},
{
"answer_id": 193897,
"author": "neilcrookes",
"author_id": 9968,
"author_profile": "https://Stackoverflow.com/users/9968",
"pm_score": 4,
"selected": true,
"text": "<p>These actions are model agnostic so can be put in your app/app_controller.php file</p>\n\n<pre><code><?php\nclass AppController extends Controller {\n function index() {\n $this->set(Inflector::variable($this->name), $this->{$this->modelClass}->findAll());\n $this->pageTitle = 'All '.Inflector::humanize($this->name);\n }\n function view($id = null) {\n $data = $this->{$this->modelClass}->findById($id);\n $this->set(Inflector::variable($this->modelClass), $data);\n $this->pageTitle = $data[$this->modelClass][$this->{$this->modelClass}->displayField];\n }\n}\n?>\n</code></pre>\n\n<p>Pointing your browser to /guitars will invoke your guitars controller index action, which doesn't exist so the one in AppController (which GuitarsController inherits from) will be run. Same for the view action. This will also work for your DrumsController, KeyboardsController etc etc.</p>\n"
},
{
"answer_id": 196102,
"author": "Alexander Morland",
"author_id": 4013,
"author_profile": "https://Stackoverflow.com/users/4013",
"pm_score": 1,
"selected": false,
"text": "<p>In response to your own answer about oo paradigm. Its like this :</p>\n\n<pre><code>function view($id) {\n $this->Guitar->id = $id;\n $this->Guitar->read();\n $this->pageTitle = $this->Guitar->data['Guitar']['name'];\n $this->set('data', $this->Guitar->data);\n}\n</code></pre>\n\n<p>By the way, you should check if id is set and valid etc, since this is url user input.</p>\n"
},
{
"answer_id": 672496,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>echo \"<pre>\"; print_r($this);echo \"</pre>\";\n</code></pre>\n\n<p>how about </p>\n\n<pre><code>pr( $this );\n</code></pre>\n"
},
{
"answer_id": 6004551,
"author": "windmaomao",
"author_id": 288096,
"author_profile": "https://Stackoverflow.com/users/288096",
"pm_score": 0,
"selected": false,
"text": "<p>OK, I really want to set the page title in the controller instead in the view. So here's what I did:</p>\n\n<pre><code>class CustomersController extends AppController {\n\n var $name = 'Customers';\n\n function beforeFilter() {\n parent::beforeFilter();\n $this->set('menu',$this->name);\n switch ($this->action) {\n case 'index':\n $this->title = 'List Customer';\n break;\n case 'view':\n $this->title = 'View Customer';\n break;\n case 'edit':\n $this->title = 'Edit Customer';\n break;\n case 'add':\n $this->title = 'Add New Customer';\n break;\n default:\n $title = 'Welcome to '.$name;\n break;\n }\n $this->set('title',$this->title);\n }\n</code></pre>\n\n<p>The trick is that you can't set <code>$this->title</code> inside any action, it won't work. It seems to me that the web page reaches action after rendering, however you can do it in <code>beforeFilter</code>. </p>\n"
},
{
"answer_id": 6804991,
"author": "Tarik",
"author_id": 44852,
"author_profile": "https://Stackoverflow.com/users/44852",
"pm_score": 1,
"selected": false,
"text": "<p>As of CakePHP 1.3, setting page title has been changed.</p>\n\n<pre><code>$this->pageTitle = \"Title\"; //deprecated\n\n$this->set(\"title_for_layout\",Inflector::humanize($this->name)); // new way of setting title\n</code></pre>\n\n<p>Note: More about Inflector: <a href=\"http://api13.cakephp.org/class/inflector#method-Inflector\" rel=\"nofollow\">http://api13.cakephp.org/class/inflector#method-Inflector</a></p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/377/"
] |
OK, so I'm trying to teach myself the CakePHP framework, and I'm trying to knock up a simple demo app for myself.
I have the controllers, views and models all set up and working, but I want to do something slightly more than the basic online help shows.
I have a guitars\_controller.php file as follows...
```
<?php
class GuitarsController extends AppController {
var $name = 'Guitars';
function index() {
$this->set('Guitars', $this->Guitar->findAll());
$this->pageTitle = "All Guitars";
}
function view($id = null) {
$this->Guitar->id = $id;
$this->set('guitar', $this->Guitar->read());
// Want to set the title here.
}
}
?>
```
The 'Guitar' object contains an attribute called 'Name', and I'd like to be able to set that as the pageTitle for the individual page views.
Can anyone point out how I'd do that, please?
**NB**: I know that there is general disagreement about where in the application to set this kind of data, but to me, it is data related.
|
These actions are model agnostic so can be put in your app/app\_controller.php file
```
<?php
class AppController extends Controller {
function index() {
$this->set(Inflector::variable($this->name), $this->{$this->modelClass}->findAll());
$this->pageTitle = 'All '.Inflector::humanize($this->name);
}
function view($id = null) {
$data = $this->{$this->modelClass}->findById($id);
$this->set(Inflector::variable($this->modelClass), $data);
$this->pageTitle = $data[$this->modelClass][$this->{$this->modelClass}->displayField];
}
}
?>
```
Pointing your browser to /guitars will invoke your guitars controller index action, which doesn't exist so the one in AppController (which GuitarsController inherits from) will be run. Same for the view action. This will also work for your DrumsController, KeyboardsController etc etc.
|
192,649 |
<p>Ruby can add methods to the Number class and other core types to get effects like this:</p>
<pre class="lang-rb prettyprint-override"><code>1.should_equal(1)
</code></pre>
<p>But it seems like Python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p>
<p><em>Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in Python, would allow this.</em></p>
<p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability.</p>
<pre><code> item.price.should_equal(19.99)
</code></pre>
<p>This reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p>
<pre><code>should_equal(item.price, 19.99)
</code></pre>
<p>This concept is what <a href="http://rspec.info/" rel="nofollow noreferrer">Rspec</a> and some other Ruby frameworks are based on.</p>
|
[
{
"answer_id": 192651,
"author": "sanxiyn",
"author_id": 18382,
"author_profile": "https://Stackoverflow.com/users/18382",
"pm_score": 0,
"selected": false,
"text": "<p>No, you can't do that in Python. I consider it to be a good thing.</p>\n"
},
{
"answer_id": 192681,
"author": "HanClinto",
"author_id": 26933,
"author_profile": "https://Stackoverflow.com/users/26933",
"pm_score": 2,
"selected": false,
"text": "<p>If you really really <em>really</em> want to do a monkey patch in Python, you can do a (sortof) hack with the \"import foo as bar\" technique.</p>\n\n<p>If you have a class such as TelnetConnection, and you want to extend it, subclass it in a separate file and call it something like TelnetConnectionExtended.</p>\n\n<p>Then, at the top of your code, where you would normally say:</p>\n\n<pre><code>import TelnetConnection\n</code></pre>\n\n<p>change that to be:</p>\n\n<pre><code>import TelnetConnectionExtended as TelnetConnection\n</code></pre>\n\n<p>and then everywhere in your code that you reference TelnetConnection will actually be referencing TelnetConnectionExtended.</p>\n\n<p>Sadly, this assumes that you have access to that class, and the \"as\" only operates within that particular file (it's not a global-rename), but I've found it to be useful from time to time.</p>\n"
},
{
"answer_id": 192694,
"author": "Luka Marinko",
"author_id": 19814,
"author_profile": "https://Stackoverflow.com/users/19814",
"pm_score": 1,
"selected": false,
"text": "<p>No but you have UserDict UserString and UserList which were made with exactly this in mind.</p>\n\n<p>If you google you will find examples for other types, but this are builtin.</p>\n\n<p>In general monkey patching is less used in Python than in Ruby.</p>\n"
},
{
"answer_id": 192703,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 7,
"selected": true,
"text": "<p>What exactly do you mean by Monkey Patch here? There are <a href=\"http://wikipedia.org/wiki/Monkey_patch\" rel=\"noreferrer\">several slightly different definitions</a>.</p>\n\n<p>If you mean, \"can you change a class's methods at runtime?\", then the answer is emphatically yes:</p>\n\n<pre><code>class Foo:\n pass # dummy class\n\nFoo.bar = lambda self: 42\n\nx = Foo()\nprint x.bar()\n</code></pre>\n\n<p>If you mean, \"can you change a class's methods at runtime and <strong>make all of the instances of that class change after-the-fact</strong>?\" then the answer is yes as well. Just change the order slightly:</p>\n\n<pre><code>class Foo:\n pass # dummy class\n\nx = Foo()\n\nFoo.bar = lambda self: 42\n\nprint x.bar()\n</code></pre>\n\n<p>But you can't do this for certain built-in classes, like <code>int</code> or <code>float</code>. These classes' methods are implemented in C and there are certain abstractions sacrificed in order to make the implementation easier and more efficient.</p>\n\n<p>I'm not really clear on <strong>why</strong> you would want to alter the behavior of the built-in numeric classes anyway. If you need to alter their behavior, subclass them!!</p>\n"
},
{
"answer_id": 192857,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 6,
"selected": false,
"text": "<p>No, you cannot. In Python, all data (classes, methods, functions, etc) defined in C extension modules (including builtins) are immutable. This is because C modules are shared between multiple interpreters in the same process, so monkeypatching them would also affect unrelated interpreters in the same process. (Multiple interpreters in the same process are possible through the <a href=\"https://docs.python.org/3/c-api/init.html#sub-interpreter-support\" rel=\"noreferrer\">C API</a>, and there has been <a href=\"https://www.python.org/dev/peps/pep-0554/\" rel=\"noreferrer\">some effort</a> towards making them usable at Python level.)</p>\n\n<p>However, classes defined in Python code may be monkeypatched because they are local to that interpreter.</p>\n"
},
{
"answer_id": 193660,
"author": "zaphod",
"author_id": 13871,
"author_profile": "https://Stackoverflow.com/users/13871",
"pm_score": 4,
"selected": false,
"text": "<p>Python's core types are immutable by design, as other users have pointed out:</p>\n\n<pre><code>>>> int.frobnicate = lambda self: whatever()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: can't set attributes of built-in/extension type 'int'\n</code></pre>\n\n<p>You certainly <em>could</em> achieve the effect you describe by making a subclass, since user-defined types in Python are mutable by default.</p>\n\n<pre><code>>>> class MyInt(int):\n... def frobnicate(self):\n... print 'frobnicating %r' % self\n... \n>>> five = MyInt(5)\n>>> five.frobnicate()\nfrobnicating 5\n>>> five + 8\n13\n</code></pre>\n\n<p>There's no need to make the <code>MyInt</code> subclass public, either; one could just as well define it inline directly in the function or method that constructs the instance.</p>\n\n<p>There are certainly a few situations where Python programmers who are fluent in the idiom consider this sort of subclassing the right thing to do. For instance, <code>os.stat()</code> returns a <code>tuple</code> subclass that adds named members, precisely in order to address the sort of readability concern you refer to in your example.</p>\n\n<pre><code>>>> import os\n>>> st = os.stat('.')\n>>> st\n(16877, 34996226, 65024L, 69, 1000, 1000, 4096, 1223697425, 1223699268, 1223699268)\n>>> st[6]\n4096\n>>> st.st_size\n4096\n</code></pre>\n\n<p>That said, in the specific example you give, I don't believe that subclassing <code>float</code> in <code>item.price</code> (or elsewhere) would be very likely to be considered the Pythonic thing to do. I <em>can</em> easily imagine somebody deciding to add a <code>price_should_equal()</code> method to <code>item</code> if that were the primary use case; if one were looking for something more general, perhaps it might make more sense to use named arguments to make the intended meaning clearer, as in</p>\n\n<pre><code>should_equal(observed=item.price, expected=19.99)\n</code></pre>\n\n<p>or something along those lines. It's a bit verbose, but no doubt it could be improved upon. A possible advantage to such an approach over Ruby-style monkey-patching is that <code>should_equal()</code> could easily perform its comparison on any type, not just <code>int</code> or <code>float</code>. But perhaps I'm getting too caught up in the details of the particular example that you happened to provide.</p>\n"
},
{
"answer_id": 830114,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>What does <code>should_equal</code> do? Is it a boolean returning <code>True</code> or <code>False</code>? In that case, it's spelled:</p>\n\n<pre><code>item.price == 19.99\n</code></pre>\n\n<p>There's no accounting for taste, but no regular python developer would say that's less readable than your version.</p>\n\n<p>Does <code>should_equal</code> instead set some sort of validator? (why would a validator be limited to one value? Why not just set the value and not update it after that?) If you want a validator, this could never work anyway, since you're proposing to modify either a particular integer or all integers. (A validator that requires <code>18.99</code> to equal <code>19.99</code> will always fail.) Instead, you could spell it like this:</p>\n\n<pre><code>item.price_should_equal(19.99)\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>item.should_equal('price', 19.99)\n</code></pre>\n\n<p>and define appropriate methods on item's class or superclasses.</p>\n"
},
{
"answer_id": 838000,
"author": "Ryan Ginstrom",
"author_id": 10658,
"author_profile": "https://Stackoverflow.com/users/10658",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an example of implementing <code>item.price.should_equal</code>, although I'd use Decimal instead of float in a real program:</p>\n\n<pre><code>class Price(float):\n def __init__(self, val=None):\n float.__init__(self)\n if val is not None:\n self = val\n\n def should_equal(self, val):\n assert self == val, (self, val)\n\nclass Item(object):\n def __init__(self, name, price=None):\n self.name = name\n self.price = Price(price)\n\nitem = Item(\"spam\", 3.99)\nitem.price.should_equal(3.99)\n</code></pre>\n"
},
{
"answer_id": 4025310,
"author": "Jonathan",
"author_id": 487810,
"author_profile": "https://Stackoverflow.com/users/487810",
"pm_score": 5,
"selected": false,
"text": "<pre><code>def should_equal_def(self, value):\n if self != value:\n raise ValueError, \"%r should equal %r\" % (self, value)\n\nclass MyPatchedInt(int):\n should_equal=should_equal_def\n\nclass MyPatchedStr(str):\n should_equal=should_equal_def\n\nimport __builtin__\n__builtin__.str = MyPatchedStr\n__builtin__.int = MyPatchedInt\n\nint(1).should_equal(1)\nstr(\"44\").should_equal(\"44\")\n</code></pre>\n\n<p>Have fun ;)</p>\n"
},
{
"answer_id": 5988122,
"author": "Lvsoft",
"author_id": 751878,
"author_profile": "https://Stackoverflow.com/users/751878",
"pm_score": 3,
"selected": false,
"text": "<p>You can't patch core types in python. \nHowever, you could use pipe to write a more human readable code: </p>\n\n<pre><code>from pipe import *\n\n@Pipe\ndef should_equal(obj, val):\n if obj==val: return True\n return False\n\nclass dummy: pass\nitem=dummy()\nitem.value=19.99\n\nprint item.value | should_equal(19.99)\n</code></pre>\n"
},
{
"answer_id": 6245617,
"author": "Petr Viktorin",
"author_id": 99057,
"author_profile": "https://Stackoverflow.com/users/99057",
"pm_score": 1,
"selected": false,
"text": "<p>It seems what you really wanted to write is:</p>\n\n<pre><code>assert item.price == 19.99\n</code></pre>\n\n<p>(Of course comparing floats for equality, or using floats for prices, is <a href=\"http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html\" rel=\"nofollow\">a bad idea</a>, so you'd write <code>assert item.price == Decimal(19.99)</code> or whatever numeric class you were using for the price.)</p>\n\n<p>You could also use a testing framework like <a href=\"http://doc.pytest.org/en/latest/example/reportingdemo.html\" rel=\"nofollow\">py.test</a> to get more info on failing asserts in your tests.</p>\n"
},
{
"answer_id": 10891256,
"author": "mdwhatcott",
"author_id": 605022,
"author_profile": "https://Stackoverflow.com/users/605022",
"pm_score": -1,
"selected": false,
"text": "<p>Here's how I achieve the .should_something... behavior:</p>\n\n<pre><code>result = calculate_result('blah') # some method defined somewhere else\n\nthe(result).should.equal(42)\n</code></pre>\n\n<h2>or</h2>\n\n<pre><code>the(result).should_NOT.equal(41)\n</code></pre>\n\n<p>I included a decorator method for extending this behavior at runtime on a stand-alone method:</p>\n\n<pre><code>@should_expectation\ndef be_42(self)\n self._assert(\n action=lambda: self._value == 42,\n report=lambda: \"'{0}' should equal '5'.\".format(self._value)\n )\n\nresult = 42\n\nthe(result).should.be_42()\n</code></pre>\n\n<p>You have to know a bit about the internals but it works.</p>\n\n<p>Here's the source:</p>\n\n<p><a href=\"https://github.com/mdwhatcott/pyspecs\" rel=\"nofollow\">https://github.com/mdwhatcott/pyspecs</a></p>\n\n<p>It's also on PyPI under pyspecs.</p>\n"
},
{
"answer_id": 13971038,
"author": "Dima Tisnek",
"author_id": 705086,
"author_profile": "https://Stackoverflow.com/users/705086",
"pm_score": 0,
"selected": false,
"text": "<p>No, sadly you cannot extend types implemented in C at runtime.</p>\n\n<p>You can subclass int, although it is non-trivial, you may have to override <code>__new__</code>.</p>\n\n<p>You also have a syntax issue:</p>\n\n<pre><code>1.somemethod() # invalid\n</code></pre>\n\n<p>However</p>\n\n<pre><code>(1).__eq__(1) # valid\n</code></pre>\n"
},
{
"answer_id": 17246179,
"author": "alcalde",
"author_id": 2128279,
"author_profile": "https://Stackoverflow.com/users/2128279",
"pm_score": 5,
"selected": false,
"text": "<p>You can do this, but it takes a little bit of hacking. Fortunately, there's a module now called \"Forbidden Fruit\" that gives you the power to patch methods of built-in types very simply. You can find it at </p>\n\n<p><a href=\"http://clarete.github.io/forbiddenfruit/?goback=.gde_50788_member_228887816\" rel=\"noreferrer\">http://clarete.github.io/forbiddenfruit/?goback=.gde_50788_member_228887816</a></p>\n\n<p>or </p>\n\n<p><a href=\"https://pypi.python.org/pypi/forbiddenfruit/0.1.0\" rel=\"noreferrer\">https://pypi.python.org/pypi/forbiddenfruit/0.1.0</a></p>\n\n<p>With the original question example, after you write the \"should_equal\" function, you'd just do</p>\n\n<pre><code>from forbiddenfruit import curse\ncurse(int, \"should_equal\", should_equal)\n</code></pre>\n\n<p>and you're good to go! There's also a \"reverse\" function to remove a patched method. </p>\n"
},
{
"answer_id": 72763352,
"author": "electroJo",
"author_id": 19420844,
"author_profile": "https://Stackoverflow.com/users/19420844",
"pm_score": 0,
"selected": false,
"text": "<p>Here is how I made custom string/int/float...etc. methods:</p>\n<pre><code>class MyStrClass(str):\n\n def __init__(self, arg: str):\n self.arg_one = arg\n\n def my_str_method(self):\n return self.arg_one\n\n def my_str_multiple_arg_method(self, arg_two):\n return self.arg_one + arg_two\n\nclass MyIntClass(int):\n\n def __init__(self, arg: int):\n self.arg_one = arg\n\n def my_int_method(self):\n return self.arg_one * 2\n\n\nmyString = MyStrClass("StackOverflow")\nmyInteger = MyIntClass(15)\n\nprint(myString.count("a")) # Output: 1\nprint(myString.my_str_method()) # Output: StackOverflow\nprint(myString.my_str_multiple_arg_method(" is cool!")) # Output: StackOverflow is cool!\nprint(myInteger.my_int_method()) # Output: 30\n</code></pre>\n<p>It's maybe not the best solution, but it works just fine.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5304/"
] |
Ruby can add methods to the Number class and other core types to get effects like this:
```rb
1.should_equal(1)
```
But it seems like Python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that *type* can't be modified?
*Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in Python, would allow this.*
To answer some of you: The reason I *might* want to do this is simply aesthetics/readability.
```
item.price.should_equal(19.99)
```
This reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:
```
should_equal(item.price, 19.99)
```
This concept is what [Rspec](http://rspec.info/) and some other Ruby frameworks are based on.
|
What exactly do you mean by Monkey Patch here? There are [several slightly different definitions](http://wikipedia.org/wiki/Monkey_patch).
If you mean, "can you change a class's methods at runtime?", then the answer is emphatically yes:
```
class Foo:
pass # dummy class
Foo.bar = lambda self: 42
x = Foo()
print x.bar()
```
If you mean, "can you change a class's methods at runtime and **make all of the instances of that class change after-the-fact**?" then the answer is yes as well. Just change the order slightly:
```
class Foo:
pass # dummy class
x = Foo()
Foo.bar = lambda self: 42
print x.bar()
```
But you can't do this for certain built-in classes, like `int` or `float`. These classes' methods are implemented in C and there are certain abstractions sacrificed in order to make the implementation easier and more efficient.
I'm not really clear on **why** you would want to alter the behavior of the built-in numeric classes anyway. If you need to alter their behavior, subclass them!!
|
192,653 |
<p>I'm using .NET 3.5 and I have a class, A, marked as internal sealed partial and it derives from System.Configuration.ApplicationSettingsBase. I then use an instance of this class in the following manner:</p>
<pre><code>A A_Instance = new A();
A_Instance.Default.Save();
</code></pre>
<p>Why would the Visual C# compiler be complaining:</p>
<pre><code>error CS0117: 'A' does not contain a definition for 'Default'
</code></pre>
<p>?</p>
|
[
{
"answer_id": 192677,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "<p>ApplicationSettingsBase inherits from SettingsBase, neither of which expose a Default property. Judging by the compiler error your class doesn't add one.</p>\n\n<p>AFAIK C# does not support any special syntax around the word 'Default' for accessing a property that is marked as the default.</p>\n\n<p>What behaviour are you expecting?</p>\n"
},
{
"answer_id": 192690,
"author": "Greg Dean",
"author_id": 1200558,
"author_profile": "https://Stackoverflow.com/users/1200558",
"pm_score": 3,
"selected": true,
"text": "<p>You are probably looking for this:</p>\n\n<pre><code>private static ServerSettings defaultInstance = ((ServerSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new ServerSettings())));\n\npublic static ServerSettings Default \n {\n get { return defaultInstance; }\n}\n</code></pre>\n\n<p>This is the code that gets generated by visual studio</p>\n"
},
{
"answer_id": 192982,
"author": "Mike Caron",
"author_id": 2836,
"author_profile": "https://Stackoverflow.com/users/2836",
"pm_score": 1,
"selected": false,
"text": "<p>.NET doesn't provide a 'Default' member in ApplicationSettingsBase from which to access any methods. What I failed to notice was that 'Default' was being used as a singleton of A. Thus, the sample code provided by gdean2323 gave me some guidance to the fix. The code to fix the problem required me adding the following code to class A (without necessary synchronization for simplicity):</p>\n\n<pre><code>private static A defaultInstance = new A();\npublic static A Default \n{\n get\n {\n return defaultInstance;\n }\n}\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2836/"
] |
I'm using .NET 3.5 and I have a class, A, marked as internal sealed partial and it derives from System.Configuration.ApplicationSettingsBase. I then use an instance of this class in the following manner:
```
A A_Instance = new A();
A_Instance.Default.Save();
```
Why would the Visual C# compiler be complaining:
```
error CS0117: 'A' does not contain a definition for 'Default'
```
?
|
You are probably looking for this:
```
private static ServerSettings defaultInstance = ((ServerSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new ServerSettings())));
public static ServerSettings Default
{
get { return defaultInstance; }
}
```
This is the code that gets generated by visual studio
|
192,678 |
<p>We are connecting to a WCF web service which has Anonomous Access turned off, Windows Authentication turned on. The web.config file has a local user account for allow users and deny users="?". </p>
<p>I can download and generate the service proxy fine (being prompted for creds), however from my windows form project (even when passing in the credentials), I get the following error:</p>
<pre><code>System.ServiceModel.Security.MessageSecurityException was unhandled
Message="The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Basic realm=\"SEIPART001\"'."
Message="The remote server returned an error: (401) Unauthorized."
</code></pre>
<p>Here is my sample code:</p>
<pre><code>ip.eIPCShoppingCartWSSoapClient client = new iParts.ip.eIPCShoppingCartWSSoapClient();
System.Net.NetworkCredential creds = new System.Net.NetworkCredential("username", "password", "domain");
client.ClientCredentials.Windows.ClientCredential = creds;
iParts.ip.OrderListItem[] listItem = client.GetOrderList("1234"); //throws exception here
</code></pre>
|
[
{
"answer_id": 194009,
"author": "tomasr",
"author_id": 10292,
"author_profile": "https://Stackoverflow.com/users/10292",
"pm_score": 1,
"selected": false,
"text": "<p>Looks like your service is asking for <em>basic</em> authentication; not windows integrated authentication. </p>\n\n<p>In that case, I think you need to specify the credentials on the client proxy using in the ClientCredentials.UserName property and not ClientCredentials.Windows.</p>\n"
},
{
"answer_id": 194568,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>No change. The virtual directory is asking for Windows Auth and passing in a local user. It works fine in the browser but the service keeps erroring out.</p>\n"
},
{
"answer_id": 374979,
"author": "khebbie",
"author_id": 4189,
"author_profile": "https://Stackoverflow.com/users/4189",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like you should switch to transport security.\nLookin the security section of your configuration.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
We are connecting to a WCF web service which has Anonomous Access turned off, Windows Authentication turned on. The web.config file has a local user account for allow users and deny users="?".
I can download and generate the service proxy fine (being prompted for creds), however from my windows form project (even when passing in the credentials), I get the following error:
```
System.ServiceModel.Security.MessageSecurityException was unhandled
Message="The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Basic realm=\"SEIPART001\"'."
Message="The remote server returned an error: (401) Unauthorized."
```
Here is my sample code:
```
ip.eIPCShoppingCartWSSoapClient client = new iParts.ip.eIPCShoppingCartWSSoapClient();
System.Net.NetworkCredential creds = new System.Net.NetworkCredential("username", "password", "domain");
client.ClientCredentials.Windows.ClientCredential = creds;
iParts.ip.OrderListItem[] listItem = client.GetOrderList("1234"); //throws exception here
```
|
Looks like your service is asking for *basic* authentication; not windows integrated authentication.
In that case, I think you need to specify the credentials on the client proxy using in the ClientCredentials.UserName property and not ClientCredentials.Windows.
|
192,693 |
<p>I'm writing a routine that validates data before inserting it into a database, and one of the steps is to see if numeric values fit the precision and scale of a Numeric(x,y) SQL-Server type. </p>
<p>I have the precision and scale from SQL-Server already, but what's the most efficient way in C# to get the precision and scale of a CLR value, or at least to test if it fits a given constraint?</p>
<p>At the moment, I'm converting the CLR value to a string, then looking for the location of the decimal point with .IndexOf(). Is there a faster way?</p>
|
[
{
"answer_id": 192750,
"author": "HasaniH",
"author_id": 7141,
"author_profile": "https://Stackoverflow.com/users/7141",
"pm_score": 0,
"selected": false,
"text": "<p>You can use decimal.Truncate(val) to get the integral part of the value and decimal.Remainder(val, 1) to get the part after the decimal point and then check that each part meets your constraints (I'm guessing this can be a simple > or < check)</p>\n"
},
{
"answer_id": 192906,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 5,
"selected": true,
"text": "<pre><code>System.Data.SqlTypes.SqlDecimal.ConvertToPrecScale( new SqlDecimal (1234.56789), 8, 2)\n</code></pre>\n<p>gives 1234.57. it will truncate extra digits after the decimal place, and will throw an error rather than try to truncate digits before the decimal place (i.e. ConvertToPrecScale(12344234, 5,2)</p>\n"
},
{
"answer_id": 38383700,
"author": "Craig",
"author_id": 525558,
"author_profile": "https://Stackoverflow.com/users/525558",
"pm_score": 3,
"selected": false,
"text": "<p>Without triggering an exception, you could use the following method to determine if the value fits the precision and scale constraints.</p>\n\n<pre><code>private static bool IsValid(decimal value, byte precision, byte scale)\n{\n var sqlDecimal = new SqlDecimal(value);\n\n var actualDigitsToLeftOfDecimal = sqlDecimal.Precision - sqlDecimal.Scale;\n\n var allowedDigitsToLeftOfDecimal = precision - scale;\n\n return \n actualDigitsToLeftOfDecimal <= allowedDigitsToLeftOfDecimal && \n sqlDecimal.Scale <= scale;\n}\n</code></pre>\n"
},
{
"answer_id": 48912609,
"author": "Evil Pigeon",
"author_id": 404089,
"author_profile": "https://Stackoverflow.com/users/404089",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a maths based approach.</p>\n\n<pre><code>private static bool IsValidSqlDecimal(decimal value, int precision, int scale)\n{\n var minOverflowValue = (decimal)Math.Pow(10, precision - scale) - (decimal)Math.Pow(10, -scale) / 2;\n return Math.Abs(value) < minOverflowValue;\n}\n</code></pre>\n\n<p>This takes into account how sql server will do rounding and prevent overflow errors, even if we exceed the precision. For example:</p>\n\n<pre><code>DECLARE @value decimal(10,2)\nSET @value = 99999999.99499 -- Works\nSET @value = 99999999.995 -- Error\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5548/"
] |
I'm writing a routine that validates data before inserting it into a database, and one of the steps is to see if numeric values fit the precision and scale of a Numeric(x,y) SQL-Server type.
I have the precision and scale from SQL-Server already, but what's the most efficient way in C# to get the precision and scale of a CLR value, or at least to test if it fits a given constraint?
At the moment, I'm converting the CLR value to a string, then looking for the location of the decimal point with .IndexOf(). Is there a faster way?
|
```
System.Data.SqlTypes.SqlDecimal.ConvertToPrecScale( new SqlDecimal (1234.56789), 8, 2)
```
gives 1234.57. it will truncate extra digits after the decimal place, and will throw an error rather than try to truncate digits before the decimal place (i.e. ConvertToPrecScale(12344234, 5,2)
|
192,715 |
<p>Take this non-compiling code for instance:</p>
<pre><code>public string GetPath(string basefolder, string[] extraFolders)
{
string version = Versioner.GetBuildAndDotNetVersions();
string callingModule = StackCrawler.GetCallingModuleName();
return AppendFolders(basefolder, version, callingModule, extraFolders);
}
private string AppendFolders(params string[] folders)
{
string outstring = folders[0];
for (int i = 1; i < folders.Length; i++)
{
string fixedPath = folders[i][0] == '\\' ? folders[i].Substring(1) : folders[i];
Path.Combine(outstring, fixedPath);
}
return outstring;
}
</code></pre>
<p>This example is a somewhat simplified version of testing code I am using. Please, I am only interested in solutions having directly to do with the param keyword. I know how lists and other similar things work.</p>
<p>Is there a way to "explode" the extraFolders array so that it's contents can be passed into AppendFolders along with other parameters?</p>
|
[
{
"answer_id": 192726,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 1,
"selected": false,
"text": "<p>A quick and dirty solution would be to build a List<string> from the items and then pass that (with ToArray()).</p>\n\n<p>Note that you don't need to test for the backslash. Path.Combine handles <a href=\"https://stackoverflow.com/questions/144439/building-a-directory-string-from-component-parts-in-c\">the dirty things rather fine</a>.</p>\n"
},
{
"answer_id": 192758,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "<p>Just pass it. The folders parameter is an array first. the \"params\" functionality is a little bit of compiler magic, but it's not required.</p>\n\n<pre><code>AppendFolders(extraFolders);\n</code></pre>\n\n<p>Now, it this particulat instance, you'll have to add some things to that array, first.</p>\n\n<pre><code>List<string> lstFolders = new List<string>(extraFolders);\nlstFolder.Insert(0, callingModule);\nlstFolder.Insert(0, version);\nlstFolder.Insert(0, basefolder);\nreturn AppendFolders(lstFolders.ToArray());\n</code></pre>\n"
},
{
"answer_id": 192797,
"author": "MojoFilter",
"author_id": 93,
"author_profile": "https://Stackoverflow.com/users/93",
"pm_score": 1,
"selected": false,
"text": "<p>I think OregonGhost's answer is probably the way you want to go. Just to elaborate on it, he's suggesting doing something like this:</p>\n\n<pre><code>public string GetPath(string basefolder, string[] extraFolders)\n{\n string version = Versioner.GetBuildAndDotNetVersions();\n string callingModule = StackCrawler.GetCallingModuleName();\n\n List<string> parameters = new List<string>(extraFolders.Length + 3);\n parameters.Add(basefolder);\n parameters.Add(version);\n parameters.Add(callingModule);\n parameters.AddRange(extraFolders);\n return AppendFolders(parameters.ToArray());\n}\n</code></pre>\n\n<p>And I don't mean that as a lesson on how to use Lists, just as a little clarification for anybody who may come along looking for the solution in the future.</p>\n"
},
{
"answer_id": 192817,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "<p>I'll quibble with the term \"collapse\", since it seems you really want to \"expand\". And I'm not sure what you mean by solutions \"having directly to do with params keyword\" and that \"you're not interested in workarounds\". In the end, you either have to pass a number of strings - which the compiler will magically package into an array - or an array of strings directly. That being said, my solution (without changing the interface) would go something like:</p>\n\n<pre><code>return AppendFolders(new string[] { basefolder, version, callingModule }.Concat(extraFolders).ToArray());\n</code></pre>\n\n<p>Edit: </p>\n\n<p>While you can't add an operator via extension methods, you could do:</p>\n\n<pre><code>return AppendFolders(new string[] { baseFolder, callingModuleName, version }.Concat(extraFolders));\n\npublic static T[] Concat<T>(this T[] a, T[] b) {\n return ((IEnumerable<T>)a).Concat(b).ToArray();\n}\n</code></pre>\n\n<p>But, if we're going to go that far - might as well just extend List<T> to handle this elegantly:</p>\n\n<pre><code>return AppendFolders(new Params<string>() { baseFolder, callingModuleName, version, extraFolders });\n\nclass Params<T> : List<T> {\n public void Add(IEnumerable<T> collection) {\n base.AddRange(collection);\n }\n\n public static implicit operator T[](Params<T> a) {\n return a.ToArray();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 193050,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": true,
"text": "<p>One option is to make the <code>params</code> parameter an <code>object[]</code>:</p>\n\n<pre><code>static string appendFolders(params object[] folders)\n { return (string) folders.Aggregate(\"\",(output, f) => \n Path.Combine( (string)output\n ,(f is string[]) \n ? appendFolders((object[])f)\n : ((string)f).TrimStart('\\\\')));\n }\n</code></pre>\n\n<p>If you want something more strongly-typed, another option is to create a custom union type with implicit conversion operators:</p>\n\n<pre><code> static string appendFolders(params StringOrArray[] folders)\n { return folders.SelectMany(x=>x.AsEnumerable())\n .Aggregate(\"\",\n (output, f)=>Path.Combine(output,f.TrimStart('\\\\')));\n }\n\n class StringOrArray\n { string[] array;\n\n public IEnumerable<string> AsEnumerable()\n { return soa.array;}\n\n public static implicit operator StringOrArray(string s) \n { return new StringOrArray{array=new[]{s}};}\n\n public static implicit operator StringOrArray(string[] s) \n { return new StringOrArray{array=s};}\n }\n</code></pre>\n\n<p>In either case, this <strong>will</strong> compile:</p>\n\n<pre><code>appendFolders(\"base\", \"v1\", \"module\", new[]{\"debug\",\"bin\"});\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9251/"
] |
Take this non-compiling code for instance:
```
public string GetPath(string basefolder, string[] extraFolders)
{
string version = Versioner.GetBuildAndDotNetVersions();
string callingModule = StackCrawler.GetCallingModuleName();
return AppendFolders(basefolder, version, callingModule, extraFolders);
}
private string AppendFolders(params string[] folders)
{
string outstring = folders[0];
for (int i = 1; i < folders.Length; i++)
{
string fixedPath = folders[i][0] == '\\' ? folders[i].Substring(1) : folders[i];
Path.Combine(outstring, fixedPath);
}
return outstring;
}
```
This example is a somewhat simplified version of testing code I am using. Please, I am only interested in solutions having directly to do with the param keyword. I know how lists and other similar things work.
Is there a way to "explode" the extraFolders array so that it's contents can be passed into AppendFolders along with other parameters?
|
One option is to make the `params` parameter an `object[]`:
```
static string appendFolders(params object[] folders)
{ return (string) folders.Aggregate("",(output, f) =>
Path.Combine( (string)output
,(f is string[])
? appendFolders((object[])f)
: ((string)f).TrimStart('\\')));
}
```
If you want something more strongly-typed, another option is to create a custom union type with implicit conversion operators:
```
static string appendFolders(params StringOrArray[] folders)
{ return folders.SelectMany(x=>x.AsEnumerable())
.Aggregate("",
(output, f)=>Path.Combine(output,f.TrimStart('\\')));
}
class StringOrArray
{ string[] array;
public IEnumerable<string> AsEnumerable()
{ return soa.array;}
public static implicit operator StringOrArray(string s)
{ return new StringOrArray{array=new[]{s}};}
public static implicit operator StringOrArray(string[] s)
{ return new StringOrArray{array=s};}
}
```
In either case, this **will** compile:
```
appendFolders("base", "v1", "module", new[]{"debug","bin"});
```
|
192,718 |
<p>I need to run a JNDI provider without the overhead of a J2EE container. I've tried to follow the directions in this <a href="http://www.javaworld.com/javaworld/jw-04-2002/jw-0419-jndi.html" rel="noreferrer">article</a>, which describes (on page 3) exactly what I want to do. Unfortunately, these directions fail. I had to add the jboss-common.jar to my classpath too. Once I did that, I get a stack trace:</p>
<pre><code>$ java org.jnp.server.Main
0 [main] DEBUG
org.jboss.naming.Naming - Creating
NamingServer stub, theServer=null,rmiPort=0,clientSocketFactory=null,serverSocketFactory=org.jboss.net.sockets.DefaultSocketFactory@ad093076[bindAddress=null]
Exception in thread "main"
java.lang.NullPointerException
at org.jnp.server.Main.getNamingInstance(Main.java:301)
at org.jnp.server.Main.initJnpInvoker(Main.java:354)
at org.jnp.server.Main.start(Main.java:316)
at org.jnp.server.Main.main(Main.java:104)
</code></pre>
<p>I'm hoping to make this work, but I would also be open to other lightweight standalone JNDI providers. All of this is to make ActiveMQ work, and if somebody can suggest another lightweight JMS provider that works well outside of the vm the clients are in without a full blown app server that would work too. </p>
|
[
{
"answer_id": 192727,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 1,
"selected": false,
"text": "<p>The JBoss JMQ can also be run with just the MicroKernel and a very minimal set of libraries. The JBoss AS installer has options for \"profiles\" one of which is for a standalone JMQ. It also allows you to pick and choose components (though it doesn't help you with dependencies too much). Have you tried running the installer?</p>\n"
},
{
"answer_id": 192936,
"author": "KC Baltz",
"author_id": 9910,
"author_profile": "https://Stackoverflow.com/users/9910",
"pm_score": 2,
"selected": false,
"text": "<p>Use a jndi.properties file like this:</p>\n\n<pre><code>java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory\n\n# use the following property to configure the default connector\njava.naming.provider.url=tcp://jmshost:61616\n\n# use the following property to specify the JNDI name the connection factory\n# should appear as. \n#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry\n\n# register some queues in JNDI using the form\n# queue.[jndiName] = [physicalName]\n#queue.MyQueue = example.MyQueue\n\n\n# register some topics in JNDI using the form\n# topic.[jndiName] = [physicalName]\ntopic.myTopic = MY.TOPIC\n</code></pre>\n\n<p>Make sure that this file is in your classpath. Then you can lookup the topic/queue like this (minus appropriate try/catches):</p>\n\n<pre><code>context = new InitialContext(properties);\n\ncontext = (Context) context.lookup(\"java:comp/env/jms\");\n\ntopicConnectionFactory = (TopicConnectionFactory) context.lookup(\"ConnectionFactory\");\n\ntopic = (Topic) context.lookup(\"myTopic\");\n</code></pre>\n"
},
{
"answer_id": 197073,
"author": "James Strachan",
"author_id": 2068211,
"author_profile": "https://Stackoverflow.com/users/2068211",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://activemq.apache.org/\" rel=\"noreferrer\">Apache ActiveMQ</a> already comes with an integrated lightweight JNDI provider. See <a href=\"http://activemq.apache.org/jndi-support.html\" rel=\"noreferrer\">these instructions on using it</a>. </p>\n\n<p>Basically you just add the jndi.properties file to the classpath and you're done.</p>\n\n<pre><code>java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory\n\n# use the following property to configure the default connector\njava.naming.provider.url = failover:tcp://localhost:61616\n\n# use the following property to specify the JNDI name the connection factory\n# should appear as. \n#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry\n\n# register some queues in JNDI using the form\n# queue.[jndiName] = [physicalName]\nqueue.MyQueue = example.MyQueue\n\n\n# register some topics in JNDI using the form\n# topic.[jndiName] = [physicalName]\ntopic.MyTopic = example.MyTopic\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13816/"
] |
I need to run a JNDI provider without the overhead of a J2EE container. I've tried to follow the directions in this [article](http://www.javaworld.com/javaworld/jw-04-2002/jw-0419-jndi.html), which describes (on page 3) exactly what I want to do. Unfortunately, these directions fail. I had to add the jboss-common.jar to my classpath too. Once I did that, I get a stack trace:
```
$ java org.jnp.server.Main
0 [main] DEBUG
org.jboss.naming.Naming - Creating
NamingServer stub, theServer=null,rmiPort=0,clientSocketFactory=null,serverSocketFactory=org.jboss.net.sockets.DefaultSocketFactory@ad093076[bindAddress=null]
Exception in thread "main"
java.lang.NullPointerException
at org.jnp.server.Main.getNamingInstance(Main.java:301)
at org.jnp.server.Main.initJnpInvoker(Main.java:354)
at org.jnp.server.Main.start(Main.java:316)
at org.jnp.server.Main.main(Main.java:104)
```
I'm hoping to make this work, but I would also be open to other lightweight standalone JNDI providers. All of this is to make ActiveMQ work, and if somebody can suggest another lightweight JMS provider that works well outside of the vm the clients are in without a full blown app server that would work too.
|
[Apache ActiveMQ](http://activemq.apache.org/) already comes with an integrated lightweight JNDI provider. See [these instructions on using it](http://activemq.apache.org/jndi-support.html).
Basically you just add the jndi.properties file to the classpath and you're done.
```
java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory
# use the following property to configure the default connector
java.naming.provider.url = failover:tcp://localhost:61616
# use the following property to specify the JNDI name the connection factory
# should appear as.
#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry
# register some queues in JNDI using the form
# queue.[jndiName] = [physicalName]
queue.MyQueue = example.MyQueue
# register some topics in JNDI using the form
# topic.[jndiName] = [physicalName]
topic.MyTopic = example.MyTopic
```
|
192,721 |
<p>In <a href="https://stackoverflow.com/users/23233/mmalc">@mmalc's</a> <a href="https://stackoverflow.com/questions/155964/what-are-best-practices-that-you-use-when-writing-objective-c-and-cocoa#156288">response</a> to <a href="https://stackoverflow.com/questions/155964/what-are-best-practices-that-you-use-when-writing-objective-c-and-cocoa">this question</a> he states that "In general you should <em>not</em> use accessor methods in dealloc (or init)." Why does mmalc say this?</p>
<p>The only really reasons I can think of are performance and avoiding unknown side-effects of @dynamic setters.</p>
<p>Discussion?</p>
|
[
{
"answer_id": 192852,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 5,
"selected": false,
"text": "<p>It's basically a guideline to minimize the potential for bugs.</p>\n\n<p>In this case there is the (possibility) that your setter/getter may inadvertently make direct or indirect assumptions about the state of the object. These assumptions could be a problem when the object is in the midst of being setup or destroyed.</p>\n\n<p>For example in the code below the observer does not know that 'Example' is being destroyed and could assume that other properties, which have already been freed, are valid. </p>\n\n<p>(You could argue that your object should remove all observers before tearing itself down, which would be good practice, and another guideline to prevent inadvertent problems).</p>\n\n<pre><code>@implementation Example\n\n-(void) setFoo:(Foo*)foo\n{\n _foo = foo;\n [_observer onPropertyChange:self object:foo];\n}\n\n-(void) dealloc\n{\n ...\n self.foo = nil;\n}\n\n@end\n</code></pre>\n"
},
{
"answer_id": 193880,
"author": "mmalc",
"author_id": 23233,
"author_profile": "https://Stackoverflow.com/users/23233",
"pm_score": 4,
"selected": false,
"text": "<p>You answered your own question:</p>\n\n<ol>\n<li>Performance may be a perfectly adequate reason in itself (especially if your accessors are atomic).</li>\n<li>You should avoid any side-effects that accessors may have.</li>\n</ol>\n\n<p>The latter is particularly an issue if your class may be subclassed.</p>\n\n<p>It's not clear, though, why this is addressed specifically at <em>Objective-C 2</em> accessors? The same principles apply whether you use declared properties or write accessors yourself.</p>\n"
},
{
"answer_id": 227555,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 5,
"selected": true,
"text": "<p>It is all about using idiomatically consistent code. If you pattern all of your code appropriately there are sets of rules that guarantee that using an accessor in init/dealloc is safe.</p>\n\n<p>The big issue is that (as mmalc said) the code the sets up the properties default state should not go through an accessor because it leads to all sorts of nasty issues. The catch is that there is no reason init has to setup the default state of a property. For a number of reasons I have been moving to accessors that self initialize, like the simple example below:</p>\n\n<pre><code>- (NSMutableDictionary *) myMutableDict {\n if (!myMutableDict) {\n myMutableDict = [[NSMutableDictionary alloc] init];\n }\n\n return myMutableDict;\n}\n</code></pre>\n\n<p>This style of property initialization allows one to defer a lot of init code that may not actually be necessary. In the above case init is not responsible for initing the properties state, and it is completely safe (even necessary) for one to use the accessors in the init method.</p>\n\n<p>Admittedly this does impose additional restrictions on your code, for instance, subclasses with custom accessors for a property in the superclass must call the superclasses accessor, but those restrictions are not out of line with various other restrictions common in Cocoa.</p>\n"
},
{
"answer_id": 1579457,
"author": "zaph",
"author_id": 451475,
"author_profile": "https://Stackoverflow.com/users/451475",
"pm_score": 2,
"selected": false,
"text": "<p>It may be that the setter has logic that should run or perhaps the implementation used an ivar with name different from the getter/setter or perhaps two ivars that need to be released and/or have their value set to nil. The only sure way is to call the setter. It is the setter's responsibility to be written in such a way that undesirable side effects do not occur when called during init or dealloc.</p>\n\n<p>From \"Cocoa Design Patterns\", Buck, Yacktman, pp 115: \"... there is no practical alternative to using accessors when you use synthesized instance variables with the modern Objective-C runtime or ...\"</p>\n"
},
{
"answer_id": 4588671,
"author": "FeifanZ",
"author_id": 472768,
"author_profile": "https://Stackoverflow.com/users/472768",
"pm_score": 0,
"selected": false,
"text": "<p>In fact, for a class that comes and goes rather often (like a detail view controller), you want to use the accessor in the init; otherwise, you could end up releasing a value in viewDidUnload that you try to access later (they show that in CS193P...)</p>\n"
},
{
"answer_id": 8451621,
"author": "Sulthan",
"author_id": 669586,
"author_profile": "https://Stackoverflow.com/users/669586",
"pm_score": 0,
"selected": false,
"text": "<p>You can create the same problems by NOT calling the setter when allocating/deallocating.</p>\n\n<p>I don't think you can achieve anything by using retain/release directly in init/dealloc. You just change the set of possible bugs.</p>\n\n<p>Everytime you have to think about the order of property allocation/deallocation.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23113/"
] |
In [@mmalc's](https://stackoverflow.com/users/23233/mmalc) [response](https://stackoverflow.com/questions/155964/what-are-best-practices-that-you-use-when-writing-objective-c-and-cocoa#156288) to [this question](https://stackoverflow.com/questions/155964/what-are-best-practices-that-you-use-when-writing-objective-c-and-cocoa) he states that "In general you should *not* use accessor methods in dealloc (or init)." Why does mmalc say this?
The only really reasons I can think of are performance and avoiding unknown side-effects of @dynamic setters.
Discussion?
|
It is all about using idiomatically consistent code. If you pattern all of your code appropriately there are sets of rules that guarantee that using an accessor in init/dealloc is safe.
The big issue is that (as mmalc said) the code the sets up the properties default state should not go through an accessor because it leads to all sorts of nasty issues. The catch is that there is no reason init has to setup the default state of a property. For a number of reasons I have been moving to accessors that self initialize, like the simple example below:
```
- (NSMutableDictionary *) myMutableDict {
if (!myMutableDict) {
myMutableDict = [[NSMutableDictionary alloc] init];
}
return myMutableDict;
}
```
This style of property initialization allows one to defer a lot of init code that may not actually be necessary. In the above case init is not responsible for initing the properties state, and it is completely safe (even necessary) for one to use the accessors in the init method.
Admittedly this does impose additional restrictions on your code, for instance, subclasses with custom accessors for a property in the superclass must call the superclasses accessor, but those restrictions are not out of line with various other restrictions common in Cocoa.
|
192,725 |
<p>I have just started learning Erlang and am trying out some Project Euler problems to get started. However, I seem to be able to do any operations on large sequences without crashing the erlang shell.</p>
<p>Ie.,even this:</p>
<pre><code>list:seq(1,64000000).
</code></pre>
<p>crashes erlang, with the error:</p>
<p>eheap_alloc: Cannot allocate 467078560 bytes of memory (of type "heap").</p>
<p>Actually # of bytes varies of course.</p>
<p>Now half a gig is a lot of memory, but a system with 4 gigs of RAM and plenty of space for virtual memory should be able to handle it.</p>
<p>Is there a way to let erlang use more memory?</p>
|
[
{
"answer_id": 192771,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 2,
"selected": false,
"text": "<p>Possibly a noob answer (I'm a Java dev), but the JVM artificially limits the amount of memory to help detect memory leaks more easily. Perhaps erlang has similar restrictions in place?</p>\n"
},
{
"answer_id": 193033,
"author": "Marcin",
"author_id": 21640,
"author_profile": "https://Stackoverflow.com/users/21640",
"pm_score": 2,
"selected": false,
"text": "<p>Also, both windows and linux have limits on the maximum amount of memory an image can occupy\nAs I recall on linux it is half a gigabyte. </p>\n\n<p>The real question is why these operations aren't being done lazily ;)</p>\n"
},
{
"answer_id": 193804,
"author": "Darius Bacon",
"author_id": 27024,
"author_profile": "https://Stackoverflow.com/users/27024",
"pm_score": 5,
"selected": true,
"text": "<p>Your OS may have a default limit on the size of a user process. On Linux you can change this with ulimit.</p>\n\n<p>You probably want to iterate over these 64000000 numbers without needing them all in memory at once. Lazy lists let you write code similar in style to the list-all-at-once code:</p>\n\n<pre><code>-module(lazy).\n-export([seq/2]).\n\nseq(M, N) when M =< N ->\n fun() -> [M | seq(M+1, N)] end;\nseq(_, _) ->\n fun () -> [] end.\n\n1> Ns = lazy:seq(1, 64000000).\n#Fun<lazy.0.26378159>\n2> hd(Ns()).\n1\n3> Ns2 = tl(Ns()).\n#Fun<lazy.0.26378159>\n4> hd(Ns2()).\n2\n</code></pre>\n"
},
{
"answer_id": 194315,
"author": "FlinkmanSV",
"author_id": 15054,
"author_profile": "https://Stackoverflow.com/users/15054",
"pm_score": 2,
"selected": false,
"text": "<p>This is a feature. We do not want one processes to consume all memory. It like the fuse box in your house. For the safety of us all.</p>\n\n<p>You have to know erlangs recovery model to understand way they let the process just die.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7856/"
] |
I have just started learning Erlang and am trying out some Project Euler problems to get started. However, I seem to be able to do any operations on large sequences without crashing the erlang shell.
Ie.,even this:
```
list:seq(1,64000000).
```
crashes erlang, with the error:
eheap\_alloc: Cannot allocate 467078560 bytes of memory (of type "heap").
Actually # of bytes varies of course.
Now half a gig is a lot of memory, but a system with 4 gigs of RAM and plenty of space for virtual memory should be able to handle it.
Is there a way to let erlang use more memory?
|
Your OS may have a default limit on the size of a user process. On Linux you can change this with ulimit.
You probably want to iterate over these 64000000 numbers without needing them all in memory at once. Lazy lists let you write code similar in style to the list-all-at-once code:
```
-module(lazy).
-export([seq/2]).
seq(M, N) when M =< N ->
fun() -> [M | seq(M+1, N)] end;
seq(_, _) ->
fun () -> [] end.
1> Ns = lazy:seq(1, 64000000).
#Fun<lazy.0.26378159>
2> hd(Ns()).
1
3> Ns2 = tl(Ns()).
#Fun<lazy.0.26378159>
4> hd(Ns2()).
2
```
|
192,736 |
<p>A word of warning: I'm a n00b to <code>git</code> in general. My team uses feature branches in <code>svn</code>, and I'd like to use <code>git-svn</code> to track my work on a particular feature branch. I've been (roughly) following <a href="http://andy.delcambre.com/2008/03/04/git-svn-workflow.html" rel="noreferrer">Andy Delcambre's post</a> to set up my local <code>git</code> repo, but those instructions seem to have led <code>git</code> to pick the <code>svn</code> branch that had changed most recently as the remote repository; the problem is that's not the branch I care about. How do I control which branch <code>git-svn</code> uses? Or am I approaching this completely wrong?</p>
<p>UPDATE: I did use the <code>-T</code>, <code>-b</code>, and <code>-t</code> options (in my case because the <code>svn</code> repo has multiple projects, but I want the <code>git</code> repo to contain only the project I'm working on).</p>
|
[
{
"answer_id": 192763,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "<p>I use git-svn but I haven't used the features that interoperate with SVN branches. Having said that, I notice that the tutorial you were following didn't use the <a href=\"http://git-scm.com/docs/git-svn\" rel=\"nofollow noreferrer\">-T, -b, -t</a> options to git svn init. These options tell git-svn what the upstream trunk/branches/tags directories are named, which might be important in your situation.</p>\n"
},
{
"answer_id": 197453,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 7,
"selected": true,
"text": "<p>Muchas gracias to Bart's Blog for this handy <a href=\"http://www.jukie.net/~bart/blog/svn-branches-in-git\" rel=\"noreferrer\">reference for svn branches in git</a>. Apparently all I needed was to specify a remote branch when creating the <code>git</code> branch, e.g., </p>\n\n<pre><code>git checkout -b git-topic-branch-foo foo\n</code></pre>\n\n<p>where <code>foo</code> is the name of the remote branch.</p>\n"
},
{
"answer_id": 696304,
"author": "Sam Mulube",
"author_id": 84492,
"author_profile": "https://Stackoverflow.com/users/84492",
"pm_score": 5,
"selected": false,
"text": "<p>You might also have a look at this: <a href=\"http://www.robbyonrails.com/articles/2008/04/10/git-svn-is-a-gateway-drug\" rel=\"noreferrer\">git-svn is a gateway drug - robby on rails</a>.</p>\n\n<p>I used something like this when I needed to make sure that my local branch was pointing to the correct remote svn branch:</p>\n\n<pre><code>git branch -r\n</code></pre>\n\n<p>to get the name of the remote branch I want to be tracking. Then</p>\n\n<pre><code>git reset --hard remotes/svn-branch-name\n</code></pre>\n\n<p>to explicitly change my local branch to point to a different remote branch.</p>\n"
},
{
"answer_id": 7268987,
"author": "android.weasel",
"author_id": 444234,
"author_profile": "https://Stackoverflow.com/users/444234",
"pm_score": 3,
"selected": false,
"text": "<p>I needed to run 'git svn fetch' first, since the branch I wanted to associate with had been created after my git client.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4203/"
] |
A word of warning: I'm a n00b to `git` in general. My team uses feature branches in `svn`, and I'd like to use `git-svn` to track my work on a particular feature branch. I've been (roughly) following [Andy Delcambre's post](http://andy.delcambre.com/2008/03/04/git-svn-workflow.html) to set up my local `git` repo, but those instructions seem to have led `git` to pick the `svn` branch that had changed most recently as the remote repository; the problem is that's not the branch I care about. How do I control which branch `git-svn` uses? Or am I approaching this completely wrong?
UPDATE: I did use the `-T`, `-b`, and `-t` options (in my case because the `svn` repo has multiple projects, but I want the `git` repo to contain only the project I'm working on).
|
Muchas gracias to Bart's Blog for this handy [reference for svn branches in git](http://www.jukie.net/~bart/blog/svn-branches-in-git). Apparently all I needed was to specify a remote branch when creating the `git` branch, e.g.,
```
git checkout -b git-topic-branch-foo foo
```
where `foo` is the name of the remote branch.
|
192,748 |
<p>I am working on a webpage in ASP.Net/C# that uses absolute positioning for a textbox, for several in fact. It was working just fine, until I added some more text boxes. That is, the existing text boxes still positioned correctly, but the new ones did not, despite the fact that I created new styles in the CSS for them just like the others. An exampe is below:</p>
<pre><code>.pieceBox {
position: absolute;
top: 425px;
left: 133px;
background-color: White;
color: Black;
width: 132px;
font-weight: bold;
text-align: center;
}
</code></pre>
<p>Identical styles in the same CSS file (with different names of course) both above and below this one work fine. I have checked, double-checked, and triple-checked the name of the style in the CssClass attribute of the and it is correct. However, no matter what I do, including giving it a new name, copying the old entries, and renaming them, etc., these three new text boxes position themselves at the top of the page, whereas the others show in their correct absolute positions. I looked at the aspx source page and made sure they are not in some other DIV, etc. I am at my wits end with it. I did come up with a workaround for now, but it is not how I want to leave it (involves programmatically creating some HTML inside an Asp:Literal.)</p>
<p>I checked the resulting source (via IE's viewsource) and the class is set correctly in the resulting HTML.</p>
<p>One more thing in case this matters; this website project was originally created in VS 2005 and converted to VS 2008 format. Not that it should matter, but thought I would mention it.</p>
<p>Has anyone else experienced this type of behavior?</p>
|
[
{
"answer_id": 192836,
"author": "ljubomir",
"author_id": 11506,
"author_profile": "https://Stackoverflow.com/users/11506",
"pm_score": 0,
"selected": false,
"text": "<p>It is difficult to explain problems like this if no actual code is provided, but my first guess would be that you're having problem with new controls that are not using the same parent containers as the old ones.</p>\n\n<p>Have you checked the css rules that apply for parent containers of properly working text boxes? They usually should be set to \"position: relative;\" if you want to have your child controls aligned according to them.</p>\n\n<p>Also make sure that the layout problem isn't occurring due to overlapping of the controls i.e. two text boxes might have similar or near positions and then one comes over another.</p>\n\n<p>In any case, if you want proper and straight solution to your problem, i would suggest that you post part of your code. </p>\n"
},
{
"answer_id": 193549,
"author": "Bryan M.",
"author_id": 4636,
"author_profile": "https://Stackoverflow.com/users/4636",
"pm_score": 1,
"selected": false,
"text": "<p>If you have absolutely positioned elements that have a parent that is either absolutely or relatively positioned, they will position themselves relative to their container instead of the whole page.</p>\n\n<p>In other words, your elements might be positioning themselves from different origin points.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26895/"
] |
I am working on a webpage in ASP.Net/C# that uses absolute positioning for a textbox, for several in fact. It was working just fine, until I added some more text boxes. That is, the existing text boxes still positioned correctly, but the new ones did not, despite the fact that I created new styles in the CSS for them just like the others. An exampe is below:
```
.pieceBox {
position: absolute;
top: 425px;
left: 133px;
background-color: White;
color: Black;
width: 132px;
font-weight: bold;
text-align: center;
}
```
Identical styles in the same CSS file (with different names of course) both above and below this one work fine. I have checked, double-checked, and triple-checked the name of the style in the CssClass attribute of the and it is correct. However, no matter what I do, including giving it a new name, copying the old entries, and renaming them, etc., these three new text boxes position themselves at the top of the page, whereas the others show in their correct absolute positions. I looked at the aspx source page and made sure they are not in some other DIV, etc. I am at my wits end with it. I did come up with a workaround for now, but it is not how I want to leave it (involves programmatically creating some HTML inside an Asp:Literal.)
I checked the resulting source (via IE's viewsource) and the class is set correctly in the resulting HTML.
One more thing in case this matters; this website project was originally created in VS 2005 and converted to VS 2008 format. Not that it should matter, but thought I would mention it.
Has anyone else experienced this type of behavior?
|
If you have absolutely positioned elements that have a parent that is either absolutely or relatively positioned, they will position themselves relative to their container instead of the whole page.
In other words, your elements might be positioning themselves from different origin points.
|
192,796 |
<p>Suppose I have an M-file that calculates, for exampleת <code>d=a+b+c</code> (The values on <code>a</code>, <code>b</code>, <code>c</code> were given earlier). </p>
<p>What command should I use in order to produce an output M-file showing the result of this sum?</p>
|
[
{
"answer_id": 192841,
"author": "Scottie T",
"author_id": 6688,
"author_profile": "https://Stackoverflow.com/users/6688",
"pm_score": 1,
"selected": false,
"text": "<pre><code>disp(num2str(d));\n</code></pre>\n"
},
{
"answer_id": 192859,
"author": "Azim J",
"author_id": 4612,
"author_profile": "https://Stackoverflow.com/users/4612",
"pm_score": 3,
"selected": false,
"text": "<p>In Matlab a semicolon \";\" at the end of a line suppresses output. So,</p>\n\n<pre><code>>> d=1+2;\n>> d=1+2\nd = \n 3\n</code></pre>\n\n<p>Or you can use <em>disp</em> as in the <a href=\"https://stackoverflow.com/questions/192796/creating-output-m-file-in-matlab#192841\">first answer</a>.</p>\n\n<pre><code>>> disp(num2str(d));\n3\n</code></pre>\n\n<p>If you want to write the values of a variable to a file you can use either <em>dlmwrite</em> (use Matlab's help function to get more info) or <em>save</em> commands. For <em>dlmwrite</em>, the usage is basically </p>\n\n<pre><code>>> dlmwrite('filename',d,',') \n</code></pre>\n\n<p>which writes the vector (matrix), d, to the text file named <em>filename</em> using a comma as the delimiter between elements. </p>\n\n<p>The other option is to use the <em>save</em> command, as in</p>\n\n<pre><code>>> save('filename','d')\n</code></pre>\n\n<p>which will save the variable 'd' to a MAT file (see <em>help save</em> for more information). Hope this helps?</p>\n"
},
{
"answer_id": 193765,
"author": "b3.",
"author_id": 14946,
"author_profile": "https://Stackoverflow.com/users/14946",
"pm_score": 2,
"selected": false,
"text": "<p>To expand on <a href=\"https://stackoverflow.com/questions/192796/creating-output-m-file-in-matlab#192859\">Azim's answer</a>, the <strong>save</strong> command can be used to save variables to a text file. In your case you would use:</p>\n\n<pre><code>save 'filename' d -ascii\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Suppose I have an M-file that calculates, for exampleת `d=a+b+c` (The values on `a`, `b`, `c` were given earlier).
What command should I use in order to produce an output M-file showing the result of this sum?
|
In Matlab a semicolon ";" at the end of a line suppresses output. So,
```
>> d=1+2;
>> d=1+2
d =
3
```
Or you can use *disp* as in the [first answer](https://stackoverflow.com/questions/192796/creating-output-m-file-in-matlab#192841).
```
>> disp(num2str(d));
3
```
If you want to write the values of a variable to a file you can use either *dlmwrite* (use Matlab's help function to get more info) or *save* commands. For *dlmwrite*, the usage is basically
```
>> dlmwrite('filename',d,',')
```
which writes the vector (matrix), d, to the text file named *filename* using a comma as the delimiter between elements.
The other option is to use the *save* command, as in
```
>> save('filename','d')
```
which will save the variable 'd' to a MAT file (see *help save* for more information). Hope this helps?
|
192,801 |
<p>Trivial data binding examples are just that, trivial. I want to do something a little more complicated and am wondering if there's an easy, built in way to handle it.</p>
<pre><code>public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
List<DataStruct> list = new List<DataStruct>()
{
new DataStruct(){Name = "Name 1", Value = "Value 1", ComplexValue = new ComplexValue(){Part1 = "1:P1", Part2 = "1:P2"}},
new DataStruct(){Name = "Name 2", Value = "Value 2", ComplexValue = new ComplexValue(){Part1 = "2:P1", Part2 = "2:P2"}}
};
listBox1.DataSource = list;
listBox1.DisplayMember = "ComplexValue.Part1";
}
}
public class DataStruct
{
public string Name { get; set; }
public string Value { get; set; }
public ComplexValue ComplexValue { get; set; }
}
public class ComplexValue
{
public string Part1 { get; set; }
public string Part2 { get; set; }
}
</code></pre>
<p>Is there an easy way to get the value of the Part1 property to be set as the display member for a list of DataStruct items? Above I tried something that I thought made sense, but it just defaults back to the ToString() on DataStruct. I can work around it if necessary, I was just wondering if there was something built into the data binding that would handle more complex data binding like above.</p>
<p>Edit: Using WinForms</p>
|
[
{
"answer_id": 192841,
"author": "Scottie T",
"author_id": 6688,
"author_profile": "https://Stackoverflow.com/users/6688",
"pm_score": 1,
"selected": false,
"text": "<pre><code>disp(num2str(d));\n</code></pre>\n"
},
{
"answer_id": 192859,
"author": "Azim J",
"author_id": 4612,
"author_profile": "https://Stackoverflow.com/users/4612",
"pm_score": 3,
"selected": false,
"text": "<p>In Matlab a semicolon \";\" at the end of a line suppresses output. So,</p>\n\n<pre><code>>> d=1+2;\n>> d=1+2\nd = \n 3\n</code></pre>\n\n<p>Or you can use <em>disp</em> as in the <a href=\"https://stackoverflow.com/questions/192796/creating-output-m-file-in-matlab#192841\">first answer</a>.</p>\n\n<pre><code>>> disp(num2str(d));\n3\n</code></pre>\n\n<p>If you want to write the values of a variable to a file you can use either <em>dlmwrite</em> (use Matlab's help function to get more info) or <em>save</em> commands. For <em>dlmwrite</em>, the usage is basically </p>\n\n<pre><code>>> dlmwrite('filename',d,',') \n</code></pre>\n\n<p>which writes the vector (matrix), d, to the text file named <em>filename</em> using a comma as the delimiter between elements. </p>\n\n<p>The other option is to use the <em>save</em> command, as in</p>\n\n<pre><code>>> save('filename','d')\n</code></pre>\n\n<p>which will save the variable 'd' to a MAT file (see <em>help save</em> for more information). Hope this helps?</p>\n"
},
{
"answer_id": 193765,
"author": "b3.",
"author_id": 14946,
"author_profile": "https://Stackoverflow.com/users/14946",
"pm_score": 2,
"selected": false,
"text": "<p>To expand on <a href=\"https://stackoverflow.com/questions/192796/creating-output-m-file-in-matlab#192859\">Azim's answer</a>, the <strong>save</strong> command can be used to save variables to a text file. In your case you would use:</p>\n\n<pre><code>save 'filename' d -ascii\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16979/"
] |
Trivial data binding examples are just that, trivial. I want to do something a little more complicated and am wondering if there's an easy, built in way to handle it.
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
List<DataStruct> list = new List<DataStruct>()
{
new DataStruct(){Name = "Name 1", Value = "Value 1", ComplexValue = new ComplexValue(){Part1 = "1:P1", Part2 = "1:P2"}},
new DataStruct(){Name = "Name 2", Value = "Value 2", ComplexValue = new ComplexValue(){Part1 = "2:P1", Part2 = "2:P2"}}
};
listBox1.DataSource = list;
listBox1.DisplayMember = "ComplexValue.Part1";
}
}
public class DataStruct
{
public string Name { get; set; }
public string Value { get; set; }
public ComplexValue ComplexValue { get; set; }
}
public class ComplexValue
{
public string Part1 { get; set; }
public string Part2 { get; set; }
}
```
Is there an easy way to get the value of the Part1 property to be set as the display member for a list of DataStruct items? Above I tried something that I thought made sense, but it just defaults back to the ToString() on DataStruct. I can work around it if necessary, I was just wondering if there was something built into the data binding that would handle more complex data binding like above.
Edit: Using WinForms
|
In Matlab a semicolon ";" at the end of a line suppresses output. So,
```
>> d=1+2;
>> d=1+2
d =
3
```
Or you can use *disp* as in the [first answer](https://stackoverflow.com/questions/192796/creating-output-m-file-in-matlab#192841).
```
>> disp(num2str(d));
3
```
If you want to write the values of a variable to a file you can use either *dlmwrite* (use Matlab's help function to get more info) or *save* commands. For *dlmwrite*, the usage is basically
```
>> dlmwrite('filename',d,',')
```
which writes the vector (matrix), d, to the text file named *filename* using a comma as the delimiter between elements.
The other option is to use the *save* command, as in
```
>> save('filename','d')
```
which will save the variable 'd' to a MAT file (see *help save* for more information). Hope this helps?
|
192,824 |
<p>Can I ignore a folder on svn checkout? I need to ignore DOCs folder on checkout at my build server.</p>
<p><strong>edit:</strong> Ignore externals isn't an option. I have some externals that I need.</p>
|
[
{
"answer_id": 192830,
"author": "Peter Parker",
"author_id": 23264,
"author_profile": "https://Stackoverflow.com/users/23264",
"pm_score": 1,
"selected": false,
"text": "<p>No, ignore is only for adding files.<br>\nYou can use sparse checkouts (if you use svn 1.5)</p>\n"
},
{
"answer_id": 192833,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, <a href=\"http://subversion.apache.org/docs/release-notes/1.5.html\" rel=\"nofollow noreferrer\">Subversion 1.5</a> has a feature called <a href=\"http://subversion.apache.org/docs/release-notes/1.5.html#sparse-checkouts\" rel=\"nofollow noreferrer\">Sparse checkouts</a> that can do exactly this sort of thing.</p>\n"
},
{
"answer_id": 192835,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "<p>You could put the docs folder in an external repository and then use <code>svn checkout --ignore-externals</code>.</p>\n"
},
{
"answer_id": 197091,
"author": "Nik Reiman",
"author_id": 14302,
"author_profile": "https://Stackoverflow.com/users/14302",
"pm_score": 1,
"selected": false,
"text": "<p>As a few others have mentioned, you can just use svn:externals properties and then the --ignore-externals option when you checkout. One thing to note, however, is that svn:externals does <em>not</em> necessarily need to refer to another repository. It can be a reference to some other folder in the same repo.</p>\n"
},
{
"answer_id": 218131,
"author": "Jon Topper",
"author_id": 6945,
"author_profile": "https://Stackoverflow.com/users/6945",
"pm_score": 8,
"selected": true,
"text": "<p>You can't directly ignore folders on a checkout, but you can use sparse checkouts in svn 1.5. For example:</p>\n\n<pre><code>$ svn co http://subversion/project/trunk my_checkout --depth immediates\n</code></pre>\n\n<p>This will check files and directories from your project trunk into 'my_checkout', but not recurse into those directories. Eg:</p>\n\n<pre><code>$ cd my_checkout && ls\nbar/ baz foo xyzzy/\n</code></pre>\n\n<p>Then to get the contents of 'bar' down:</p>\n\n<pre><code>$ cd bar && svn update --set-depth infinity\n</code></pre>\n"
},
{
"answer_id": 218160,
"author": "mxcl",
"author_id": 6444,
"author_profile": "https://Stackoverflow.com/users/6444",
"pm_score": 3,
"selected": false,
"text": "<p>With versions prior to 1.5 I have found that if you checkout only the top most folder and then selectively update, from then on updates only effect what you have checked out. Ie.</p>\n\n<pre><code>svn co -N foo\ncd foo\nsvn up -N bar\nsvn up\n</code></pre>\n\n<p>The -N flag makes the operation non-recursive. The above will not check out anything else at the foo level, eg. say there is a folder <code>lala</code>, the final svn up will not check out that folder, but it will update <code>bar</code>.</p>\n\n<p>But at a later time you can <code>svn up lala</code> and thus, add it to the checkout.</p>\n\n<p>Presumably this also works with 1.5.</p>\n"
},
{
"answer_id": 4492129,
"author": "bv.",
"author_id": 215846,
"author_profile": "https://Stackoverflow.com/users/215846",
"pm_score": 2,
"selected": false,
"text": "<p>I have recently resolved the same task.\nThe idea is to get the immediate list of folder/files under the repository exclude the entries you need, then check out the remaining folders and update the immediate files if any.\nHere is the solution:</p>\n\n<pre><code> # Path to the svn repository to be checked out\nrpath=https://svn-repo.company.com/sw/trunk/ && \\\n # This files are to be excluded (folders are ending with '/')\n # this is a regex pattern with OR ('|') between enties to be excluded\nexcludep='docs_folder/tests_folder/|huge_folder/|file1|file2' && \\\n # Get list of the files/folders right under the repository path\nfiltered=`svn ls $rpath | egrep -v $excludep` && \\\n # Get list of files out of filtered - they need to be 'uped'\nfiles=`echo $filtered | sed 's| |\\n|g' | egrep '^.*[^/]$'` && \\\n # Get list of folders out of filtered - they need to be 'coed'\nfolders=`echo $filtered | sed 's| |\\n|g' | egrep '^.*[/]$'` && \\\n # Initial nonrecursive checkout of repository - just empty\n # to the current (./) working directory\nsvn co $rpath ./ --depth empty && \\\n # Update the files\nsvn up $files &&\\\n # Check out the all other folders finally.\nsvn co `echo $folders | sed \"s|\\<|$rpath|g\"`\n</code></pre>\n\n<p>Change to source working directory. Copy the commands. Paste. Change appropriate URL and exclude pattern. Run the command.</p>\n\n<p>Thanks,</p>\n"
},
{
"answer_id": 8446590,
"author": "tommy_turrell",
"author_id": 1089829,
"author_profile": "https://Stackoverflow.com/users/1089829",
"pm_score": 6,
"selected": false,
"text": "<p>Yes you can using SVN 1.6. You will need to do a checkout first then mark the folder for exclusion then delete the unwanted folder.</p>\n\n<pre><code>svn checkout http://www.example.com/project\ncd project\nsvn update --set-depth=exclude docs\nrm -fr docs\n</code></pre>\n\n<p>From now on any updates to the working copy won't repopulate the docs folder.</p>\n\n<p>See <a href=\"http://blogs.collab.net/subversion/2009/03/sparse-directories-now-with-exclusion/\" rel=\"noreferrer\">http://blogs.collab.net/subversion/2009/03/sparse-directories-now-with-exclusion/</a> and <a href=\"http://subversion.apache.org/docs/release-notes/1.6.html#sparse-directory-exclusion\" rel=\"noreferrer\">http://subversion.apache.org/docs/release-notes/1.6.html#sparse-directory-exclusion</a> for more details.</p>\n\n<p>Tom</p>\n"
},
{
"answer_id": 12209107,
"author": "gammay",
"author_id": 957057,
"author_profile": "https://Stackoverflow.com/users/957057",
"pm_score": 3,
"selected": false,
"text": "<p>This is in TortoiseSVN client 1.7.1 (might be available in some older versions as well):</p>\n\n<ul>\n<li><p>SVN checkout --> Select URL of repository</p></li>\n<li><p>Click on \"Checkout Items\" (under Checkout Depth) and select only the\nfolders required!</p></li>\n</ul>\n"
},
{
"answer_id": 25256909,
"author": "rgov",
"author_id": 145504,
"author_profile": "https://Stackoverflow.com/users/145504",
"pm_score": 2,
"selected": false,
"text": "<p>I found this question looking for a way to check out the WebKit sources while excluding the regression tests. I ended up with the following:</p>\n\n<pre><code>svn checkout http://svn.webkit.org/repository/webkit/trunk WebKit \\\n --depth immediates\n\ncd WebKit\nfind . \\\n -maxdepth 1 -type d \\\n -not -name '.*' \\\n -not -name '*Tests' \\\n -not -name 'Examples' \\\n -not -name 'Websites' \\\n | (while read SUBDIR; do svn update --set-depth infinity \"$SUBDIR\"; done)\n</code></pre>\n\n<p>Note you can change the exclusions as you see fit, but .* is recommended to skip the working directory (which is already up to date) and all of the .svn directories.</p>\n"
},
{
"answer_id": 73405760,
"author": "Nathan Pacey",
"author_id": 15526191,
"author_profile": "https://Stackoverflow.com/users/15526191",
"pm_score": 0,
"selected": false,
"text": "<p>The best way I have seen is to check out a zero depth version and then go into the directories you need to change and update the depth.</p>\n<p>Checking out a zero depth folder</p>\n<pre><code>$ svn co svn://subversion/project/my_project_dir --depth immediates\n</code></pre>\n<p>Then going into the working folders and adding depth</p>\n<pre><code>$ cd my_project_dir\n$ cd working_dir && svn update --set-depth infinity\n</code></pre>\n<p>Update as many folders as you need to work on!</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20683/"
] |
Can I ignore a folder on svn checkout? I need to ignore DOCs folder on checkout at my build server.
**edit:** Ignore externals isn't an option. I have some externals that I need.
|
You can't directly ignore folders on a checkout, but you can use sparse checkouts in svn 1.5. For example:
```
$ svn co http://subversion/project/trunk my_checkout --depth immediates
```
This will check files and directories from your project trunk into 'my\_checkout', but not recurse into those directories. Eg:
```
$ cd my_checkout && ls
bar/ baz foo xyzzy/
```
Then to get the contents of 'bar' down:
```
$ cd bar && svn update --set-depth infinity
```
|
192,839 |
<p>Is it possible to get the machine name, or IP, or MAC address (basically client network information) from javascript running Internet Explorer?</p>
<p>I found the following code that seems to accomplish this:</p>
<pre><code>function Button1_onclick() {
var locator = new ActiveXObject("WbemScripting.SWbemLocator");
var service = locator.ConnectServer(".");
var properties = service.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration");
var e = new Enumerator (properties);
document.write("<table border=1>");
dispHeading();
for (;!e.atEnd();e.moveNext ())
{
var p = e.item ();
document.write("<tr>");
document.write("<td>" + p.Caption + "</td>");
document.write("<td>" + p.IPFilterSecurityEnabled + "</td>");
document.write("<td>" + p.IPPortSecurityEnabled + "</td>");
document.write("<td>" + p.IPXAddress + "</td>");
document.write("<td>" + p.IPXEnabled + "</td>");
document.write("<td>" + p.IPXNetworkNumber + "</td>");
document.write("<td>" + p.MACAddress + "</td>");
document.write("<td>" + p.WINSPrimaryServer + "</td>");
document.write("<td>" + p.WINSSecondaryServer + "</td>");
document.write("</tr>");
}
document.write("</table>");
</code></pre>
<p>}</p>
<p>So it's using an ActiveX Object that seems to be installed with the OS to accomplish this. Is something similar like this possible to do from a terminal service session? To get the terminal service client network information? (Not the terminal server network information which is what the above code would do when run from a terminal service session).</p>
<p>I'm thinking maybe there is another Active X object available to accomplish this?</p>
|
[
{
"answer_id": 193088,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 0,
"selected": false,
"text": "<p>If a user is logged onto a Terminal Server and visits a page in Internet Explorer in that TS session, then Internet Explorer (and any ActiveX controls it instantiates) are running on the Terminal Server hardware, not the client hardware.</p>\n\n<p>From this perspective, the only code running on the client hardware is the Terminal Services client software. To retrieve network information about the Terminal Services client hardware/network/etc, you would have to run code on the client hardware.</p>\n"
},
{
"answer_id": 195351,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": true,
"text": "<p>Basically, there are two possibilities to get hold of the client name/address that come to mind:</p>\n\n<ul>\n<li>Use MFCOM, namely the <code>MetaFrameSession</code> object.</li>\n<li>Use WMI, the <code>MetaFrame_ICA_Client</code> class in <code>root\\Citrix</code> looks promising.</li>\n</ul>\n\n<p>Mayor drawback of both solutions is, that they require more user permissions than you might be willing to give. From what I read, at least \"Account View\" permissions are required within Citrix, but I have no way to test it right now. I could not get either to work as a normal user.</p>\n\n<p>To give you an idea, accessing the info with MFCOM would look something like this:</p>\n\n<pre><code>var MetaFrameSessionObject = 6;\n\nvar oShell = new ActiveXObject(\"WScript.Shell\");\nvar oSession = new ActiveXObject(\"MetaFrameCOM.MetaFrameSession\");\n\noSession.Initialize(\n MetaFrameSessionObject, \n oShell.ExpandEnvironmentStrings(\"%COMPUTERNAME%\"), \n oShell.ExpandEnvironmentStrings(\"%SESSIONNAME%\"), \n -1\n);\n\nalert(oSession.ClientAddress);\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341/"
] |
Is it possible to get the machine name, or IP, or MAC address (basically client network information) from javascript running Internet Explorer?
I found the following code that seems to accomplish this:
```
function Button1_onclick() {
var locator = new ActiveXObject("WbemScripting.SWbemLocator");
var service = locator.ConnectServer(".");
var properties = service.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration");
var e = new Enumerator (properties);
document.write("<table border=1>");
dispHeading();
for (;!e.atEnd();e.moveNext ())
{
var p = e.item ();
document.write("<tr>");
document.write("<td>" + p.Caption + "</td>");
document.write("<td>" + p.IPFilterSecurityEnabled + "</td>");
document.write("<td>" + p.IPPortSecurityEnabled + "</td>");
document.write("<td>" + p.IPXAddress + "</td>");
document.write("<td>" + p.IPXEnabled + "</td>");
document.write("<td>" + p.IPXNetworkNumber + "</td>");
document.write("<td>" + p.MACAddress + "</td>");
document.write("<td>" + p.WINSPrimaryServer + "</td>");
document.write("<td>" + p.WINSSecondaryServer + "</td>");
document.write("</tr>");
}
document.write("</table>");
```
}
So it's using an ActiveX Object that seems to be installed with the OS to accomplish this. Is something similar like this possible to do from a terminal service session? To get the terminal service client network information? (Not the terminal server network information which is what the above code would do when run from a terminal service session).
I'm thinking maybe there is another Active X object available to accomplish this?
|
Basically, there are two possibilities to get hold of the client name/address that come to mind:
* Use MFCOM, namely the `MetaFrameSession` object.
* Use WMI, the `MetaFrame_ICA_Client` class in `root\Citrix` looks promising.
Mayor drawback of both solutions is, that they require more user permissions than you might be willing to give. From what I read, at least "Account View" permissions are required within Citrix, but I have no way to test it right now. I could not get either to work as a normal user.
To give you an idea, accessing the info with MFCOM would look something like this:
```
var MetaFrameSessionObject = 6;
var oShell = new ActiveXObject("WScript.Shell");
var oSession = new ActiveXObject("MetaFrameCOM.MetaFrameSession");
oSession.Initialize(
MetaFrameSessionObject,
oShell.ExpandEnvironmentStrings("%COMPUTERNAME%"),
oShell.ExpandEnvironmentStrings("%SESSIONNAME%"),
-1
);
alert(oSession.ClientAddress);
```
|
192,862 |
<p>I'm developing a webapp where the user is given the chance to upload his resume in pdf format. I'm using NHibernate as a data mapper and MS SQL SERVER 2005.</p>
<p>I want to be able to save the .pdf file to a given table... any ideas?</p>
<p>Thank you very much!</p>
|
[
{
"answer_id": 192911,
"author": "Joshua",
"author_id": 14768,
"author_profile": "https://Stackoverflow.com/users/14768",
"pm_score": 0,
"selected": false,
"text": "<p>INSERT INTO Table (DocumentId, PDF)\nVALUES (newid(), 0x12345667)</p>\n\n<p>where the hex constant is the hex-encoded bytestream of the PDF.</p>\n\n<p>I'm sure someone can find a better way, but this is obvious to me.</p>\n"
},
{
"answer_id": 192922,
"author": "willasaywhat",
"author_id": 12234,
"author_profile": "https://Stackoverflow.com/users/12234",
"pm_score": 0,
"selected": false,
"text": "<p>Any reason you need to put the PDF into the table? You could save the file to the filesystem and reference it with an ID. That would save you some SQL Server space. I don't believe you can index binary data anyways.</p>\n"
},
{
"answer_id": 200565,
"author": "huo73",
"author_id": 15657,
"author_profile": "https://Stackoverflow.com/users/15657",
"pm_score": 4,
"selected": true,
"text": "<p>We are doing exactly that with the \"original\" Java Hibernate3. You just map a byte array property of your persistable class to an column of Type \"image\".</p>\n\n<pre><code>package com.hibernate.pdf.sample;\n\npublic class TPDFDocument implements java.io.Serializable {\n\n\n private Integer pdfDocumentId;\n private byte[] document;\n\n\n public Integer getPdfDocumentId() {\n return this.pdfDocumentId;\n }\n\n public void setPdfDocumentId(Integer pdfDocumentId) {\n this.pdfDocumentId = pdfDocumentId;\n }\n\n public byte[] getDocument() {\n return this.document;\n }\n\n public void setDocument(byte[] document) {\n this.document = document;\n }\n\n}\n</code></pre>\n\n<p>Hibernate Mapping:</p>\n\n<pre><code><hibernate-mapping>\n <class name=\"com.hibernate.pdf.sample.TPDFDocument\" table=\"T_PDFDocument\">\n <id name=\"pdfDocumentId\" type=\"integer\">\n <column name=\"pdfDocumentId\" />\n <generator class=\"identity\" />\n </id>\n <property name=\"document\" type=\"binary\">\n <column name=\"document\" not-null=\"true\" />\n </property>\n </class>\n</hibernate-mapping>\n</code></pre>\n\n<p>Table creation:</p>\n\n<pre><code>CREATE TABLE [dbo].[T_PDFDocument](\n [pdfDocumentId] [int] IDENTITY(1,1) NOT NULL,\n [document] [image] NOT NULL,\nCONSTRAINT [PK_PDFDocument] PRIMARY KEY CLUSTERED \n(\n [pdfDocumentId] ASC\n)\n</code></pre>\n\n<p>All you have to do is to read the documents raw bytes into the array and persist it. In our situation the documents will get hardly larger than 1MB , so putting the whole thing into the byte-array won't cause performance issues. Maybe this solution isn't feasable for very large documents.</p>\n\n<p>I guess with NHibernate implementation and C# the solution will look very similar.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7595/"
] |
I'm developing a webapp where the user is given the chance to upload his resume in pdf format. I'm using NHibernate as a data mapper and MS SQL SERVER 2005.
I want to be able to save the .pdf file to a given table... any ideas?
Thank you very much!
|
We are doing exactly that with the "original" Java Hibernate3. You just map a byte array property of your persistable class to an column of Type "image".
```
package com.hibernate.pdf.sample;
public class TPDFDocument implements java.io.Serializable {
private Integer pdfDocumentId;
private byte[] document;
public Integer getPdfDocumentId() {
return this.pdfDocumentId;
}
public void setPdfDocumentId(Integer pdfDocumentId) {
this.pdfDocumentId = pdfDocumentId;
}
public byte[] getDocument() {
return this.document;
}
public void setDocument(byte[] document) {
this.document = document;
}
}
```
Hibernate Mapping:
```
<hibernate-mapping>
<class name="com.hibernate.pdf.sample.TPDFDocument" table="T_PDFDocument">
<id name="pdfDocumentId" type="integer">
<column name="pdfDocumentId" />
<generator class="identity" />
</id>
<property name="document" type="binary">
<column name="document" not-null="true" />
</property>
</class>
</hibernate-mapping>
```
Table creation:
```
CREATE TABLE [dbo].[T_PDFDocument](
[pdfDocumentId] [int] IDENTITY(1,1) NOT NULL,
[document] [image] NOT NULL,
CONSTRAINT [PK_PDFDocument] PRIMARY KEY CLUSTERED
(
[pdfDocumentId] ASC
)
```
All you have to do is to read the documents raw bytes into the array and persist it. In our situation the documents will get hardly larger than 1MB , so putting the whole thing into the byte-array won't cause performance issues. Maybe this solution isn't feasable for very large documents.
I guess with NHibernate implementation and C# the solution will look very similar.
|
192,888 |
<p>I have some nested tables that I want to hide/show upon a click on one of the top-level rows.</p>
<p>The markup is, in a nutshell, this:</p>
<pre>
<table>
<tr>
<td>stuff</td>
.... more tds here
</tr>
<tr>
<td colspan=some_number>
<table>
</table>
</td>
</tr>
</table>
</pre>
<p>Now, I'm using some jQuery to target a link in the first table row. When that link is clicked, it pulls some data down, formats it as a bunch of table rows, and appends it to the table inside. Then it applies the .show() to the table. (this is all done via id/class targeting. I left them out of the sample for brevity).</p>
<p>This works beautifully in firefox. Click the link, data gets loaded, main table "expands" with the secondary table all nice and filled in.</p>
<p>Problem is -- Internet Explorer is giving me the finger. As best as I can tell, the data is getting appended to the inner table. The problem is that the .show() does not appear to be doing anything useful. To make matters more annoying, I've got a page that has this functionality that is working splendidly in both -- the only difference being two things:</p>
<p>In the one that is working, the inner table is wrapped in a div. I've even tried wrapping my table in this example in a div without success.
In the one that is not working, I have an extra jQuery plugin loaded -- but I've removed this plugin and tried the page without it and it still fails to show the inner table.</p>
<p>I've tried attaching the .show to the parent tr, parent td, and the table itself with no success. I must be missing something incredibly simple, because as near as I can tell this should work.</p>
<p>Has anyone come across something like this before?</p>
|
[
{
"answer_id": 192901,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 1,
"selected": false,
"text": "<p>There are a bunch of bugs in IE related to modifying the contents of tables from Javascript. In a lot of cases, IE (including IE7) will even crash.</p>\n\n<p><strike>I ran into this recently and I'm blanking on the work-around I came up with. Let me go back through my logs and see what I can find.</strike></p>\n\n<hr>\n\n<p>OK, I found the case I ran into.</p>\n\n<p>I was doing something similar. I had a table and I was trying to add a <code><td</code>> tag with a link in it via Javascript and that was causing a memory exception in IE7.</p>\n\n<p>In the end, the only way I could figure out to get around it was to rebuild the entire <code><table</code>> in Javascript rather than trying to insert things into the existing one.</p>\n\n<p>To clarify, by rebuild I mean create a string containg the table HTML and add it to the innerHTML of a div. I'm not using DOM functions to create the table.</p>\n"
},
{
"answer_id": 192904,
"author": "Zack The Human",
"author_id": 18265,
"author_profile": "https://Stackoverflow.com/users/18265",
"pm_score": 4,
"selected": true,
"text": "<p>Keep in mind that the innerHTML of a <table> element is <em>read-only</em> in IE(6 for sure, not sure about 7). That being the case, are you explicitly adding a <tbody> element? If not, try adding one and adding the rows to the body element rather than the table element.</p>\n\n<pre><code><table>\n <tbody>\n <!-- Add stuff here... -->\n </tbody>\n</table>\n</code></pre>\n\n<p>Microsoft info (sort-of) about this: <a href=\"http://support.microsoft.com/kb/239832\" rel=\"nofollow noreferrer\">PRB: Error Setting table.innerHTML in Internet Explorer</a> Note: it says this is \"by design\".</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22390/"
] |
I have some nested tables that I want to hide/show upon a click on one of the top-level rows.
The markup is, in a nutshell, this:
```
<table>
<tr>
<td>stuff</td>
.... more tds here
</tr>
<tr>
<td colspan=some_number>
<table>
</table>
</td>
</tr>
</table>
```
Now, I'm using some jQuery to target a link in the first table row. When that link is clicked, it pulls some data down, formats it as a bunch of table rows, and appends it to the table inside. Then it applies the .show() to the table. (this is all done via id/class targeting. I left them out of the sample for brevity).
This works beautifully in firefox. Click the link, data gets loaded, main table "expands" with the secondary table all nice and filled in.
Problem is -- Internet Explorer is giving me the finger. As best as I can tell, the data is getting appended to the inner table. The problem is that the .show() does not appear to be doing anything useful. To make matters more annoying, I've got a page that has this functionality that is working splendidly in both -- the only difference being two things:
In the one that is working, the inner table is wrapped in a div. I've even tried wrapping my table in this example in a div without success.
In the one that is not working, I have an extra jQuery plugin loaded -- but I've removed this plugin and tried the page without it and it still fails to show the inner table.
I've tried attaching the .show to the parent tr, parent td, and the table itself with no success. I must be missing something incredibly simple, because as near as I can tell this should work.
Has anyone come across something like this before?
|
Keep in mind that the innerHTML of a <table> element is *read-only* in IE(6 for sure, not sure about 7). That being the case, are you explicitly adding a <tbody> element? If not, try adding one and adding the rows to the body element rather than the table element.
```
<table>
<tbody>
<!-- Add stuff here... -->
</tbody>
</table>
```
Microsoft info (sort-of) about this: [PRB: Error Setting table.innerHTML in Internet Explorer](http://support.microsoft.com/kb/239832) Note: it says this is "by design".
|
192,892 |
<p>Has anyone implemented a very large EAV or open schema style database in SQL Server? I'm wondering if there are performance issues with this and how you were able to overcome those obstacles.</p>
|
[
{
"answer_id": 194490,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not an expert on EAV, but several more experienced developers than I have commented that Magento's open-source e-commerce framework is slow primarily because of the EAV architecture through MySQL. The most obvious disadvantage can't easily be overcome. That being the difficulty with which it is to troubleshoot where and how information is represented for entities and attribute values as the size of the application increases. The second argument against EAV I have heard is that it requires table joins that get into low double digits, but it was commented that using InnoDB over MyISAM improved the performance some (or it could be vice-versa, but I can't remember totally).</p>\n"
},
{
"answer_id": 231681,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": false,
"text": "<p>Regardless of MS SQL Server versus any other brand of database, the worst performance issue with EAV is that people try to do monster queries to reconstruct an entity on a single row. <em>This requires a separate join per attribute</em>.</p>\n\n<pre><code>SELECT e.id, a1.attr_value as \"cost\", a2.attr_value as \"color\",\n a3.attr_value as \"size\", . . .\nFROM entity e\n LEFT OUTER JOIN attrib a1 ON (e.entity_id = a1.entity_id AND a1.attr_name = 'cost')\n LEFT OUTER JOIN attrib a2 ON (e.entity_id = a2.entity_id AND a2.attr_name = 'color')\n LEFT OUTER JOIN attrib a2 ON (e.entity_id = a3.entity_id AND a3.attr_name = 'size')\n . . . additional joins for each attribute . . .\n</code></pre>\n\n<p>No matter what database brand you use, more joins in a query means geometrically increasing performance cost. Inevitably, you need enough attributes to exceed the architectural capacity of any SQL engine.</p>\n\n<p>The solution is to fetch the attributes in rows instead of columns, and write a class in application code to loop over these rows, assigning the values into object properties one by one. </p>\n\n<pre><code>SELECT e.id, a.attr_name, a.attr_value\nFROM entity e JOIN attrib a USING (entity_id)\nORDER BY e.id;\n</code></pre>\n\n<p>This SQL query is so much simpler and more efficient, that it makes up for the extra application code.</p>\n\n<p>What I would look for in an EAV framework is some boilerplate code that retrieves a multi-row result set like this, and maps the attributes into object properties, and then returns the collection of populated objects.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] |
Has anyone implemented a very large EAV or open schema style database in SQL Server? I'm wondering if there are performance issues with this and how you were able to overcome those obstacles.
|
Regardless of MS SQL Server versus any other brand of database, the worst performance issue with EAV is that people try to do monster queries to reconstruct an entity on a single row. *This requires a separate join per attribute*.
```
SELECT e.id, a1.attr_value as "cost", a2.attr_value as "color",
a3.attr_value as "size", . . .
FROM entity e
LEFT OUTER JOIN attrib a1 ON (e.entity_id = a1.entity_id AND a1.attr_name = 'cost')
LEFT OUTER JOIN attrib a2 ON (e.entity_id = a2.entity_id AND a2.attr_name = 'color')
LEFT OUTER JOIN attrib a2 ON (e.entity_id = a3.entity_id AND a3.attr_name = 'size')
. . . additional joins for each attribute . . .
```
No matter what database brand you use, more joins in a query means geometrically increasing performance cost. Inevitably, you need enough attributes to exceed the architectural capacity of any SQL engine.
The solution is to fetch the attributes in rows instead of columns, and write a class in application code to loop over these rows, assigning the values into object properties one by one.
```
SELECT e.id, a.attr_name, a.attr_value
FROM entity e JOIN attrib a USING (entity_id)
ORDER BY e.id;
```
This SQL query is so much simpler and more efficient, that it makes up for the extra application code.
What I would look for in an EAV framework is some boilerplate code that retrieves a multi-row result set like this, and maps the attributes into object properties, and then returns the collection of populated objects.
|
192,900 |
<p>Is it possible to set the cursor to 'wait' on the entire html page in a simple way? The idea is to show the user that something is going on while an ajax call is being completed. The code below shows a simplified version of what I tried and also demonstrate the problems I run into:</p>
<ol>
<li>if an element (#id1) has a cursor style set it will ignore the one set on body (obviously) </li>
<li>some elements have a default cursor style (a) and will not show the wait cursor on hover </li>
<li>the body element has a certain height depending on the content and if the page is short, the cursor will not show below the footer</li>
</ol>
<p>The test:</p>
<pre><code><html>
<head>
<style type="text/css">
#id1 {
background-color: #06f;
cursor: pointer;
}
#id2 {
background-color: #f60;
}
</style>
</head>
<body>
<div id="id1">cursor: pointer</div>
<div id="id2">no cursor</div>
<a href="#" onclick="document.body.style.cursor = 'wait'; return false">Do something</a>
</body>
</html>
</code></pre>
<p>Later edit...<br>
It worked in firefox and IE with: </p>
<pre><code>div#mask { display: none; cursor: wait; z-index: 9999;
position: absolute; top: 0; left: 0; height: 100%;
width: 100%; background-color: #fff; opacity: 0; filter: alpha(opacity = 0);}
<a href="#" onclick="document.getElementById('mask').style.display = 'block'; return false">
Do something</a>
</code></pre>
<p>The problem with (or feature of) this solution is that it will prevent clicks because of the overlapping div (thanks Kibbee)</p>
<p>Later later edit...<br>
A simpler solution from Dorward:</p>
<pre><code>.wait, .wait * { cursor: wait !important; }
</code></pre>
<p>and then </p>
<pre><code><a href="#" onclick="document.body.className = 'wait'; return false">Do something</a>
</code></pre>
<p>This solution only shows the wait cursor but allows clicks.</p>
|
[
{
"answer_id": 192917,
"author": "unexist",
"author_id": 18179,
"author_profile": "https://Stackoverflow.com/users/18179",
"pm_score": 2,
"selected": false,
"text": "<p>Why don't you just use one of those fancy loading graphics (eg: <a href=\"http://ajaxload.info/\" rel=\"nofollow noreferrer\">http://ajaxload.info/</a>)? The waiting cursor is for the browser itself - so whenever it appears it has something to do with the browser and not with the page.</p>\n"
},
{
"answer_id": 192967,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 6,
"selected": true,
"text": "<p>I understand you may not have control over this, but you might instead go for a \"masking\" div that covers the entire body with a z-index higher than 1. The center part of the div could contain a loading message if you like.</p>\n\n<p>Then, you can set the cursor to wait on the div and don't have to worry about links as they are \"under\" your masking div. Here's some example CSS for the \"masking div\":</p>\n\n<pre>\nbody { height: 100%; }\ndiv#mask { cursor: wait; z-index: 999; height: 100%; width: 100%; }\n</pre>\n"
},
{
"answer_id": 193006,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 4,
"selected": false,
"text": "<p>This seems to work in firefox</p>\n\n<pre><code><style>\n*{ cursor: inherit;}\nbody{ cursor: wait;}\n</style>\n</code></pre>\n\n<p>The * part ensures that the cursor doesn't change when you hover over a link. Although links will still be clickable.</p>\n"
},
{
"answer_id": 202671,
"author": "GameFreak",
"author_id": 26659,
"author_profile": "https://Stackoverflow.com/users/26659",
"pm_score": 1,
"selected": false,
"text": "<p>Try the css:</p>\n\n<pre><code>html.waiting {\ncursor: wait;\n}\n</code></pre>\n\n<p>It seems that if the property <code>body</code> is used as apposed to <code>html</code> it doesn't show the wait cursor over the whole page. Furthermore if you use a css class you can easily control when it actually shows it.</p>\n"
},
{
"answer_id": 10801889,
"author": "Dani",
"author_id": 1424042,
"author_profile": "https://Stackoverflow.com/users/1424042",
"pm_score": 7,
"selected": false,
"text": "<p>If you use this slightly modified version of the CSS you posted from Dorward,</p>\n\n<pre><code>html.wait, html.wait * { cursor: wait !important; }\n</code></pre>\n\n<p>you can then add some really simple <a href=\"http://api.jquery.com/\" rel=\"noreferrer\">jQuery</a> to work for all ajax calls:</p>\n\n<pre><code>$(document).ready(function () {\n $(document).ajaxStart(function () { $(\"html\").addClass(\"wait\"); });\n $(document).ajaxStop(function () { $(\"html\").removeClass(\"wait\"); });\n});\n</code></pre>\n\n<p>or, for older jQuery versions (before 1.9):</p>\n\n<pre><code>$(document).ready(function () {\n $(\"html\").ajaxStart(function () { $(this).addClass(\"wait\"); });\n $(\"html\").ajaxStop(function () { $(this).removeClass(\"wait\"); });\n});\n</code></pre>\n"
},
{
"answer_id": 11644401,
"author": "jere_hr",
"author_id": 998698,
"author_profile": "https://Stackoverflow.com/users/998698",
"pm_score": 2,
"selected": false,
"text": "<p>Easiest way I know is using JQuery like this:</p>\n\n<pre><code>$('*').css('cursor','wait');\n</code></pre>\n"
},
{
"answer_id": 11725235,
"author": "pasx",
"author_id": 683319,
"author_profile": "https://Stackoverflow.com/users/683319",
"pm_score": 3,
"selected": false,
"text": "<p>I have been struggling with this problem for hours today.\nBasically everything was working just fine in FireFox but (of course) not in IE.\nIn IE the wait cursor was showing AFTER the time consuming function was executed.</p>\n\n<p>I finally found the trick on this site:\n<a href=\"http://www.codingforums.com/archive/index.php/t-37185.html\" rel=\"noreferrer\">http://www.codingforums.com/archive/index.php/t-37185.html</a></p>\n\n<p>Code:</p>\n\n<pre><code>//...\ndocument.body.style.cursor = 'wait';\nsetTimeout(this.SomeLongFunction, 1);\n\n//setTimeout syntax when calling a function with parameters\n//setTimeout(function() {MyClass.SomeLongFunction(someParam);}, 1);\n\n//no () after function name this is a function ref not a function call\nsetTimeout(this.SetDefaultCursor, 1);\n...\n\nfunction SetDefaultCursor() {document.body.style.cursor = 'default';}\n\nfunction SomeLongFunction(someParam) {...}\n</code></pre>\n\n<p>My code runs in a JavaScript class hence the this and MyClass (MyClass is a singleton).</p>\n\n<p>I had the same problems when trying to display a div as described on this page. In IE it was showing after the function had been executed. So I guess this trick would solve that problem too.</p>\n\n<p>Thanks a zillion time to glenngv the author of the post. You really made my day!!!</p>\n"
},
{
"answer_id": 12966122,
"author": "redbmk",
"author_id": 817950,
"author_profile": "https://Stackoverflow.com/users/817950",
"pm_score": 2,
"selected": false,
"text": "<p>css: <code>.waiting * { cursor: 'wait' }</code></p>\n\n<p>jQuery: <code>$('body').toggleClass('waiting');</code></p>\n"
},
{
"answer_id": 18725044,
"author": "kulNinja",
"author_id": 430017,
"author_profile": "https://Stackoverflow.com/users/430017",
"pm_score": 0,
"selected": false,
"text": "<p>BlockUI is the answer for everything. Give it a try.</p>\n\n<p><a href=\"http://www.malsup.com/jquery/block/\" rel=\"nofollow\">http://www.malsup.com/jquery/block/</a></p>\n"
},
{
"answer_id": 31445877,
"author": "kofifus",
"author_id": 460084,
"author_profile": "https://Stackoverflow.com/users/460084",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a more elaborate solution that does not require external CSS:</p>\n\n<pre><code>function changeCursor(elem, cursor, decendents) {\n if (!elem) elem=$('body');\n\n // remove all classes starting with changeCursor-\n elem.removeClass (function (index, css) {\n return (css.match (/(^|\\s)changeCursor-\\S+/g) || []).join(' ');\n });\n\n if (!cursor) return;\n\n if (typeof decendents==='undefined' || decendents===null) decendents=true;\n\n let cname;\n\n if (decendents) {\n cname='changeCursor-Dec-'+cursor;\n if ($('style:contains(\"'+cname+'\")').length < 1) $('<style>').text('.'+cname+' , .'+cname+' * { cursor: '+cursor+' !important; }').appendTo('head');\n } else {\n cname='changeCursor-'+cursor;\n if ($('style:contains(\"'+cname+'\")').length < 1) $('<style>').text('.'+cname+' { cursor: '+cursor+' !important; }').appendTo('head');\n }\n\n elem.addClass(cname);\n}\n</code></pre>\n\n<p>with this you can do:</p>\n\n<pre><code>changeCursor(, 'wait'); // wait cursor on all decendents of body\nchangeCursor($('#id'), 'wait', false); // wait cursor on elem with id only\nchangeCursor(); // remove changed cursor from body\n</code></pre>\n"
},
{
"answer_id": 46794402,
"author": "ungalcrys",
"author_id": 443427,
"author_profile": "https://Stackoverflow.com/users/443427",
"pm_score": 1,
"selected": false,
"text": "<p>I used a adaptation of <a href=\"https://stackoverflow.com/a/192967/443427\">Eric Wendelin</a>'s solution. It will show a transparent, animated overlay wait-div over the whole body, the click will be blocked by the wait-div while visible:</p>\n\n<p>css:</p>\n\n<pre><code>div#waitMask {\n z-index: 999;\n position: absolute;\n top: 0;\n right: 0;\n height: 100%;\n width: 100%;\n cursor: wait;\n background-color: #000;\n opacity: 0;\n transition-duration: 0.5s;\n -webkit-transition-duration: 0.5s;\n}\n</code></pre>\n\n<p>js:</p>\n\n<pre><code>// to show it\n$(\"#waitMask\").show();\n$(\"#waitMask\").css(\"opacity\"); // must read it first\n$(\"#waitMask\").css(\"opacity\", \"0.8\");\n\n...\n\n// to hide it\n$(\"#waitMask\").css(\"opacity\", \"0\");\nsetTimeout(function() {\n $(\"#waitMask\").hide();\n}, 500) // wait for animation to end\n</code></pre>\n\n<p>html:</p>\n\n<pre><code><body>\n <div id=\"waitMask\" style=\"display:none;\">&nbsp;</div>\n ... rest of html ...\n</code></pre>\n"
},
{
"answer_id": 48931250,
"author": "indiaaditya",
"author_id": 2837780,
"author_profile": "https://Stackoverflow.com/users/2837780",
"pm_score": 1,
"selected": false,
"text": "<p>My Two pence: </p>\n\n<p>Step 1:\nDeclare an array. This will be used to store the original cursors that were assigned:</p>\n\n<pre><code>var vArrOriginalCursors = new Array(2);\n</code></pre>\n\n<p>Step 2:\nImplement the function cursorModifyEntirePage</p>\n\n<pre><code> function CursorModifyEntirePage(CursorType){\n var elements = document.body.getElementsByTagName('*');\n alert(\"These are the elements found:\" + elements.length);\n let lclCntr = 0;\n vArrOriginalCursors.length = elements.length; \n for(lclCntr = 0; lclCntr < elements.length; lclCntr++){\n vArrOriginalCursors[lclCntr] = elements[lclCntr].style.cursor;\n elements[lclCntr].style.cursor = CursorType;\n }\n}\n</code></pre>\n\n<p>What it does:\nGets all the elements on the page. Stores the original cursors assigned to them in the array declared in step 1. Modifies the cursors to the desired cursor as passed by parameter CursorType</p>\n\n<p>Step 3:\nRestore the cursors on the page</p>\n\n<pre><code> function CursorRestoreEntirePage(){\n let lclCntr = 0;\n var elements = document.body.getElementsByTagName('*');\n for(lclCntr = 0; lclCntr < elements.length; lclCntr++){\n elements[lclCntr].style.cursor = vArrOriginalCursors[lclCntr];\n }\n}\n</code></pre>\n\n<p>I have run this in an application and it works fine.\nOnly caveat is that I have not tested it when you are dynamically adding the elements.</p>\n"
},
{
"answer_id": 60616224,
"author": "Peter J. de Bruin",
"author_id": 2061591,
"author_profile": "https://Stackoverflow.com/users/2061591",
"pm_score": 2,
"selected": false,
"text": "<p>To set the cursor from JavaScript for the whole window, use:</p>\n\n<pre><code>document.documentElement.style.cursor = 'wait';\n</code></pre>\n\n<p>From CSS:</p>\n\n<pre><code>html { cursor: wait; }\n</code></pre>\n\n<p>Add further logic as needed.</p>\n"
},
{
"answer_id": 61948501,
"author": "javocity",
"author_id": 3700767,
"author_profile": "https://Stackoverflow.com/users/3700767",
"pm_score": 0,
"selected": false,
"text": "<p>This pure JavaScript seems to work pretty well ... tested on FireFox, Chrome, and Edge browsers.</p>\n\n<p>I'm not sure about the performance of this if you had an overabundance of elements on your page and a slow computer ... try it and see.</p>\n\n<p>Set cursor for all elements to wait:</p>\n\n<pre><code>Object.values(document.querySelectorAll('*')).forEach(element => element.style.cursor = \"wait\");\n</code></pre>\n\n<p>Set cursor for all elements back to default:</p>\n\n<pre><code>Object.values(document.querySelectorAll('*')).forEach(element => element.style.cursor = \"default\");\n</code></pre>\n\n<p>An alternative (and perhaps a bit more readable) version would be to create a setCursor function as follows:</p>\n\n<pre><code>function setCursor(cursor)\n{\n var x = document.querySelectorAll(\"*\");\n\n for (var i = 0; i < x.length; i++)\n {\n x[i].style.cursor = cursor;\n }\n}\n</code></pre>\n\n<p>and then call</p>\n\n<pre><code>setCursor(\"wait\");\n</code></pre>\n\n<p>and</p>\n\n<pre><code>setCursor(\"default\");\n</code></pre>\n\n<p>to set the wait cursor and default cursor respectively.</p>\n"
},
{
"answer_id": 72450083,
"author": "Francisco Jesus",
"author_id": 13899551,
"author_profile": "https://Stackoverflow.com/users/13899551",
"pm_score": -1,
"selected": false,
"text": "<p>Late to the party but simply give the Html tag an id by targeting</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>document.documentElement</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>and in the CSS place at the top</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html#wait * {\n cursor: wait !important;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>and simply remove it when you want to stop this cursor.</p>\n"
},
{
"answer_id": 74288000,
"author": "djvg",
"author_id": 4720018,
"author_profile": "https://Stackoverflow.com/users/4720018",
"pm_score": 0,
"selected": false,
"text": "<p>Lots of good answers already, but none of them mentions the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog\" rel=\"nofollow noreferrer\"><code><dialog></code> element</a>.</p>\n<p>Using this element we can create a solution similar to the <a href=\"https://stackoverflow.com/a/192967\">masking <code><div></code></a>.</p>\n<p>Here we use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/showModal\" rel=\"nofollow noreferrer\">showModal()</a> to "hide" elements, and we use <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/::backdrop\" rel=\"nofollow noreferrer\"><code>::backdrop</code></a> to set the cursor style to <code>wait</code> on the entire page:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function showWaitDialog() {\n document.getElementById('id_dialog').showModal();\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#id_dialog, #id_dialog::backdrop {\n cursor: wait;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><button onclick=\"showWaitDialog()\">click me</button>\n<dialog id=\"id_dialog\">busy...</dialog></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The dialog is hidden by default, and can be shown using either the <code>show()</code> method, or the <code>showModal()</code> method, which prevents clicking outside the dialog.</p>\n<p>The dialog can be forced to close using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/close\" rel=\"nofollow noreferrer\">close()</a> method, if necessary.\nHowever, if your button links to another page, for example, then the dialog will disappear automatically as soon as the new page is loaded.</p>\n<p>Note that the dialog can also be closed at any time by hitting the <kbd>Esc</kbd> key.</p>\n<p>CSS can be used to style the dialog however you like.</p>\n<p>The example uses the html <code>onclick</code> attribute, just for simplicity. Obviously, <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\">addEventListener()</a> could also be used.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20417/"
] |
Is it possible to set the cursor to 'wait' on the entire html page in a simple way? The idea is to show the user that something is going on while an ajax call is being completed. The code below shows a simplified version of what I tried and also demonstrate the problems I run into:
1. if an element (#id1) has a cursor style set it will ignore the one set on body (obviously)
2. some elements have a default cursor style (a) and will not show the wait cursor on hover
3. the body element has a certain height depending on the content and if the page is short, the cursor will not show below the footer
The test:
```
<html>
<head>
<style type="text/css">
#id1 {
background-color: #06f;
cursor: pointer;
}
#id2 {
background-color: #f60;
}
</style>
</head>
<body>
<div id="id1">cursor: pointer</div>
<div id="id2">no cursor</div>
<a href="#" onclick="document.body.style.cursor = 'wait'; return false">Do something</a>
</body>
</html>
```
Later edit...
It worked in firefox and IE with:
```
div#mask { display: none; cursor: wait; z-index: 9999;
position: absolute; top: 0; left: 0; height: 100%;
width: 100%; background-color: #fff; opacity: 0; filter: alpha(opacity = 0);}
<a href="#" onclick="document.getElementById('mask').style.display = 'block'; return false">
Do something</a>
```
The problem with (or feature of) this solution is that it will prevent clicks because of the overlapping div (thanks Kibbee)
Later later edit...
A simpler solution from Dorward:
```
.wait, .wait * { cursor: wait !important; }
```
and then
```
<a href="#" onclick="document.body.className = 'wait'; return false">Do something</a>
```
This solution only shows the wait cursor but allows clicks.
|
I understand you may not have control over this, but you might instead go for a "masking" div that covers the entire body with a z-index higher than 1. The center part of the div could contain a loading message if you like.
Then, you can set the cursor to wait on the div and don't have to worry about links as they are "under" your masking div. Here's some example CSS for the "masking div":
```
body { height: 100%; }
div#mask { cursor: wait; z-index: 999; height: 100%; width: 100%; }
```
|
192,907 |
<p>Python has several ways to parse XML...</p>
<p>I understand the very basics of parsing with <strong>SAX</strong>. It functions as a stream parser, with an event-driven API.</p>
<p>I understand the <strong>DOM</strong> parser also. It reads the XML into memory and converts it to objects that can be accessed with Python.</p>
<p>Generally speaking, it was easy to choose between the two depending on what you needed to do, memory constraints, performance, etc.</p>
<p>(Hopefully I'm correct so far.)</p>
<p>Since Python 2.5, we also have <strong>ElementTree</strong>. How does this compare to DOM and SAX? Which is it more similar to? Why is it better than the previous parsers?</p>
|
[
{
"answer_id": 192913,
"author": "sanxiyn",
"author_id": 18382,
"author_profile": "https://Stackoverflow.com/users/18382",
"pm_score": 3,
"selected": false,
"text": "<p>ElementTree's parse() is like DOM, whereas iterparse() is like SAX. In my opinion, ElementTree is better than DOM and SAX in that it provides API easier to work with.</p>\n"
},
{
"answer_id": 194197,
"author": "iny",
"author_id": 27067,
"author_profile": "https://Stackoverflow.com/users/27067",
"pm_score": 3,
"selected": false,
"text": "<p>ElementTree has more pythonic API. It also is in the standard library now so using it reduces dependencies.</p>\n\n<p>I actually prefer <a href=\"https://lxml.de/\" rel=\"nofollow noreferrer\">lxml</a> as it has API like ElementTree, but has also nice additional features and performs well.</p>\n"
},
{
"answer_id": 194248,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 7,
"selected": true,
"text": "<p>ElementTree is much easier to use, because it represents an XML tree (basically) as a structure of lists, and attributes are represented as dictionaries.</p>\n\n<p>ElementTree needs much less memory for XML trees than DOM (and thus is faster), and the parsing overhead via <code>iterparse</code> is comparable to SAX. Additionally, <code>iterparse</code> returns partial structures, and you can keep memory usage constant during parsing by discarding the structures as soon as you process them.</p>\n\n<p>ElementTree, as in Python 2.5, has only a small feature set compared to full-blown XML libraries, but it's enough for many applications. If you need a validating parser or complete XPath support, lxml is the way to go. For a long time, it used to be quite unstable, but I haven't had any problems with it since 2.1.</p>\n\n<p>ElementTree deviates from DOM, where nodes have access to their parent and siblings. Handling actual documents rather than data stores is also a bit cumbersome, because text nodes aren't treated as actual nodes. In the XML snippet</p>\n\n<pre><code><a>This is <b>a</b> test</a>\n</code></pre>\n\n<p>The string <code>test</code> will be the so-called <code>tail</code> of element <code>b</code>.</p>\n\n<p>In general, I recommend ElementTree as the default for all XML processing with Python, and DOM or SAX as the solutions for specific problems.</p>\n"
},
{
"answer_id": 15452402,
"author": "Paolo Rovelli",
"author_id": 2128591,
"author_profile": "https://Stackoverflow.com/users/2128591",
"pm_score": 4,
"selected": false,
"text": "<h1>Minimal DOM implementation:</h1>\n\n<p><a href=\"http://docs.python.org/2/library/xml.dom.minidom.html#module-xml.dom.minidom\" rel=\"nofollow noreferrer\">Link</a>.</p>\n\n<p>Python supplies a full, W3C-standard implementation of XML DOM (<em>xml.dom</em>) and a minimal one, <em>xml.dom.minidom</em>. This latter one is simpler and smaller than the full implementation. However, from a \"parsing perspective\", it has all the pros and cons of the standard DOM - i.e. it loads everything in memory.</p>\n\n<p>Considering a basic XML file:</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<catalog>\n <book isdn=\"xxx-1\">\n <author>A1</author>\n <title>T1</title>\n </book>\n <book isdn=\"xxx-2\">\n <author>A2</author>\n <title>T2</title>\n </book>\n</catalog>\n</code></pre>\n\n<p>A possible Python parser using <em>minidom</em> is:</p>\n\n<pre><code>import os\nfrom xml.dom import minidom\nfrom xml.parsers.expat import ExpatError\n\n#-------- Select the XML file: --------#\n#Current file name and directory:\ncurpath = os.path.dirname( os.path.realpath(__file__) )\nfilename = os.path.join(curpath, \"sample.xml\")\n#print \"Filename: %s\" % (filename)\n\n#-------- Parse the XML file: --------#\ntry:\n #Parse the given XML file:\n xmldoc = minidom.parse(filepath)\nexcept ExpatError as e:\n print \"[XML] Error (line %d): %d\" % (e.lineno, e.code)\n print \"[XML] Offset: %d\" % (e.offset)\n raise e\nexcept IOError as e:\n print \"[IO] I/O Error %d: %s\" % (e.errno, e.strerror)\n raise e\nelse:\n catalog = xmldoc.documentElement\n books = catalog.getElementsByTagName(\"book\")\n\n for book in books:\n print book.getAttribute('isdn')\n print book.getElementsByTagName('author')[0].firstChild.data\n print book.getElementsByTagName('title')[0].firstChild.data\n</code></pre>\n\n<p>Note that <em>xml.parsers.expat</em> is a Python interface to the Expat non-validating XML parser (docs.python.org/2/library/pyexpat.html).</p>\n\n<p>The <em>xml.dom</em> package supplies also the exception class <em>DOMException</em>, but it is not supperted in <em>minidom</em>!</p>\n\n<h1>The ElementTree XML API:</h1>\n\n<p><a href=\"http://docs.python.org/2/library/xml.etree.elementtree.html\" rel=\"nofollow noreferrer\">Link</a>.</p>\n\n<p><em>ElementTree</em> is much easier to use and it requires less memory than XML DOM. Furthermore, a C implementation is available (<em>xml.etree.cElementTree</em>).</p>\n\n<p>A possible Python parser using <em>ElementTree</em> is:</p>\n\n<pre><code>import os\nfrom xml.etree import cElementTree # C implementation of xml.etree.ElementTree\nfrom xml.parsers.expat import ExpatError # XML formatting errors\n\n#-------- Select the XML file: --------#\n#Current file name and directory:\ncurpath = os.path.dirname( os.path.realpath(__file__) )\nfilename = os.path.join(curpath, \"sample.xml\")\n#print \"Filename: %s\" % (filename)\n\n#-------- Parse the XML file: --------#\ntry:\n #Parse the given XML file:\n tree = cElementTree.parse(filename)\nexcept ExpatError as e:\n print \"[XML] Error (line %d): %d\" % (e.lineno, e.code)\n print \"[XML] Offset: %d\" % (e.offset)\n raise e\nexcept IOError as e:\n print \"[XML] I/O Error %d: %s\" % (e.errno, e.strerror)\n raise e\nelse:\n catalogue = tree.getroot()\n\n for book in catalogue:\n print book.attrib.get(\"isdn\")\n print book.find('author').text\n print book.find('title').text\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16148/"
] |
Python has several ways to parse XML...
I understand the very basics of parsing with **SAX**. It functions as a stream parser, with an event-driven API.
I understand the **DOM** parser also. It reads the XML into memory and converts it to objects that can be accessed with Python.
Generally speaking, it was easy to choose between the two depending on what you needed to do, memory constraints, performance, etc.
(Hopefully I'm correct so far.)
Since Python 2.5, we also have **ElementTree**. How does this compare to DOM and SAX? Which is it more similar to? Why is it better than the previous parsers?
|
ElementTree is much easier to use, because it represents an XML tree (basically) as a structure of lists, and attributes are represented as dictionaries.
ElementTree needs much less memory for XML trees than DOM (and thus is faster), and the parsing overhead via `iterparse` is comparable to SAX. Additionally, `iterparse` returns partial structures, and you can keep memory usage constant during parsing by discarding the structures as soon as you process them.
ElementTree, as in Python 2.5, has only a small feature set compared to full-blown XML libraries, but it's enough for many applications. If you need a validating parser or complete XPath support, lxml is the way to go. For a long time, it used to be quite unstable, but I haven't had any problems with it since 2.1.
ElementTree deviates from DOM, where nodes have access to their parent and siblings. Handling actual documents rather than data stores is also a bit cumbersome, because text nodes aren't treated as actual nodes. In the XML snippet
```
<a>This is <b>a</b> test</a>
```
The string `test` will be the so-called `tail` of element `b`.
In general, I recommend ElementTree as the default for all XML processing with Python, and DOM or SAX as the solutions for specific problems.
|
192,915 |
<p>Within my Subversion project I have a few directories that contain other open source projects that my code needs. For example ffmpeg, freetype, matrixssl and a few others. </p>
<p>What is the best way to update SVN to hold the the latest version of one of these projects?</p>
<p>Essentially I will be doing the following (using ffmpeg as an example):</p>
<pre><code>1) Rename current ffmpeg folder to ffmpeg.old
2) Download new version of ffmpeg from net
3) Make sure it and my code compile and work fine together
4) Update subversion to now hold the "new" version of ffmpeg
5) Delete ffmpeg.old directory tree
</code></pre>
|
[
{
"answer_id": 192925,
"author": "Dandikas",
"author_id": 23436,
"author_profile": "https://Stackoverflow.com/users/23436",
"pm_score": 1,
"selected": false,
"text": "<p>All is correct except that you don't need steps 1 and 5 - if step 3 fails revert changes using svn revert functionality.</p>\n"
},
{
"answer_id": 192930,
"author": "Tilendor",
"author_id": 1470,
"author_profile": "https://Stackoverflow.com/users/1470",
"pm_score": 0,
"selected": false,
"text": "<p>I think you've got two options.</p>\n\n<p><strong>A)</strong></p>\n\n<ol>\n<li>SVN Delete all the files.</li>\n<li>Get current & make it work.</li>\n<li>SVN Add all the files.</li>\n</ol>\n\n<p>Pro: Will make sure no extra files are kept if they are not present in the latest version.</p>\n\n<p>Con: May be time consuming.</p>\n\n<p><strong>B)</strong></p>\n\n<ol>\n<li>Download and install the new version over the old one.</li>\n<li>Make it work.</li>\n<li>SVN add any new files.</li>\n</ol>\n\n<p>Pro: You can see what has changed in the files of the tool.</p>\n\n<p>Con: May end up with clutter. Depending upon the tool overwriting may cause bugs.</p>\n"
},
{
"answer_id": 192946,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 2,
"selected": false,
"text": "<p>I've got the same situation with CMake, where I keep the binary win32 release checked into our vendor directory:</p>\n\n<pre><code>branches/\ntrunk/\nvendor/\n cmake/\n cmake-2.6.0/\n cmake-2.6.1/\n cmake-2.6.2/\n ...\n</code></pre>\n\n<p>I then use svn:externals to refer to the CMake version I'm using. Makes it really easy to test upgrading to new versions, and it is also clear which version of CMake I'm using.</p>\n"
},
{
"answer_id": 192965,
"author": "Peter Parker",
"author_id": 23264,
"author_profile": "https://Stackoverflow.com/users/23264",
"pm_score": 5,
"selected": true,
"text": "<p>You can take a look to svnbook talking about <a href=\"http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.advanced.vendorbr\" rel=\"noreferrer\">vendor branches</a>. This is exactly what you try to accomplish</p>\n\n<p>You can use <strong>svn_load_dirs.pl</strong> to replace your manual steps 1-5. svn_load_dirs.pl will also keep track of new, moved or deleted files.</p>\n"
},
{
"answer_id": 193760,
"author": "Black",
"author_id": 25234,
"author_profile": "https://Stackoverflow.com/users/25234",
"pm_score": 0,
"selected": false,
"text": "<p>If some of the vendor projects also use Subversion, You can add\nthe <em>svn:externals</em> property to the parent directory of Your branch/trunk.</p>\n\n<p>Take a look at the <a href=\"http://svnbook.red-bean.com/en/1.0/ch07s03.html\" rel=\"nofollow noreferrer\">SVN book</a> for more details.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
] |
Within my Subversion project I have a few directories that contain other open source projects that my code needs. For example ffmpeg, freetype, matrixssl and a few others.
What is the best way to update SVN to hold the the latest version of one of these projects?
Essentially I will be doing the following (using ffmpeg as an example):
```
1) Rename current ffmpeg folder to ffmpeg.old
2) Download new version of ffmpeg from net
3) Make sure it and my code compile and work fine together
4) Update subversion to now hold the "new" version of ffmpeg
5) Delete ffmpeg.old directory tree
```
|
You can take a look to svnbook talking about [vendor branches](http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.advanced.vendorbr). This is exactly what you try to accomplish
You can use **svn\_load\_dirs.pl** to replace your manual steps 1-5. svn\_load\_dirs.pl will also keep track of new, moved or deleted files.
|
192,924 |
<p>Can you get the distinct combination of 2 different fields in a database table? if so, can you provide the SQL example.</p>
|
[
{
"answer_id": 192933,
"author": "Howard Pinsley",
"author_id": 7961,
"author_profile": "https://Stackoverflow.com/users/7961",
"pm_score": 8,
"selected": true,
"text": "<p>How about simply:</p>\n\n<pre><code>select distinct c1, c2 from t\n</code></pre>\n\n<p>or</p>\n\n<pre><code>select c1, c2, count(*)\nfrom t\ngroup by c1, c2\n</code></pre>\n"
},
{
"answer_id": 192950,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 4,
"selected": false,
"text": "<p>If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.</p>\n"
},
{
"answer_id": 15370893,
"author": "Denno",
"author_id": 2162666,
"author_profile": "https://Stackoverflow.com/users/2162666",
"pm_score": 3,
"selected": false,
"text": "<p>If you still want to group only by one column (as I wanted) you can nest the query:</p>\n\n<pre><code>select c1, count(*) from (select distinct c1, c2 from t) group by c1\n</code></pre>\n"
},
{
"answer_id": 17667639,
"author": "Wilson Wu",
"author_id": 1756039,
"author_profile": "https://Stackoverflow.com/users/1756039",
"pm_score": 3,
"selected": false,
"text": "<p>You can get result distinct by two columns use below SQL:</p>\n\n<pre><code>SELECT COUNT(*) FROM (SELECT DISTINCT c1, c2 FROM [TableEntity]) TE\n</code></pre>\n"
},
{
"answer_id": 55280856,
"author": "youkaichao",
"author_id": 9191338,
"author_profile": "https://Stackoverflow.com/users/9191338",
"pm_score": 2,
"selected": false,
"text": "<p>Share my stupid thought: </p>\n\n<p>Maybe I can select distinct only on c1 but not on c2, so the syntax may be <code>select ([distinct] col)+</code> where <code>distinct</code> is a qualifier for each column. </p>\n\n<p>But after thought, I find that <strong>distinct on only one column is nonsense</strong>. Take the following relationship:</p>\n\n<pre><code> | A | B\n__________\n 1| 1 | 2\n 2| 1 | 1\n</code></pre>\n\n<p>If we <code>select (distinct A), B</code>, then what is the proper <code>B</code> for <code>A = 1</code>?</p>\n\n<p>Thus, <code>distinct</code> is a qualifier for a <code>statement</code>.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
Can you get the distinct combination of 2 different fields in a database table? if so, can you provide the SQL example.
|
How about simply:
```
select distinct c1, c2 from t
```
or
```
select c1, c2, count(*)
from t
group by c1, c2
```
|
192,980 |
<p>I've recently created these two (unrelated) methods to replace lots of boiler-plate code in my winforms application. As far as I can tell, they work ok, but I need some reassurance/advice on whether there are some problems I might be missing.</p>
<p>(from memory)</p>
<pre><code>static class SafeInvoker
{
//Utility to avoid boiler-plate InvokeRequired code
//Usage: SafeInvoker.Invoke(myCtrl, () => myCtrl.Enabled = false);
public static void Invoke(Control ctrl, Action cmd)
{
if (ctrl.InvokeRequired)
ctrl.BeginInvoke(new MethodInvoker(cmd));
else
cmd();
}
//Replaces OnMyEventRaised boiler-plate code
//Usage: SafeInvoker.RaiseEvent(this, MyEventRaised)
public static void RaiseEvent(object sender, EventHandler evnt)
{
var handler = evnt;
if (handler != null)
handler(sender, EventArgs.Empty);
}
}
</code></pre>
<p>EDIT: See related question <a href="https://stackoverflow.com/questions/258409/how-to-get-information-about-an-exception-raised-by-the-target-of-controlinvoke">here</a></p>
<p><strong>UPDATE</strong></p>
<p>Following on from deadlock problems (related in <a href="https://stackoverflow.com/questions/2055960/control-invoke-getting-stuck-in-hidden-showdialog">this question</a>), I have switched from Invoke to BeginInvoke (see an explanation <a href="https://stackoverflow.com/questions/229554/whats-the-difference-between-invoke-and-begininvoke/229558#229558">here</a>).</p>
<p><strong>Another Update</strong></p>
<p>Regarding the second snippet, I am increasingly inclined to use the 'empty delegate' pattern, which fixes this problem 'at source' by declaring the event directly with an empty handler, like so:</p>
<pre><code>event EventHandler MyEventRaised = delegate {};
</code></pre>
|
[
{
"answer_id": 193012,
"author": "eulerfx",
"author_id": 13855,
"author_profile": "https://Stackoverflow.com/users/13855",
"pm_score": 0,
"selected": false,
"text": "<p>Similar patterns have worked for me with no problems. I am not sure why you are wrapping Action in MethodInvoker though.</p>\n"
},
{
"answer_id": 193038,
"author": "programmer",
"author_id": 5289,
"author_profile": "https://Stackoverflow.com/users/5289",
"pm_score": 5,
"selected": true,
"text": "<p>This is good stuff. Make them extension methods though to clean up your code a little more. For example:</p>\n\n<pre><code>//Replaces OnMyEventRaised boiler-plate code\n//Usage: SafeInvoker.RaiseEvent(this, MyEventRaised)\npublic static void Raise(this EventHandler eventToRaise, object sender)\n{\n EventHandler eventHandler = eventToRaise;\n\n if (eventHandler != null)\n eventHandler(sender, EventArgs.Empty);\n}\n</code></pre>\n\n<p>Now on your events you can call: myEvent.Raise(this);</p>\n"
},
{
"answer_id": 2057360,
"author": "Oliver",
"author_id": 1838048,
"author_profile": "https://Stackoverflow.com/users/1838048",
"pm_score": 2,
"selected": false,
"text": "<p>Due to the fact, that Benjol doesn't know, why he places the Action into a MethodInvoker and broccliman meant to use it as an Extension Function, here is the clean up code:</p>\n\n<pre><code>static class SafeInvoker\n{\n //Utility to avoid boiler-plate InvokeRequired code\n //Usage: myCtrl.SafeInvoke(() => myCtrl.Enabled = false);\n public static void SafeInvoke(this Control ctrl, Action cmd)\n {\n if (ctrl.InvokeRequired)\n ctrl.BeginInvoke(cmd);\n else\n cmd();\n }\n\n //Replaces OnMyEventRaised boiler-plate code\n //Usage: this.RaiseEvent(myEventRaised);\n public static void RaiseEvent(this object sender, EventHandler evnt)\n {\n if (evnt != null)\n evnt(sender, EventArgs.Empty);\n }\n}\n</code></pre>\n\n<p>Just a last note: <code>MethodInvoker</code> and <code>Action</code> are both just delegates having the exact same structure. Due to this case both are replaceable by each other. The root of this naming clash comes from legacy. At the beginning (.Net 2.0) there was just <code>MethodInvoker</code> and <code>Action(T)</code>. But due to the fact, that everyone who used <code>Action(T)</code> whishes to have a <code>Action</code> and found it very unnatural to take <code>MethodInvoker</code>. So in .Net 3.5 the <code>Action</code>, <code>Action(T1, T2, T3, T4)</code> and all the <code>Func</code> delegates where added too, but MethodInvoker could not be removed anymore without making any breaking changes.</p>\n\n<h3>Additional:</h3>\n\n<p>If you are able to use .Net 3.5 the above code is fine, but if you're pinned to .Net 2.0 you can use it as normal function as before and replace <code>Action</code> by <code>MethodInvoker</code>.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11410/"
] |
I've recently created these two (unrelated) methods to replace lots of boiler-plate code in my winforms application. As far as I can tell, they work ok, but I need some reassurance/advice on whether there are some problems I might be missing.
(from memory)
```
static class SafeInvoker
{
//Utility to avoid boiler-plate InvokeRequired code
//Usage: SafeInvoker.Invoke(myCtrl, () => myCtrl.Enabled = false);
public static void Invoke(Control ctrl, Action cmd)
{
if (ctrl.InvokeRequired)
ctrl.BeginInvoke(new MethodInvoker(cmd));
else
cmd();
}
//Replaces OnMyEventRaised boiler-plate code
//Usage: SafeInvoker.RaiseEvent(this, MyEventRaised)
public static void RaiseEvent(object sender, EventHandler evnt)
{
var handler = evnt;
if (handler != null)
handler(sender, EventArgs.Empty);
}
}
```
EDIT: See related question [here](https://stackoverflow.com/questions/258409/how-to-get-information-about-an-exception-raised-by-the-target-of-controlinvoke)
**UPDATE**
Following on from deadlock problems (related in [this question](https://stackoverflow.com/questions/2055960/control-invoke-getting-stuck-in-hidden-showdialog)), I have switched from Invoke to BeginInvoke (see an explanation [here](https://stackoverflow.com/questions/229554/whats-the-difference-between-invoke-and-begininvoke/229558#229558)).
**Another Update**
Regarding the second snippet, I am increasingly inclined to use the 'empty delegate' pattern, which fixes this problem 'at source' by declaring the event directly with an empty handler, like so:
```
event EventHandler MyEventRaised = delegate {};
```
|
This is good stuff. Make them extension methods though to clean up your code a little more. For example:
```
//Replaces OnMyEventRaised boiler-plate code
//Usage: SafeInvoker.RaiseEvent(this, MyEventRaised)
public static void Raise(this EventHandler eventToRaise, object sender)
{
EventHandler eventHandler = eventToRaise;
if (eventHandler != null)
eventHandler(sender, EventArgs.Empty);
}
```
Now on your events you can call: myEvent.Raise(this);
|
192,997 |
<p>I have a Windows forms project and a Web Service project in my solution, and I'm trying to call the web service and return a customer object as the result. The problem is that when I try to receive the return object, I get an error that it can't convert it. For example, here is the signature for my webservice:</p>
<pre><code>Public Function GetDriverByID(ByVal DriverID As Integer) As Driver
</code></pre>
<p>And here is the code I'm using to call it:</p>
<pre><code> Dim d As Driver = mywebserviceinstance.GetDriverByID(1)
</code></pre>
<p>But I receive this compile-time error (wsDrivers is the name of the web reference I've added to my form project): "Value of type ProjectNamespace.Common.wsDrivers.Driver cannot be converted to ProjectNamespace.Common.Driver"</p>
<p>This "Common" namespace contains the Driver class, and I'm not sure why the return class from the web service isn't just a generic "Driver", but is instead a "wsDrivers.Driver", and I can't convert it back. Anybody know how I can deal with this type mismatch?</p>
<p>EDIT: Thanks for the explanations - this actually makes it clear what it's doing. However, is there any way that I can force it to use the actual type instead of the proxy (or, rather, is there any way to convert between the "real" instance and the "proxy" instance), or do I have to serialize the properties before I send them over the wire, and then manually de-serialize the return values?</p>
|
[
{
"answer_id": 193018,
"author": "hangy",
"author_id": 11963,
"author_profile": "https://Stackoverflow.com/users/11963",
"pm_score": 0,
"selected": false,
"text": "<p>The web service reference in a VB.NET or C# project can reference <em>any</em> type of web service and is not limited to those provided by ASP.NET. That is why Visual Studio creates proxy classes for each object which can be retrieved from the web service.</p>\n"
},
{
"answer_id": 193023,
"author": "Nick",
"author_id": 22407,
"author_profile": "https://Stackoverflow.com/users/22407",
"pm_score": 3,
"selected": true,
"text": "<p>This is actually pretty common. What's happening is that the Web Service has defined in it the definitions of all the types used in the web service. When you add a reference to that web service, it auto-generates a proxy type in a sub namespace of your namespace. That is what is being returned by your web service when you call it.</p>\n\n<p>However, you probably are also referencing the same library that the web service does seperately that contains the same type. That is the type that is expected when you Dim Driver. That's why there is a mismatch.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8114/"
] |
I have a Windows forms project and a Web Service project in my solution, and I'm trying to call the web service and return a customer object as the result. The problem is that when I try to receive the return object, I get an error that it can't convert it. For example, here is the signature for my webservice:
```
Public Function GetDriverByID(ByVal DriverID As Integer) As Driver
```
And here is the code I'm using to call it:
```
Dim d As Driver = mywebserviceinstance.GetDriverByID(1)
```
But I receive this compile-time error (wsDrivers is the name of the web reference I've added to my form project): "Value of type ProjectNamespace.Common.wsDrivers.Driver cannot be converted to ProjectNamespace.Common.Driver"
This "Common" namespace contains the Driver class, and I'm not sure why the return class from the web service isn't just a generic "Driver", but is instead a "wsDrivers.Driver", and I can't convert it back. Anybody know how I can deal with this type mismatch?
EDIT: Thanks for the explanations - this actually makes it clear what it's doing. However, is there any way that I can force it to use the actual type instead of the proxy (or, rather, is there any way to convert between the "real" instance and the "proxy" instance), or do I have to serialize the properties before I send them over the wire, and then manually de-serialize the return values?
|
This is actually pretty common. What's happening is that the Web Service has defined in it the definitions of all the types used in the web service. When you add a reference to that web service, it auto-generates a proxy type in a sub namespace of your namespace. That is what is being returned by your web service when you call it.
However, you probably are also referencing the same library that the web service does seperately that contains the same type. That is the type that is expected when you Dim Driver. That's why there is a mismatch.
|
192,998 |
<p>I have some custom SharePoint site definitions that are deployed via SharePoint wsp solution packages. They appear to work fine. I can deploy them fine via the stsadm command line, and my C# code running in some features can also deploy sites based on them. My <code>webtemp.*.xml</code> files appear to be correctly placed in the <code>12\1033\XML</code> folder when my solutions are deployed. My problem is that they just don't show up in the central admin app when I try to <code>Create Site Collection.</code> Why not? I don't even know where to look for this.</p>
<hr>
<p><strong>EDIT:</strong></p>
<p>Hmmm.. About an hour later I happened to go back to the create site collection page and my templates were there. I'm not sure what was up... weird caching somewhere or something. </p>
<p>I also should have been more clear that these solution packages had been successfully deployed many times on my dev box, so I didn't expect there to be a problem (with the deployment aspect anyway) on this other server.</p>
|
[
{
"answer_id": 193022,
"author": "MrChrister",
"author_id": 24229,
"author_profile": "https://Stackoverflow.com/users/24229",
"pm_score": 0,
"selected": false,
"text": "<p>Do you have the publishing feature enabled? I read that content types can't be saved in templates, so they don't allow publishing sites to be made into templates. This is perhaps linked to why they won't show you the ones you already made. </p>\n\n<p>Although I don't have access to a central admin to verify, this is the case from within my site collection.</p>\n"
},
{
"answer_id": 193907,
"author": "Nico",
"author_id": 22970,
"author_profile": "https://Stackoverflow.com/users/22970",
"pm_score": 0,
"selected": false,
"text": "<p>Did you forget to run iisreset ?\nThis is needed for SharePoint to reload site templates.</p>\n"
},
{
"answer_id": 815391,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Many tasks in SharePoint are queued and then executed via timer job. An IISReset causes the web applicationt to be reloaded into memory and for configuration information for example the web.config to be reloaded. </p>\n\n<p>To give SharePoint a \"nudge\" and cause jobs to execute you might try: </p>\n\n<pre><code>stsadm -o execadmsvcjobs\n</code></pre>\n"
},
{
"answer_id": 9710852,
"author": "Jason S",
"author_id": 691965,
"author_profile": "https://Stackoverflow.com/users/691965",
"pm_score": 0,
"selected": false,
"text": "<p>If you use the Record Center as the template for your root website, templates (.stp files) in your template library will not show up when creating a new list. </p>\n\n<p>There is some weird bug that makes this happen.</p>\n\n<p>Here is code that you can try running in the SharePoint PowerShell. The return value for GetCustomListTemplates($web).Count will be zero if you have the root web made from the Record Center template.</p>\n\n<pre><code>$site = get-spsite(\"http://localhost\")\n$web = $site.RootWeb\n$list = $web.Lists[\"TestDocLibrary\"]\n$list.SaveAsTemplate(\"MyListTemplate.stp\", \"MyListTemplate\", \"My List Template\", $false)\n$site.GetCustomListTemplates($web).Count\n</code></pre>\n\n<p>More information can be found at the following links:</p>\n\n<ul>\n<li><a href=\"http://social.msdn.microsoft.com/Forums/ar/sharepoint2010general/thread/c5455a27-360a-465c-91d5-f81beeac6789\" rel=\"nofollow\">http://social.msdn.microsoft.com/Forums/ar/sharepoint2010general/thread/c5455a27-360a-465c-91d5-f81beeac6789</a> </li>\n<li><a href=\"http://sharepointrecordsmanagement.com/2011/02/\" rel=\"nofollow\">http://sharepointrecordsmanagement.com/2011/02/</a> </li>\n</ul>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/192998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
] |
I have some custom SharePoint site definitions that are deployed via SharePoint wsp solution packages. They appear to work fine. I can deploy them fine via the stsadm command line, and my C# code running in some features can also deploy sites based on them. My `webtemp.*.xml` files appear to be correctly placed in the `12\1033\XML` folder when my solutions are deployed. My problem is that they just don't show up in the central admin app when I try to `Create Site Collection.` Why not? I don't even know where to look for this.
---
**EDIT:**
Hmmm.. About an hour later I happened to go back to the create site collection page and my templates were there. I'm not sure what was up... weird caching somewhere or something.
I also should have been more clear that these solution packages had been successfully deployed many times on my dev box, so I didn't expect there to be a problem (with the deployment aspect anyway) on this other server.
|
Many tasks in SharePoint are queued and then executed via timer job. An IISReset causes the web applicationt to be reloaded into memory and for configuration information for example the web.config to be reloaded.
To give SharePoint a "nudge" and cause jobs to execute you might try:
```
stsadm -o execadmsvcjobs
```
|
193,020 |
<p>If I define a constant in a Perl module, how do I use that constant in my main program? (Or how do I call that constant in the main program?)</p>
|
[
{
"answer_id": 193031,
"author": "friedo",
"author_id": 20745,
"author_profile": "https://Stackoverflow.com/users/20745",
"pm_score": 6,
"selected": false,
"text": "<p>Constants can be exported just like other package symbols. Using the standard <a href=\"http://search.cpan.org/~ferreira/Exporter-5.63/lib/Exporter.pm\" rel=\"noreferrer\">Exporter</a> module, you can export constants from a package like this:</p>\n\n<pre><code>package Foo;\nuse strict;\nuse warnings;\n\nuse base 'Exporter';\n\nuse constant CONST => 42;\n\nour @EXPORT_OK = ('CONST');\n\n1;\n</code></pre>\n\n<p>Then, in a client script (or other module)</p>\n\n<pre><code>use Foo 'CONST';\nprint CONST;\n</code></pre>\n\n<p>You can use the <code>%EXPORT_TAGS</code> hash (see the Exporter documentation) to define groups of constants that can be exported with a single import argument.</p>\n\n<p>Update: Here's an example of how to use the <code>%EXPORT_TAGS</code> feature if you have multiple constants. </p>\n\n<pre><code>use constant LARRY => 42;\nuse constant CURLY => 43;\nuse constant MOE => 44;\n\nour @EXPORT_OK = ('LARRY', 'CURLY', 'MOE');\nour %EXPORT_TAGS = ( stooges => [ 'LARRY', 'CURLY', 'MOE' ] );\n</code></pre>\n\n<p>Then you can say</p>\n\n<pre><code>use Foo ':stooges';\nprint \"$_\\n\" for LARRY, CURLY, MOE;\n</code></pre>\n"
},
{
"answer_id": 193037,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 5,
"selected": false,
"text": "<p>Constants are just subs with empty prototype, so they can be exported like any other sub.</p>\n\n<pre><code># file Foo.pm\npackage Foo;\nuse constant BAR => 123;\nuse Exporter qw(import);\nour @EXPORT_OK = qw(BAR);\n\n\n# file main.pl:\nuse Foo qw(BAR);\nprint BAR;\n</code></pre>\n"
},
{
"answer_id": 193069,
"author": "Tanktalus",
"author_id": 23512,
"author_profile": "https://Stackoverflow.com/users/23512",
"pm_score": 5,
"selected": false,
"text": "<p>To expand on the earlier answers, since constants are really just subs, you can <em>also</em> call them directly:</p>\n\n<pre><code>use Foo;\nprint Foo::BAR;\n</code></pre>\n"
},
{
"answer_id": 193935,
"author": "Berserk",
"author_id": 26313,
"author_profile": "https://Stackoverflow.com/users/26313",
"pm_score": 4,
"selected": false,
"text": "<p>You might want to consider using <a href=\"http://search.cpan.org/~roode/Readonly-1.03/Readonly.pm\" rel=\"noreferrer\">Readonly</a> instead of constant.</p>\n"
},
{
"answer_id": 195946,
"author": "maletin",
"author_id": 27239,
"author_profile": "https://Stackoverflow.com/users/27239",
"pm_score": 3,
"selected": false,
"text": "<pre><code>package Foo;\nuse Readonly;\nReadonly my $C1 => 'const1';\nReadonly our $C2 => 'const2';\nsub get_c1 { return $C1 }\n1;\n\nperl -MFoo -e 'print \"$_\\n\" for Foo->get_c1, $Foo::C2'\n</code></pre>\n"
},
{
"answer_id": 214795,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 3,
"selected": false,
"text": "<p>To add to the bag of tricks, since a constant is just a subroutine you can even call it as a class method.</p>\n\n<pre><code>package Foo;\nuse constant PI => 3.14;\n\nprint Foo->PI;\n</code></pre>\n\n<p>If you have lots of constants it's a nice way to get at the occasional one without having to export them all. However, unlike <code>Foo::PI</code> or exporting <code>PI</code>, Perl will not compile out <code>Foo->PI</code> so you incur the cost of a method call (which probably doesn't matter).</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26964/"
] |
If I define a constant in a Perl module, how do I use that constant in my main program? (Or how do I call that constant in the main program?)
|
Constants can be exported just like other package symbols. Using the standard [Exporter](http://search.cpan.org/~ferreira/Exporter-5.63/lib/Exporter.pm) module, you can export constants from a package like this:
```
package Foo;
use strict;
use warnings;
use base 'Exporter';
use constant CONST => 42;
our @EXPORT_OK = ('CONST');
1;
```
Then, in a client script (or other module)
```
use Foo 'CONST';
print CONST;
```
You can use the `%EXPORT_TAGS` hash (see the Exporter documentation) to define groups of constants that can be exported with a single import argument.
Update: Here's an example of how to use the `%EXPORT_TAGS` feature if you have multiple constants.
```
use constant LARRY => 42;
use constant CURLY => 43;
use constant MOE => 44;
our @EXPORT_OK = ('LARRY', 'CURLY', 'MOE');
our %EXPORT_TAGS = ( stooges => [ 'LARRY', 'CURLY', 'MOE' ] );
```
Then you can say
```
use Foo ':stooges';
print "$_\n" for LARRY, CURLY, MOE;
```
|
193,044 |
<p>Languages like C and even C# (which technically doesn't have a preprocessor) allow you to write code like:</p>
<pre><code>#DEFINE DEBUG
...
string returnedStr = this.SomeFoo();
#if DEBUG
Debug.WriteLine("returned string =" + returnedStr);
#endif
</code></pre>
<p>This is something I like to use in my code as a form of scaffolding, and I'm wondering if PHP has something like this. I'm sure I can emulate this with variables, but I imagine the fact that PHP is interpreted in most cases will not make it easy to strip/remove the debugging code (since its not needed) automatically when executing it.</p>
|
[
{
"answer_id": 193072,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 4,
"selected": true,
"text": "<p>PHP doesn't have anything like this. but you could definitely whip up something quickly (and perhaps a regex parse to strip it out later if you wanted). i'd do it as such:</p>\n\n<pre><code>define('DEBUG', true);\n...\nif (DEBUG):\n $debug->writeLine(\"stuff\");\nendif;\n</code></pre>\n\n<p>of course you'd have to write your own debug module to handle all that. if you wanted to make life easier on regex parsing, perhaps you could use a ternary operator instead:</p>\n\n<pre><code>$str = 'string';\nDEBUG ? $debug->writeLine(\"stuff is \".$str) : null;\n</code></pre>\n\n<p>which would make removing debug lines pretty trivial.</p>\n"
},
{
"answer_id": 193097,
"author": "douglashunter",
"author_id": 13838,
"author_profile": "https://Stackoverflow.com/users/13838",
"pm_score": 0,
"selected": false,
"text": "<p>It has a <code>define</code> funciton, documented here: <a href=\"http://us.php.net/manual/en/language.constants.php\" rel=\"nofollow noreferrer\">http://us.php.net/manual/en/language.constants.php</a>.</p>\n\n<p>Given the set of differences between variables and constants explained in the documentation, I assume that PHP's <code>define</code> allows the interpreter to eliminate unusable code paths at compile time, but that's just a guess.</p>\n\n<p>-- Douglas Hunter</p>\n"
},
{
"answer_id": 193099,
"author": "Jayrox",
"author_id": 24802,
"author_profile": "https://Stackoverflow.com/users/24802",
"pm_score": 1,
"selected": false,
"text": "<p>xdump is one of my personal favorites for debugging.</p>\n\n<p><a href=\"http://freshmeat.net/projects/xdump/\" rel=\"nofollow noreferrer\">http://freshmeat.net/projects/xdump/</a></p>\n\n<pre><code>define(DEBUG, true);\n\n[...]\n\nif(DEBUG) echo xdump::dump($debugOut);\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10708/"
] |
Languages like C and even C# (which technically doesn't have a preprocessor) allow you to write code like:
```
#DEFINE DEBUG
...
string returnedStr = this.SomeFoo();
#if DEBUG
Debug.WriteLine("returned string =" + returnedStr);
#endif
```
This is something I like to use in my code as a form of scaffolding, and I'm wondering if PHP has something like this. I'm sure I can emulate this with variables, but I imagine the fact that PHP is interpreted in most cases will not make it easy to strip/remove the debugging code (since its not needed) automatically when executing it.
|
PHP doesn't have anything like this. but you could definitely whip up something quickly (and perhaps a regex parse to strip it out later if you wanted). i'd do it as such:
```
define('DEBUG', true);
...
if (DEBUG):
$debug->writeLine("stuff");
endif;
```
of course you'd have to write your own debug module to handle all that. if you wanted to make life easier on regex parsing, perhaps you could use a ternary operator instead:
```
$str = 'string';
DEBUG ? $debug->writeLine("stuff is ".$str) : null;
```
which would make removing debug lines pretty trivial.
|
193,092 |
<p>I am just starting to fiddle with Excel via C# to be able to automate the creation, and addition to an Excel file.</p>
<p>I can open the file and update its data and move through the existing worksheets. My problem is how can I add new sheets?</p>
<p>I tried:</p>
<pre><code>Excel.Worksheet newWorksheet;
newWorksheet = (Excel.Worksheet)excelApp.ThisWorkbook.Worksheets.Add(
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
</code></pre>
<p>But I get below <em>COM Exception</em> and my googling has not given me any answer.</p>
<blockquote>
<p>Exception from HRESULT: 0x800A03EC Source is: "Interop.Excel"</p>
</blockquote>
<p>I am hoping someone maybe able to put me out of my misery.</p>
|
[
{
"answer_id": 193323,
"author": "AR.",
"author_id": 1354,
"author_profile": "https://Stackoverflow.com/users/1354",
"pm_score": 6,
"selected": true,
"text": "<p>You need to add a COM reference in your project to the <strong>\"<code>Microsoft Excel 11.0 Object Library</code>\"</strong> - or whatever version is appropriate.</p>\n\n<p>This code works for me:</p>\n\n<pre><code>private void AddWorksheetToExcelWorkbook(string fullFilename,string worksheetName)\n{\n Microsoft.Office.Interop.Excel.Application xlApp = null;\n Workbook xlWorkbook = null;\n Sheets xlSheets = null;\n Worksheet xlNewSheet = null;\n\n try {\n xlApp = new Microsoft.Office.Interop.Excel.Application();\n\n if (xlApp == null)\n return;\n\n // Uncomment the line below if you want to see what's happening in Excel\n // xlApp.Visible = true;\n\n xlWorkbook = xlApp.Workbooks.Open(fullFilename, 0, false, 5, \"\", \"\",\n false, XlPlatform.xlWindows, \"\",\n true, false, 0, true, false, false);\n\n xlSheets = xlWorkbook.Sheets as Sheets;\n\n // The first argument below inserts the new worksheet as the first one\n xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);\n xlNewSheet.Name = worksheetName;\n\n xlWorkbook.Save();\n xlWorkbook.Close(Type.Missing,Type.Missing,Type.Missing);\n xlApp.Quit();\n }\n finally {\n Marshal.ReleaseComObject(xlNewSheet);\n Marshal.ReleaseComObject(xlSheets);\n Marshal.ReleaseComObject(xlWorkbook);\n Marshal.ReleaseComObject(xlApp);\n xlApp = null;\n }\n}\n</code></pre>\n\n<blockquote>\n <p>Note that you want to be very careful about <a href=\"https://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c\">properly cleaning up and releasing your COM object references</a>. Included in that StackOverflow question is a useful rule of thumb: <em>\"Never use 2 dots with COM objects\"</em>. In your code; you're going to have real trouble with that. <em>My demo code above does NOT properly clean up the Excel app, but it's a start!</em></p>\n</blockquote>\n\n<p>Some other links that I found useful when looking into this question:</p>\n\n<ul>\n<li><a href=\"http://www.codeproject.com/KB/office/csharp_excel.aspx\" rel=\"nofollow noreferrer\">Opening and Navigating Excel with C#</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms173186(VS.80).aspx\" rel=\"nofollow noreferrer\">How to: Use COM Interop to Create an Excel Spreadsheet (C# Programming Guide)</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/6fczc37s(VS.80).aspx\" rel=\"nofollow noreferrer\">How to: Add New Worksheets to Workbooks</a></li>\n</ul>\n\n<p>According to MSDN </p>\n\n<blockquote>\n <p>To use COM interop, you must have\n administrator or Power User security\n permissions.</p>\n</blockquote>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 193453,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 0,
"selected": false,
"text": "<p>You can use OLEDB to create and manipulate Excel files. See <a href=\"https://stackoverflow.com/questions/151005/create-excel-xls-and-xlsx-file-from-c#151048\">this question</a> for links and samples.</p>\n"
},
{
"answer_id": 193762,
"author": "sbeskur",
"author_id": 10446,
"author_profile": "https://Stackoverflow.com/users/10446",
"pm_score": 2,
"selected": false,
"text": "<p>Another \"Up Tick\" for AR..., but if you don't have to use interop I would avoid it altogether. This product is actually quite interesting:\n<a href=\"http://www.clearoffice.com/\" rel=\"nofollow noreferrer\">http://www.clearoffice.com/</a> and it provides a very intuitive, fully managed, api for manipulation excel files and seems to be free. (at least for the time being) <a href=\"http://www.spreadsheetgear.com/\" rel=\"nofollow noreferrer\">SpreadSheetGear</a> is also excellent but pricey. </p>\n\n<p>my two cents.</p>\n"
},
{
"answer_id": 193856,
"author": "Jon",
"author_id": 6486,
"author_profile": "https://Stackoverflow.com/users/6486",
"pm_score": 3,
"selected": false,
"text": "<p>Would like to thank you for some excellent replies. @AR., your a star and it works perfectly. I had noticed last night that the <code>Excel.exe</code> was not closing; so I did some research and found out about how to release the COM objects. Here is my final code:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Reflection;\nusing System.IO;\nusing Excel;\n\nnamespace testExcelconsoleApp\n{\n class Program\n {\n private String fileLoc = @\"C:\\temp\\test.xls\";\n\n static void Main(string[] args)\n {\n Program p = new Program();\n p.createExcel();\n }\n\n private void createExcel()\n {\n Excel.Application excelApp = null;\n Excel.Workbook workbook = null;\n Excel.Sheets sheets = null;\n Excel.Worksheet newSheet = null;\n\n try\n {\n FileInfo file = new FileInfo(fileLoc);\n if (file.Exists)\n {\n excelApp = new Excel.Application();\n workbook = excelApp.Workbooks.Open(fileLoc, 0, false, 5, \"\", \"\",\n false, XlPlatform.xlWindows, \"\",\n true, false, 0, true, false, false);\n\n sheets = workbook.Sheets;\n\n //check columns exist\n foreach (Excel.Worksheet sheet in sheets)\n {\n Console.WriteLine(sheet.Name);\n sheet.Select(Type.Missing);\n\n System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);\n }\n\n newSheet = (Worksheet)sheets.Add(sheets[1], Type.Missing, Type.Missing, Type.Missing);\n newSheet.Name = \"My New Sheet\";\n newSheet.Cells[1, 1] = \"BOO!\";\n\n workbook.Save();\n workbook.Close(null, null, null);\n excelApp.Quit();\n }\n }\n finally\n {\n System.Runtime.InteropServices.Marshal.ReleaseComObject(newSheet);\n System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);\n System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);\n System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);\n\n newSheet = null;\n sheets = null;\n workbook = null;\n excelApp = null;\n\n GC.Collect();\n }\n }\n }\n}\n</code></pre>\n\n<p>Thank you for all your help.</p>\n"
},
{
"answer_id": 2111540,
"author": "hmm",
"author_id": 256043,
"author_profile": "https://Stackoverflow.com/users/256043",
"pm_score": 0,
"selected": false,
"text": "<p>Here are a couple things I figured out: </p>\n\n<ol>\n<li><p>You can't open more than one instance of the same object at the same time. For Example if you instanciate a new excel sheet object called <code>xlsheet1</code> you have to release it before creating another excel sheet object ex <code>xlsheet2</code>. It seem as COM looses track of the object and leaves a zombie process on the server.</p></li>\n<li><p>Using the open method associated with <code>excel.workbooks</code> also becomes difficult to close if you have multiple users accessing the same file. Use the Add method instead, it works just as good without locking the file. eg. <code>xlBook = xlBooks.Add(\"C:\\location\\XlTemplate.xls\")</code></p></li>\n<li><p>Place your garbage collection in a separate block or method after releasing the COM objects.</p></li>\n</ol>\n"
},
{
"answer_id": 9311992,
"author": "Leniel Maccaferri",
"author_id": 114029,
"author_profile": "https://Stackoverflow.com/users/114029",
"pm_score": 0,
"selected": false,
"text": "<p><strong>COM</strong> is definitely not a good way to go. More specifically, it's a no go if you're dealing with web environment...</p>\n\n<p>I've used with success the following open source projects:</p>\n\n<ul>\n<li><p>ExcelPackage for OOXML formats (Office 2007)</p></li>\n<li><p>NPOI for .XLS format (Office 2003)</p></li>\n</ul>\n\n<p>Take a look at these blog posts:</p>\n\n<p><a href=\"http://www.leniel.net/2009/07/creating-excel-spreadsheets-xls-xlsx-c.html\" rel=\"nofollow\">Creating Excel spreadsheets .XLS and .XLSX in C#</a></p>\n\n<p><a href=\"http://www.leniel.net/2009/10/npoi-with-excel-table-and-dynamic-chart.html\" rel=\"nofollow\">NPOI with Excel Table and dynamic Chart</a></p>\n"
},
{
"answer_id": 9959997,
"author": "Gokul",
"author_id": 1305548,
"author_profile": "https://Stackoverflow.com/users/1305548",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Do not forget to include <em>Reference</em> to <strong><code>Microsoft Excel 12.0/11.0 object Library</code></strong></p>\n</blockquote>\n\n<pre><code>using Excel = Microsoft.Office.Interop.Excel;\n// Include this Namespace\n</code></pre>\n\n<p>\n\n<pre><code>Microsoft.Office.Interop.Excel.Application xlApp = null;\nExcel.Workbook xlWorkbook = null;\nExcel.Sheets xlSheets = null;\nExcel.Worksheet xlNewSheet = null;\nstring worksheetName =\"Sheet_Name\";\nobject readOnly1 = false;\n\nobject isVisible = true;\n\nobject missing = System.Reflection.Missing.Value;\n\ntry\n{\n xlApp = new Microsoft.Office.Interop.Excel.Application();\n\n if (xlApp == null)\n return;\n\n // Uncomment the line below if you want to see what's happening in Excel\n // xlApp.Visible = true;\n\n xlWorkbook = xlApp.Workbooks.Open(@\"C:\\Book1.xls\", missing, readOnly1, missing, missing, missing, missing, missing, missing, missing, missing, isVisible, missing, missing, missing);\n\n xlSheets = (Excel.Sheets)xlWorkbook.Sheets;\n\n // The first argument below inserts the new worksheet as the first one\n xlNewSheet = (Excel.Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);\n xlNewSheet.Name = worksheetName;\n\n xlWorkbook.Save();\n xlWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);\n xlApp.Quit();\n}\nfinally\n{\n System.Runtime.InteropServices.Marshal.ReleaseComObject(xlNewSheet);\n System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheets);\n System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbook);\n System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);\n //xlApp = null;\n}\n</code></pre>\n"
},
{
"answer_id": 20488719,
"author": "Dobermaxx99",
"author_id": 1631890,
"author_profile": "https://Stackoverflow.com/users/1631890",
"pm_score": 0,
"selected": false,
"text": "<p>This is what i used to add addtional worksheet</p>\n\n<pre><code>Workbook workbook = null;\nWorksheet worksheet = null;\n\nworkbook = app.Workbooks.Add(1);\nworkbook.Sheets.Add();\n\nWorksheet additionalWorksheet = workbook.ActiveSheet;\n</code></pre>\n"
},
{
"answer_id": 26180388,
"author": "Jiri Tersel",
"author_id": 2660867,
"author_profile": "https://Stackoverflow.com/users/2660867",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem application-level add-in in VSTO, the exception HRESULT: 0x800A03EC when adding new sheet.</p>\n\n<blockquote>\n <p>The error code 0x800A03EC (or -2146827284) means NAME_NOT_FOUND; in\n other words, you've asked for something, and Excel can't find it.</p>\n</blockquote>\n\n<p>Dominic Zukiewicz @ <a href=\"https://stackoverflow.com/questions/891394/excel-error-hresult-0x800a03ec-while-trying-to-get-range-with-cells-name\">Excel error HRESULT: 0x800A03EC while trying to get range with cell's name</a></p>\n\n<p>Then I finally realized <strong>ThisWorkbook</strong> triggered the exception. <strong>ActiveWorkbook</strong> went OK.</p>\n\n<pre><code>Excel.Worksheet newSheetException = Globals.ThisAddIn.Application.ThisWorkbook.Worksheets.Add(Type.Missing, sheet, Type.Missing, Type.Missing);\nExcel.Worksheet newSheetNoException = Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets.Add(Type.Missing, sheet, Type.Missing, Type.Missing);\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6486/"
] |
I am just starting to fiddle with Excel via C# to be able to automate the creation, and addition to an Excel file.
I can open the file and update its data and move through the existing worksheets. My problem is how can I add new sheets?
I tried:
```
Excel.Worksheet newWorksheet;
newWorksheet = (Excel.Worksheet)excelApp.ThisWorkbook.Worksheets.Add(
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
```
But I get below *COM Exception* and my googling has not given me any answer.
>
> Exception from HRESULT: 0x800A03EC Source is: "Interop.Excel"
>
>
>
I am hoping someone maybe able to put me out of my misery.
|
You need to add a COM reference in your project to the **"`Microsoft Excel 11.0 Object Library`"** - or whatever version is appropriate.
This code works for me:
```
private void AddWorksheetToExcelWorkbook(string fullFilename,string worksheetName)
{
Microsoft.Office.Interop.Excel.Application xlApp = null;
Workbook xlWorkbook = null;
Sheets xlSheets = null;
Worksheet xlNewSheet = null;
try {
xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
return;
// Uncomment the line below if you want to see what's happening in Excel
// xlApp.Visible = true;
xlWorkbook = xlApp.Workbooks.Open(fullFilename, 0, false, 5, "", "",
false, XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
xlSheets = xlWorkbook.Sheets as Sheets;
// The first argument below inserts the new worksheet as the first one
xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
xlNewSheet.Name = worksheetName;
xlWorkbook.Save();
xlWorkbook.Close(Type.Missing,Type.Missing,Type.Missing);
xlApp.Quit();
}
finally {
Marshal.ReleaseComObject(xlNewSheet);
Marshal.ReleaseComObject(xlSheets);
Marshal.ReleaseComObject(xlWorkbook);
Marshal.ReleaseComObject(xlApp);
xlApp = null;
}
}
```
>
> Note that you want to be very careful about [properly cleaning up and releasing your COM object references](https://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c). Included in that StackOverflow question is a useful rule of thumb: *"Never use 2 dots with COM objects"*. In your code; you're going to have real trouble with that. *My demo code above does NOT properly clean up the Excel app, but it's a start!*
>
>
>
Some other links that I found useful when looking into this question:
* [Opening and Navigating Excel with C#](http://www.codeproject.com/KB/office/csharp_excel.aspx)
* [How to: Use COM Interop to Create an Excel Spreadsheet (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/ms173186(VS.80).aspx)
* [How to: Add New Worksheets to Workbooks](http://msdn.microsoft.com/en-us/library/6fczc37s(VS.80).aspx)
According to MSDN
>
> To use COM interop, you must have
> administrator or Power User security
> permissions.
>
>
>
Hope that helps.
|
193,096 |
<p>Why is an exception being thrown in the "f++" part of the code below ("IndexOutOfRangeException was unhandled by user code"):</p>
<pre><code>for (int f = 0; f < gnf; f++)
{
fieldNames[g] = grid.FieldName(f);
}
</code></pre>
<p>The bug is in the "fieldNames[g] = ..." part of the code, my algorithm should be:</p>
<pre><code>for (int f = 0; f < gnf; f++)
{
fieldNames[f] = grid.FieldName(f);
}
</code></pre>
<p>(This does not crash.) But the debugger is not showing the exception on the "fieldNames[g]..." line when the wrong (top) code runs.</p>
<p>I'm not using threads at this point so I don't see it being one of those "debugging exceptions in a threaded program is suicide" situations.</p>
<p>Why is the debugger showing the exception in the wrong place? Optimizations or something? Has anyone else had the debugger be "wrong" like this before?</p>
|
[
{
"answer_id": 193103,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ey1cdcx8.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ey1cdcx8.aspx</a></p>\n\n<p>You need to use the overloaded DateTime.Parse to accurately parse timezones.</p>\n"
},
{
"answer_id": 193106,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If a specific date and time format will be parsed across different locales, use one of the overloads of the ParseExact method and provide a format specifier. </p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2543/"
] |
Why is an exception being thrown in the "f++" part of the code below ("IndexOutOfRangeException was unhandled by user code"):
```
for (int f = 0; f < gnf; f++)
{
fieldNames[g] = grid.FieldName(f);
}
```
The bug is in the "fieldNames[g] = ..." part of the code, my algorithm should be:
```
for (int f = 0; f < gnf; f++)
{
fieldNames[f] = grid.FieldName(f);
}
```
(This does not crash.) But the debugger is not showing the exception on the "fieldNames[g]..." line when the wrong (top) code runs.
I'm not using threads at this point so I don't see it being one of those "debugging exceptions in a threaded program is suicide" situations.
Why is the debugger showing the exception in the wrong place? Optimizations or something? Has anyone else had the debugger be "wrong" like this before?
|
<http://msdn.microsoft.com/en-us/library/ey1cdcx8.aspx>
You need to use the overloaded DateTime.Parse to accurately parse timezones.
|
193,107 |
<p>I am using Oracle SQL (in SQLDeveloper, using the SQL Worksheet). I would like to print a statement before my select, such as</p>
<pre><code>PRINT 'Querying Table1';
SELECT * from Table1;
</code></pre>
<p>What do I use to Print / show text output? It's not Print, because that gives me the error: Bind Variable <code>Table1</code> is NOT DECLARED. DBMS_OUTPUT.PUT_LINE is an unknown command. (Obviously, I'm an inexperienced SQLDeveloper and Oracle user. There must be some synonym for Print, but I'm having trouble finding help on it without knowing what it is.)</p>
|
[
{
"answer_id": 193158,
"author": "Eddie Awad",
"author_id": 17273,
"author_profile": "https://Stackoverflow.com/users/17273",
"pm_score": 4,
"selected": false,
"text": "<p>You could <a href=\"http://download.oracle.com/docs/cd/B19306_01/server.102/b14357/ch12040.htm#SQPUG075\" rel=\"noreferrer\">set echo</a> to on:</p>\n\n<pre><code>set echo on\nREM Querying table\nselect * from dual;\n</code></pre>\n\n<p>In SQLDeveloper, hit F5 to run as a script.</p>\n"
},
{
"answer_id": 195000,
"author": "Leigh Riffel",
"author_id": 27010,
"author_profile": "https://Stackoverflow.com/users/27010",
"pm_score": 4,
"selected": false,
"text": "<p>You could put your text in a select statement such as...</p>\n\n<pre><code>SELECT 'Querying Table1' FROM dual;\n</code></pre>\n"
},
{
"answer_id": 360029,
"author": "Perry Tribolet",
"author_id": 5668,
"author_profile": "https://Stackoverflow.com/users/5668",
"pm_score": 8,
"selected": true,
"text": "<p><img src=\"https://i.stack.imgur.com/72MPn.png\" alt=\"enter image description here\"></p>\n\n<p>for simple comments:</p>\n\n<pre><code>set serveroutput on format wrapped;\nbegin\n DBMS_OUTPUT.put_line('simple comment');\nend;\n/\n\n-- do something\n\nbegin\n DBMS_OUTPUT.put_line('second simple comment');\nend;\n/\n</code></pre>\n\n<p>you should get:</p>\n\n<pre><code>anonymous block completed\nsimple comment\n\nanonymous block completed\nsecond simple comment\n</code></pre>\n\n<p>if you want to print out the results of variables, here's another example:</p>\n\n<pre><code>set serveroutput on format wrapped;\ndeclare\na_comment VARCHAR2(200) :='first comment';\nbegin\n DBMS_OUTPUT.put_line(a_comment);\nend;\n\n/\n\n-- do something\n\n\ndeclare\na_comment VARCHAR2(200) :='comment';\nbegin\n DBMS_OUTPUT.put_line(a_comment || 2);\nend;\n</code></pre>\n\n<p>your output should be:</p>\n\n<pre><code>anonymous block completed\nfirst comment\n\nanonymous block completed\ncomment2\n</code></pre>\n"
},
{
"answer_id": 4084876,
"author": "H77",
"author_id": 489884,
"author_profile": "https://Stackoverflow.com/users/489884",
"pm_score": 6,
"selected": false,
"text": "<pre><code>PROMPT text to print\n</code></pre>\n\n<p><strong>Note:</strong> must use \n Run as Script (F5)\nnot\n Run Statement (Ctl + Enter)</p>\n"
},
{
"answer_id": 5170303,
"author": "Michael Erickson",
"author_id": 591312,
"author_profile": "https://Stackoverflow.com/users/591312",
"pm_score": 3,
"selected": false,
"text": "<p>For me, I could only get it to work with</p>\n\n<pre><code>set serveroutput on format word_wrapped;\n</code></pre>\n\n<p>The wraped and WRAPPED just threw errors: SQLPLUS command failed - not enough arguments</p>\n"
},
{
"answer_id": 27368885,
"author": "Frank Staheli",
"author_id": 3704314,
"author_profile": "https://Stackoverflow.com/users/3704314",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't want all of your SQL statements to be echoed, but you only want to see the easily identifiable results of your script, do it this way:</p>\n<blockquote>\n<p>set echo on</p>\n<p>REM MyFirstTable</p>\n<p>set echo off</p>\n<p>delete from MyFirstTable;</p>\n<p>set echo on</p>\n<p>REM MySecondTable</p>\n<p>set echo off</p>\n<p>delete from MySecondTable;</p>\n</blockquote>\n<p>The output from the above example will look something like this:</p>\n<blockquote>\n<p>-REM MyFirstTable</p>\n<p>13 rows deleted.</p>\n<p>-REM MySecondTable</p>\n<p>27 rows deleted.</p>\n</blockquote>\n"
},
{
"answer_id": 54714471,
"author": "ΩmegaMan",
"author_id": 285795,
"author_profile": "https://Stackoverflow.com/users/285795",
"pm_score": 4,
"selected": false,
"text": "<p>The main answer left out a step for new installs where one has to open up the dbms output window.</p>\n\n<p><a href=\"https://i.stack.imgur.com/SlsOg.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/SlsOg.png\" alt=\"enter image description here\"></a></p>\n\n<p>Then the script I used:</p>\n\n<pre><code>dbms_output.put_line('Start');\n</code></pre>\n\n<hr>\n\n<p>Another script:</p>\n\n<pre><code>set serveroutput on format wrapped;\nbegin\n DBMS_OUTPUT.put_line('jabberwocky');\nend;\n</code></pre>\n"
},
{
"answer_id": 61905399,
"author": "FrenkyB",
"author_id": 867703,
"author_profile": "https://Stackoverflow.com/users/867703",
"pm_score": 2,
"selected": false,
"text": "<p>If I ommit begin - end it is error. So for me this is working (nothing else needed):</p>\n\n<pre><code>set serveroutput on;\nbegin\nDBMS_OUTPUT.PUT_LINE('testing');\nend;\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22523/"
] |
I am using Oracle SQL (in SQLDeveloper, using the SQL Worksheet). I would like to print a statement before my select, such as
```
PRINT 'Querying Table1';
SELECT * from Table1;
```
What do I use to Print / show text output? It's not Print, because that gives me the error: Bind Variable `Table1` is NOT DECLARED. DBMS\_OUTPUT.PUT\_LINE is an unknown command. (Obviously, I'm an inexperienced SQLDeveloper and Oracle user. There must be some synonym for Print, but I'm having trouble finding help on it without knowing what it is.)
|

for simple comments:
```
set serveroutput on format wrapped;
begin
DBMS_OUTPUT.put_line('simple comment');
end;
/
-- do something
begin
DBMS_OUTPUT.put_line('second simple comment');
end;
/
```
you should get:
```
anonymous block completed
simple comment
anonymous block completed
second simple comment
```
if you want to print out the results of variables, here's another example:
```
set serveroutput on format wrapped;
declare
a_comment VARCHAR2(200) :='first comment';
begin
DBMS_OUTPUT.put_line(a_comment);
end;
/
-- do something
declare
a_comment VARCHAR2(200) :='comment';
begin
DBMS_OUTPUT.put_line(a_comment || 2);
end;
```
your output should be:
```
anonymous block completed
first comment
anonymous block completed
comment2
```
|
193,119 |
<p>I need to have my iPhone Objective-C code catch Javascript errors in a UIWebView. That includes uncaught exceptions, syntax errors when loading files, undefined variable references, etc.</p>
<p>This is for a development environment, so it doesn't need to be SDK-kosher. In fact, it only really needs to work on the simulator.</p>
<p>I've already found used some of the hidden WebKit tricks to e.g. expose Obj-C objects to JS and to intercept alert popups, but this one is still eluding me.</p>
<p>[NOTE: after posting this I did find one way using a debugging delegate. Is there a way with lower overhead, using the error console / web inspector?]</p>
|
[
{
"answer_id": 193212,
"author": "kdbdallas",
"author_id": 26728,
"author_profile": "https://Stackoverflow.com/users/26728",
"pm_score": 0,
"selected": false,
"text": "<p>I have done this in firmware 1.x but not 2.x.\nHere is the code I used in 1.x, it should at least help you on your way.</p>\n\n<pre><code>// Dismiss Javascript alerts and telephone confirms\n/*- (void)alertSheet:(UIAlertSheet*)sheet buttonClicked:(int)button\n{\n if (button == 1)\n {\n [sheet setContext: nil];\n }\n\n [sheet dismiss];\n}*/\n\n// Javascript errors and logs\n- (void) webView: (WebView*)webView addMessageToConsole: (NSDictionary*)dictionary\n{\n NSLog(@\"Javascript log: %@\", dictionary);\n}\n\n// Javascript alerts\n- (void) webView: (WebView*)webView runJavaScriptAlertPanelWithMessage: (NSString*) message initiatedByFrame: (WebFrame*) frame\n{\n NSLog(@\"Javascript Alert: %@\", message);\n\n UIAlertSheet *alertSheet = [[UIAlertSheet alloc] init];\n [alertSheet setTitle: @\"Javascript Alert\"];\n [alertSheet addButtonWithTitle: @\"OK\"];\n [alertSheet setBodyText:message];\n [alertSheet setDelegate: self];\n [alertSheet setContext: self];\n [alertSheet popupAlertAnimated:YES];\n}\n</code></pre>\n"
},
{
"answer_id": 193282,
"author": "Robert Sanders",
"author_id": 16952,
"author_profile": "https://Stackoverflow.com/users/16952",
"pm_score": 5,
"selected": false,
"text": "<p>I have now found one way using the script debugger hooks in WebView (note, NOT UIWebView). I first had to subclass UIWebView and add a method like this:</p>\n\n<pre><code>- (void)webView:(id)webView windowScriptObjectAvailable:(id)newWindowScriptObject {\n // save these goodies\n windowScriptObject = newWindowScriptObject;\n privateWebView = webView;\n\n if (scriptDebuggingEnabled) {\n [webView setScriptDebugDelegate:[[YourScriptDebugDelegate alloc] init]];\n }\n}\n</code></pre>\n\n<p>Next you should create a YourScriptDebugDelegate class that contains methods like these:</p>\n\n<pre><code>// in YourScriptDebugDelegate\n\n- (void)webView:(WebView *)webView didParseSource:(NSString *)source\n baseLineNumber:(unsigned)lineNumber\n fromURL:(NSURL *)url\n sourceId:(int)sid\n forWebFrame:(WebFrame *)webFrame\n{\n NSLog(@\"NSDD: called didParseSource: sid=%d, url=%@\", sid, url);\n}\n\n// some source failed to parse\n- (void)webView:(WebView *)webView failedToParseSource:(NSString *)source\n baseLineNumber:(unsigned)lineNumber\n fromURL:(NSURL *)url\n withError:(NSError *)error\n forWebFrame:(WebFrame *)webFrame\n{\n NSLog(@\"NSDD: called failedToParseSource: url=%@ line=%d error=%@\\nsource=%@\", url, lineNumber, error, source);\n}\n\n- (void)webView:(WebView *)webView exceptionWasRaised:(WebScriptCallFrame *)frame\n sourceId:(int)sid\n line:(int)lineno\n forWebFrame:(WebFrame *)webFrame\n{\n NSLog(@\"NSDD: exception: sid=%d line=%d function=%@, caller=%@, exception=%@\", \n sid, lineno, [frame functionName], [frame caller], [frame exception]);\n}\n</code></pre>\n\n<p>There is probably a large runtime impact for this, as the debug delegate can also supply methods to be called for entering and exiting a stack frame, and for executing each line of code.</p>\n\n<p>See <a href=\"http://www.koders.com/noncode/fid7DE7ECEB052C3531743728D41A233A951C79E0AE.aspx\" rel=\"noreferrer\">http://www.koders.com/noncode/fid7DE7ECEB052C3531743728D41A233A951C79E0AE.aspx</a> for the Objective-C++ definition of WebScriptDebugDelegate.</p>\n\n<p>Those other methods:</p>\n\n<pre><code>// just entered a stack frame (i.e. called a function, or started global scope)\n- (void)webView:(WebView *)webView didEnterCallFrame:(WebScriptCallFrame *)frame\n sourceId:(int)sid\n line:(int)lineno\n forWebFrame:(WebFrame *)webFrame;\n\n// about to execute some code\n- (void)webView:(WebView *)webView willExecuteStatement:(WebScriptCallFrame *)frame\n sourceId:(int)sid\n line:(int)lineno\n forWebFrame:(WebFrame *)webFrame;\n\n// about to leave a stack frame (i.e. return from a function)\n- (void)webView:(WebView *)webView willLeaveCallFrame:(WebScriptCallFrame *)frame\n sourceId:(int)sid\n line:(int)lineno\n forWebFrame:(WebFrame *)webFrame;\n</code></pre>\n\n<p>Note that this is all hidden away in a private framework, so don't try to put this in code you submit to the App Store, and be prepared for some hackery to get it to work.</p>\n"
},
{
"answer_id": 774573,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I have created an SDK kosher error reporter that includes:</p>\n\n<ol>\n<li>The error message</li>\n<li>The name of the file the error happens in</li>\n<li>The line number the error happens on</li>\n<li>The JavaScript callstack including parameters passed</li>\n</ol>\n\n<p>It is part of the QuickConnectiPhone framework available from <a href=\"http://sourceforge.net/projects/quickconnect/\" rel=\"nofollow noreferrer\">the sourceForge project</a></p>\n\n<p>There is even an example application that shows how to send an error message to the Xcode terminal.</p>\n\n<p>All you need to do is to surround your JavaScript code, including function definitions, etc. with try catch. It should look like this.</p>\n\n<pre><code>try{\n//put your code here\n}\ncatch(err){\n logError(err);\n}\n</code></pre>\n\n<p>It doesn't work really well with compilation errors but works with all others. Even anonymous functions.</p>\n\n<p>The development <a href=\"http://tetontech.wordpress.com/\" rel=\"nofollow noreferrer\">blog is here</a>\nis here and includes links to the wiki, sourceForge, the google group, and twitter. Maybe this would help you out.</p>\n"
},
{
"answer_id": 4108206,
"author": "Krešimir Prcela",
"author_id": 475978,
"author_profile": "https://Stackoverflow.com/users/475978",
"pm_score": 4,
"selected": false,
"text": "<p>I used the great solution proposed from Robert Sanders: <a href=\"https://stackoverflow.com/questions/193119/how-can-my-iphone-objective-c-code-get-notified-of-javascript-errors-in-a-uiwebvi/193282#193282\">How can my iPhone Objective-C code get notified of Javascript errors in a UIWebView?</a></p>\n\n<p>That hook for webkit works fine also on <strong>iPhone</strong>. Instead of standard UIWebView I allocated derived MyUIWebView. I needed also to define hidden classes inside MyWebScriptObjectDelegate.h:</p>\n\n<p><code>@class WebView;</code><br>\n<code>@class WebFrame;</code><br>\n<code>@class WebScriptCallFrame;</code></p>\n\n<p>Within the ios sdk 4.1 the function:</p>\n\n<pre><code>- (void)webView:(id)webView windowScriptObjectAvailable:(id)newWindowScriptObject \n</code></pre>\n\n<p>is <strong>deprecated</strong> and instead of it I used the function: </p>\n\n<pre><code>- (void)webView:(id)sender didClearWindowObject:(id)windowObject forFrame:(WebFrame*)frame\n</code></pre>\n\n<p>Also, I get some annoying warnings like \"NSObject may not respond -windowScriptObject\" because the class interface is hidden. I ignore them and it works nice.</p>\n"
},
{
"answer_id": 7694244,
"author": "psy",
"author_id": 195090,
"author_profile": "https://Stackoverflow.com/users/195090",
"pm_score": 3,
"selected": false,
"text": "<p>Straight Forward Way: Put this code on top of your controller/view that is using the UIWebView</p>\n\n<pre><code>#ifdef DEBUG\n@interface DebugWebDelegate : NSObject\n@end\n@implementation DebugWebDelegate\n@class WebView;\n@class WebScriptCallFrame;\n@class WebFrame;\n- (void)webView:(WebView *)webView exceptionWasRaised:(WebScriptCallFrame *)frame\n sourceId:(int)sid\n line:(int)lineno\n forWebFrame:(WebFrame *)webFrame\n{\n NSLog(@\"NSDD: exception: sid=%d line=%d function=%@, caller=%@, exception=%@\", \n sid, lineno, [frame functionName], [frame caller], [frame exception]);\n}\n@end\n@interface DebugWebView : UIWebView\nid windowScriptObject;\nid privateWebView;\n@end\n@implementation DebugWebView\n- (void)webView:(id)sender didClearWindowObject:(id)windowObject forFrame:(WebFrame*)frame\n{\n [sender setScriptDebugDelegate:[[DebugWebDelegate alloc] init]];\n}\n@end\n#endif\n</code></pre>\n\n<p>And then instantiate it like this:</p>\n\n<pre><code>#ifdef DEBUG\n myWebview = [[DebugWebView alloc] initWithFrame:frame];\n#else\n myWebview = [[UIWebView alloc] initWithFrame:frame];\n#endif\n</code></pre>\n\n<p>Using #ifdef DEBUG ensures that it doesn't go in the release build, but I would also recommend commenting it out when you're not using it since it has a performance impact. Credit goes to Robert Sanders and Prcela for the original code</p>\n\n<p>Also if using ARC you may need to add \"-fno-objc-arc\" to prevent some build errors.</p>\n"
},
{
"answer_id": 11496729,
"author": "Pablo",
"author_id": 1490862,
"author_profile": "https://Stackoverflow.com/users/1490862",
"pm_score": 4,
"selected": false,
"text": "<p>I created a nice little drop-in category that you can add to your project...\nIt is based on Robert Sanders solution. Kudos.</p>\n\n<p>You can dowload it here:</p>\n\n<p><a href=\"https://github.com/PabloGS/UIWebView-Debug\" rel=\"noreferrer\">UIWebView+Debug</a></p>\n\n<p>This should make it a lot easier to debug you UIWebView :)</p>\n"
},
{
"answer_id": 13413850,
"author": "Oleg",
"author_id": 263347,
"author_profile": "https://Stackoverflow.com/users/263347",
"pm_score": -1,
"selected": false,
"text": "<p>A simpler solution for some cases might be to just add <a href=\"https://getfirebug.com/firebuglite\" rel=\"nofollow\">Firebug Lite</a> to the Web page.</p>\n"
},
{
"answer_id": 15484629,
"author": "bobc",
"author_id": 468180,
"author_profile": "https://Stackoverflow.com/users/468180",
"pm_score": 3,
"selected": false,
"text": "<p>One way that works during development if you have Safari v 6+ (I'm uncertain what iOS version you need) is to use the Safari development tools and hook into the UIWebView through it. </p>\n\n<ol>\n<li>In Safari: Enable the Develop Menu (Preferences > Advanced > Show Develop menu in menu bar)</li>\n<li>Plug your phone into the computer via the cable. </li>\n<li>List item</li>\n<li>Load up the app (either through xcode or just launch it) and go to the screen you want to debug.</li>\n<li>Back in Safari, open the Develop menu, look for the name of your device in that menu (mine is called iPhone 5), should be right under User Agent.</li>\n<li>Select it and you should see a drop down of the web views currently visible in your app.</li>\n<li>If you have more than one webview on the screen you can try to tell them apart by rolling over the name of the app in the develop menu. The corresponding UIWebView will turn blue.</li>\n<li>Select the name of the app, the develop window opens and you can inspect the console. You can even issue JS commands through it. </li>\n</ol>\n"
},
{
"answer_id": 28664004,
"author": "Yoav Zibin",
"author_id": 2304593,
"author_profile": "https://Stackoverflow.com/users/2304593",
"pm_score": 0,
"selected": false,
"text": "<p>See exception handling in iOS7:\n<a href=\"http://www.bignerdranch.com/blog/javascriptcore-example/\" rel=\"nofollow\">http://www.bignerdranch.com/blog/javascriptcore-example/</a></p>\n\n<pre><code>[context setExceptionHandler:^(JSContext *context, JSValue *value) {\n NSLog(@\"%@\", value);\n}];\n</code></pre>\n"
},
{
"answer_id": 43383129,
"author": "Patrick",
"author_id": 689568,
"author_profile": "https://Stackoverflow.com/users/689568",
"pm_score": 0,
"selected": false,
"text": "<p>First setup <a href=\"https://github.com/marcuswestin/WebViewJavascriptBridge\" rel=\"nofollow noreferrer\">WebViewJavascriptBridge</a> , \nthen override console.error function.</p>\n\n<p>In javascript</p>\n\n<pre><code> window.originConsoleError = console.error;\n console.error = (msg) => {\n window.originConsoleError(msg);\n bridge.callHandler(\"sendConsoleLogToNative\", {\n action:action,\n message:message\n }, null)\n };\n</code></pre>\n\n<p>In Objective-C</p>\n\n<pre><code>[self.bridge registerHandler:@\"sendConsoleLogToNative\" handler:^(id data, WVJBResponseCallback responseCallback) {\n NSString *action = data[@\"action\"];\n NSString *msg = data[@\"message\"];\n if (isStringValid(action)){\n if ([@\"console.error\" isEqualToString:action]){\n NSLog(@\"JS error :%@\",msg);\n }\n }\n}];\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16952/"
] |
I need to have my iPhone Objective-C code catch Javascript errors in a UIWebView. That includes uncaught exceptions, syntax errors when loading files, undefined variable references, etc.
This is for a development environment, so it doesn't need to be SDK-kosher. In fact, it only really needs to work on the simulator.
I've already found used some of the hidden WebKit tricks to e.g. expose Obj-C objects to JS and to intercept alert popups, but this one is still eluding me.
[NOTE: after posting this I did find one way using a debugging delegate. Is there a way with lower overhead, using the error console / web inspector?]
|
I have now found one way using the script debugger hooks in WebView (note, NOT UIWebView). I first had to subclass UIWebView and add a method like this:
```
- (void)webView:(id)webView windowScriptObjectAvailable:(id)newWindowScriptObject {
// save these goodies
windowScriptObject = newWindowScriptObject;
privateWebView = webView;
if (scriptDebuggingEnabled) {
[webView setScriptDebugDelegate:[[YourScriptDebugDelegate alloc] init]];
}
}
```
Next you should create a YourScriptDebugDelegate class that contains methods like these:
```
// in YourScriptDebugDelegate
- (void)webView:(WebView *)webView didParseSource:(NSString *)source
baseLineNumber:(unsigned)lineNumber
fromURL:(NSURL *)url
sourceId:(int)sid
forWebFrame:(WebFrame *)webFrame
{
NSLog(@"NSDD: called didParseSource: sid=%d, url=%@", sid, url);
}
// some source failed to parse
- (void)webView:(WebView *)webView failedToParseSource:(NSString *)source
baseLineNumber:(unsigned)lineNumber
fromURL:(NSURL *)url
withError:(NSError *)error
forWebFrame:(WebFrame *)webFrame
{
NSLog(@"NSDD: called failedToParseSource: url=%@ line=%d error=%@\nsource=%@", url, lineNumber, error, source);
}
- (void)webView:(WebView *)webView exceptionWasRaised:(WebScriptCallFrame *)frame
sourceId:(int)sid
line:(int)lineno
forWebFrame:(WebFrame *)webFrame
{
NSLog(@"NSDD: exception: sid=%d line=%d function=%@, caller=%@, exception=%@",
sid, lineno, [frame functionName], [frame caller], [frame exception]);
}
```
There is probably a large runtime impact for this, as the debug delegate can also supply methods to be called for entering and exiting a stack frame, and for executing each line of code.
See <http://www.koders.com/noncode/fid7DE7ECEB052C3531743728D41A233A951C79E0AE.aspx> for the Objective-C++ definition of WebScriptDebugDelegate.
Those other methods:
```
// just entered a stack frame (i.e. called a function, or started global scope)
- (void)webView:(WebView *)webView didEnterCallFrame:(WebScriptCallFrame *)frame
sourceId:(int)sid
line:(int)lineno
forWebFrame:(WebFrame *)webFrame;
// about to execute some code
- (void)webView:(WebView *)webView willExecuteStatement:(WebScriptCallFrame *)frame
sourceId:(int)sid
line:(int)lineno
forWebFrame:(WebFrame *)webFrame;
// about to leave a stack frame (i.e. return from a function)
- (void)webView:(WebView *)webView willLeaveCallFrame:(WebScriptCallFrame *)frame
sourceId:(int)sid
line:(int)lineno
forWebFrame:(WebFrame *)webFrame;
```
Note that this is all hidden away in a private framework, so don't try to put this in code you submit to the App Store, and be prepared for some hackery to get it to work.
|
193,124 |
<p>I have an ASPX page that creates an XMLDocument object from SQL data and then transforms it into another XML document (RSS feed) using an XSLT file with XPathNavigator and XslCompiledTransform. Occasionally the data will contain smart quotes (\u2019) which results in an error (Unable to translate Unicode character \u2019 at index 947 to specified code page). I'm not sure how all the encoding settings work, but is there a way to prevent this without having to check for these types of characters in all the data as I'm creating the XML attributes? </p>
<p>My XSLT file looks like this...</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="iso-8859-1"/>
</code></pre>
<p>I've tried changing the xsl:output encoding to utf-8 and utf-16 but still get the same problem. Any ideas? </p>
<p>Here's my code if that helps...</p>
<pre><code>XmlDocument xdoc = new XmlDocument();
XmlNode xnode = requests.XMLNode(xdoc, imageType, Request, promotionPageId, eventPageId);
xdoc.AppendChild(xnode);
Response.Clear();
Response.ContentType = "text/xml";
Response.AddHeader("Content-Type", "text/xml");
if (xsltFile != string.Empty)
{
XPathNavigator xnav = xdoc.CreateNavigator();
XslCompiledTransform xslTransform = new XslCompiledTransform();
xslTransform.Load(Server.MapPath(string.Format("~/xslt/{0}.xslt", xsltFile)));
xslTransform.OutputSettings.Encoding.
xslTransform.Transform(xnav, null, Response.OutputStream);
}
else
{
xdoc.Save(Response.OutputStream);
}
Response.End();
</code></pre>
|
[
{
"answer_id": 193886,
"author": "AmbroseChapel",
"author_id": 242241,
"author_profile": "https://Stackoverflow.com/users/242241",
"pm_score": 0,
"selected": false,
"text": "<p>What's the document encoding of the input XML your XSL is working on? You should be able to set that, then the XSL will know what to expect. </p>\n"
},
{
"answer_id": 194525,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 1,
"selected": false,
"text": "<p>Your transform is working fine. The problem is that the transform is emitting a character that isn't supported by the content encoding of the output stream. Set the <code>ContentEncoding</code> on the <code>HttpResponse</code> to <code>Encoding.UTF16</code> and this problem should go away.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have an ASPX page that creates an XMLDocument object from SQL data and then transforms it into another XML document (RSS feed) using an XSLT file with XPathNavigator and XslCompiledTransform. Occasionally the data will contain smart quotes (\u2019) which results in an error (Unable to translate Unicode character \u2019 at index 947 to specified code page). I'm not sure how all the encoding settings work, but is there a way to prevent this without having to check for these types of characters in all the data as I'm creating the XML attributes?
My XSLT file looks like this...
```
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="iso-8859-1"/>
```
I've tried changing the xsl:output encoding to utf-8 and utf-16 but still get the same problem. Any ideas?
Here's my code if that helps...
```
XmlDocument xdoc = new XmlDocument();
XmlNode xnode = requests.XMLNode(xdoc, imageType, Request, promotionPageId, eventPageId);
xdoc.AppendChild(xnode);
Response.Clear();
Response.ContentType = "text/xml";
Response.AddHeader("Content-Type", "text/xml");
if (xsltFile != string.Empty)
{
XPathNavigator xnav = xdoc.CreateNavigator();
XslCompiledTransform xslTransform = new XslCompiledTransform();
xslTransform.Load(Server.MapPath(string.Format("~/xslt/{0}.xslt", xsltFile)));
xslTransform.OutputSettings.Encoding.
xslTransform.Transform(xnav, null, Response.OutputStream);
}
else
{
xdoc.Save(Response.OutputStream);
}
Response.End();
```
|
Your transform is working fine. The problem is that the transform is emitting a character that isn't supported by the content encoding of the output stream. Set the `ContentEncoding` on the `HttpResponse` to `Encoding.UTF16` and this problem should go away.
|
193,130 |
<p>I'd like to have a custom object attached to the application so I can preserve state in it between different html pages in adobe air. Is this possible?</p>
<hr>
<p>I was asking for a fullblown solution to store a custom js object in memory and persist it between pages loaded from the application sandbox, but this cannot be done unless I use iframes which is not very pleasant, since I have to add a lot of stuff to the bridge. Anoter way may be to do partial rendering of the page filled with html read from files, but this exposes a lot of unpleasant bugs + you cant write script tags in the dom dynamically. It's a crippled platform.</p>
|
[
{
"answer_id": 193909,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 0,
"selected": false,
"text": "<p>What sort of object ?-)</p>\n\n<p>If it only holds values that are meaningful in a string, you could store it as a cookie or perhaps in a serverside session ...</p>\n"
},
{
"answer_id": 194276,
"author": "Dimitry",
"author_id": 27073,
"author_profile": "https://Stackoverflow.com/users/27073",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps you could try attaching the object on the user's machine. There is a tutorial online that seems like it could help:</p>\n\n<p><a href=\"http://corlan.org/2008/09/02/storing-data-locally-in-air/\" rel=\"nofollow noreferrer\">http://corlan.org/2008/09/02/storing-data-locally-in-air/</a></p>\n\n<p>Example from the site:</p>\n\n<pre><code>//write an Object to a file\nprivate function writeObject():void {\n var object:Object = new Object();//create an object to store\n object.value = asObject.text; //set the text field value to the value property\n //create a file under the application storage folder\n var file:File = File.applicationStorageDirectory.resolvePath(\"myobject.file\");\n if (file.exists)\n file.deleteFile();\n var fileStream:FileStream = new FileStream(); //create a file stream\n fileStream.open(file, FileMode.WRITE);// and open the file for write\n fileStream.writeObject(object);//write the object to the file\n fileStream.close();\n}\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7883/"
] |
I'd like to have a custom object attached to the application so I can preserve state in it between different html pages in adobe air. Is this possible?
---
I was asking for a fullblown solution to store a custom js object in memory and persist it between pages loaded from the application sandbox, but this cannot be done unless I use iframes which is not very pleasant, since I have to add a lot of stuff to the bridge. Anoter way may be to do partial rendering of the page filled with html read from files, but this exposes a lot of unpleasant bugs + you cant write script tags in the dom dynamically. It's a crippled platform.
|
Perhaps you could try attaching the object on the user's machine. There is a tutorial online that seems like it could help:
<http://corlan.org/2008/09/02/storing-data-locally-in-air/>
Example from the site:
```
//write an Object to a file
private function writeObject():void {
var object:Object = new Object();//create an object to store
object.value = asObject.text; //set the text field value to the value property
//create a file under the application storage folder
var file:File = File.applicationStorageDirectory.resolvePath("myobject.file");
if (file.exists)
file.deleteFile();
var fileStream:FileStream = new FileStream(); //create a file stream
fileStream.open(file, FileMode.WRITE);// and open the file for write
fileStream.writeObject(object);//write the object to the file
fileStream.close();
}
```
|
193,143 |
<p>I'm using MSTEST inside Visual Studio 2008. How can I have each unit test method in a certain test class act as if it were the first test to run so that all global state is reset before running each test? I do not want to explicitly clean up the world using TestInitialize, ClassInitialize, AssemblyInitialize, etc. For example:</p>
<pre><code>[TestClass]
public class MyClassTests
{
[TestMethod]
public void Test1()
{
// The "Instance" property creates a new instance of "SomeSingleton"
// if it hasn't been created before.
var i1 = SomeSingleton.Instance;
...
}
[TestMethod]
public void Test2()
{
// When I select "Test1" and "Test2" to run, I'd like Test2
// to have a new AppDomain feel so that the static variable inside
// of "SomeSingleton" is reset (it was previously set in Test1) on
// the call to ".Instance"
var i2 = SomeSingleton.Instance;
// some code
}
</code></pre>
<p>Although a <a href="https://stackoverflow.com/questions/154180/how-does-nunit-and-mstest-handle-tests-that-change-staticshared-variables">similar question</a> appeared on this topic, it only clarified that tests do not run in parallel. I realize that tests run serially, but there doesn't seem to be a way to explicitly force a new AppDomain for each method (or something equivalent to clear all state).</p>
<p>Ideally, I'd like to specify this behavior for only a small subset of my unit tests so that I don't have to pay the penalty of a new AppDomain creation for tests that don't care about global state (the vast majority of my tests).</p>
|
[
{
"answer_id": 197910,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>We had a similar issue arise with our MSTests. We handled it by calling a function at the beginning and end of the specific tests that needed it. </p>\n\n<p>We are storing a test expiration date in our app configuration. Three tests needed this date to fall into a specific range to determine the appropriate values. The way our application is set up, the configuration values would only be reset if there was not a value assigned in session. So, we created two new private static functions - one to explicitly set the configuration value to a specified date and one to clear that date from session after the test runs. In our three tests, we called these two functions. When the next test runs, the application sees an empty value for the date and refetches it from the configuration file.</p>\n\n<p>I'm not sure if that's helpful, but that was how we worked around our similar issue.</p>\n"
},
{
"answer_id": 197943,
"author": "Alex",
"author_id": 26564,
"author_profile": "https://Stackoverflow.com/users/26564",
"pm_score": 2,
"selected": false,
"text": "<p>I think you are looking for the TestIntialize attribute and the TestCleanUp attribute. Here is an MSDN blog showing the execution order<a href=\"http://blogs.msdn.com/nnaderi/archive/2007/02/17/explaining-execution-order.aspx\" rel=\"nofollow noreferrer\">link text</a></p>\n"
},
{
"answer_id": 198334,
"author": "Jeff Moser",
"author_id": 1869,
"author_profile": "https://Stackoverflow.com/users/1869",
"pm_score": 4,
"selected": true,
"text": "<p>In the end, I wrote a helper that used <a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain.createdomain.aspx\" rel=\"nofollow noreferrer\">AppDomain.CreateDomain</a> and then used reflection to call the unit test under a different AppDomain. It provides the isolation I needed.</p>\n\n<p><a href=\"http://social.msdn.microsoft.com/Forums/en-US/vststest/thread/130c923f-15cb-4a87-8d3b-0f9779080cfa/\" rel=\"nofollow noreferrer\">This post</a> on MSDN's forums shows how to handle the situation if you only have a few statics that need to be reset. <a href=\"http://social.msdn.microsoft.com/Forums/en-US/vststest/thread/130c923f-15cb-4a87-8d3b-0f9779080cfa/\" rel=\"nofollow noreferrer\">It</a> does mention some options (e.g. using Reflection and <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privatetype.aspx\" rel=\"nofollow noreferrer\">PrivateType</a> ).</p>\n\n<p>I continue to welcome any further ideas, especially if I'm missing something obvious about MSTEST.</p>\n"
},
{
"answer_id": 198562,
"author": "Watson",
"author_id": 25807,
"author_profile": "https://Stackoverflow.com/users/25807",
"pm_score": 3,
"selected": false,
"text": "<p>Add a helper in your tests that uses reflection to delete the singleton instance (you can add a reset method to the singleton as well, but I would be concerned about its use). Something like:</p>\n\n<pre><code>public static class SingletonHelper {\n public static void CleanDALFactory() \n {\n typeof(DalFactory)\n .GetField(\"_instance\",BindingFlags.Static | BindingFlags.NonPublic)\n .SetValue(null, null);\n }\n}\n</code></pre>\n\n<p>Call this in your TestInitialize method. [ I know this is \"cleaning up the world\", but you only have to write the method once in a helper per singleton, its very trivial and gives you explicit control ]</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1869/"
] |
I'm using MSTEST inside Visual Studio 2008. How can I have each unit test method in a certain test class act as if it were the first test to run so that all global state is reset before running each test? I do not want to explicitly clean up the world using TestInitialize, ClassInitialize, AssemblyInitialize, etc. For example:
```
[TestClass]
public class MyClassTests
{
[TestMethod]
public void Test1()
{
// The "Instance" property creates a new instance of "SomeSingleton"
// if it hasn't been created before.
var i1 = SomeSingleton.Instance;
...
}
[TestMethod]
public void Test2()
{
// When I select "Test1" and "Test2" to run, I'd like Test2
// to have a new AppDomain feel so that the static variable inside
// of "SomeSingleton" is reset (it was previously set in Test1) on
// the call to ".Instance"
var i2 = SomeSingleton.Instance;
// some code
}
```
Although a [similar question](https://stackoverflow.com/questions/154180/how-does-nunit-and-mstest-handle-tests-that-change-staticshared-variables) appeared on this topic, it only clarified that tests do not run in parallel. I realize that tests run serially, but there doesn't seem to be a way to explicitly force a new AppDomain for each method (or something equivalent to clear all state).
Ideally, I'd like to specify this behavior for only a small subset of my unit tests so that I don't have to pay the penalty of a new AppDomain creation for tests that don't care about global state (the vast majority of my tests).
|
In the end, I wrote a helper that used [AppDomain.CreateDomain](http://msdn.microsoft.com/en-us/library/system.appdomain.createdomain.aspx) and then used reflection to call the unit test under a different AppDomain. It provides the isolation I needed.
[This post](http://social.msdn.microsoft.com/Forums/en-US/vststest/thread/130c923f-15cb-4a87-8d3b-0f9779080cfa/) on MSDN's forums shows how to handle the situation if you only have a few statics that need to be reset. [It](http://social.msdn.microsoft.com/Forums/en-US/vststest/thread/130c923f-15cb-4a87-8d3b-0f9779080cfa/) does mention some options (e.g. using Reflection and [PrivateType](http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privatetype.aspx) ).
I continue to welcome any further ideas, especially if I'm missing something obvious about MSTEST.
|
193,151 |
<p>So the question is how to distribute/offload the media files from Wordpress posts across multiple domains. </p>
<p>The reasoning being to overcome this limitation:
"Most browser will only make 2 simultaneous requests to a server, so if you page requires 16 files they will be requested 2 at a time."</p>
<p>In relation to: <a href="http://codex.wordpress.org/WordPress_Optimization/Offloading" rel="nofollow noreferrer">http://codex.wordpress.org/WordPress_Optimization/Offloading</a></p>
<p>To further clarify:<br>
There are two plug ins for "offloading" that already do this. They are the SteadyOffloading Plugin and the Amazon S3 plugin.<br>
So is there a generic solution that anyone has come across. Where it will allow you to change the base URL of the media, it doesn't necessary have to upload that media to an external service/server.</p>
<p>Thanks</p>
|
[
{
"answer_id": 193207,
"author": "Osama Al-Maadeed",
"author_id": 25544,
"author_profile": "https://Stackoverflow.com/users/25544",
"pm_score": 0,
"selected": false,
"text": "<p>The question is a bit ambiguous, I'm not sure but maybe if the domains are on the same server you could replace wp-content/uploads by a symlink.</p>\n"
},
{
"answer_id": 193447,
"author": "Jordan Ogren",
"author_id": 21888,
"author_profile": "https://Stackoverflow.com/users/21888",
"pm_score": 1,
"selected": false,
"text": "<p>You just need to edit the URL's to the various media files throughout your WordPress theme.</p>\n\n<p>For example, edit you \"header.php\" to change the css file to an alternate domain.</p>\n\n<p>Change This:</p>\n\n<pre><code>print(\"<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"<?php bloginfo('stylesheet_url'); ?>\" />\");\n</code></pre>\n\n<p>To something like this:</p>\n\n<pre><code>print(\"<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"http://www.NEW_DOMAIN.com/theme/stylesheet.css\" />\");\n</code></pre>\n\n<p>All the media could then be placed on this alternate server and would be referenced by the stylesheet.</p>\n\n<p>The same could be done for any pictures or other media. There are even several WP plugins for utilizing media services such as Flikr.com</p>\n\n<p>If you actually have several physical servers to utilize, you would install WordPress on the base web server \"www.DOMAIN.com\" server. Then all your images could all reside on an second server \"images.DOMAIN.com\". Next you could place your stylesheets and JavaScript files on a third sub-domain/server, \"scripts.DOMAIN.com\". Then your 1st. server would refer to the stylesheet on the 3rd server which would access all the media files on the 2nd server.</p>\n\n<p>If you owned all your own hardware, you could get really crazy and use some sort of script to mirror all the files between 2 servers and use a Hardware Load Balancer to split the web traffic and use Log shipping to mirror you database between multiple servers... But that is getting a bit ridiculous.</p>\n\n<p>Hope this helps.</p>\n\n<p>-Jordan</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
So the question is how to distribute/offload the media files from Wordpress posts across multiple domains.
The reasoning being to overcome this limitation:
"Most browser will only make 2 simultaneous requests to a server, so if you page requires 16 files they will be requested 2 at a time."
In relation to: <http://codex.wordpress.org/WordPress_Optimization/Offloading>
To further clarify:
There are two plug ins for "offloading" that already do this. They are the SteadyOffloading Plugin and the Amazon S3 plugin.
So is there a generic solution that anyone has come across. Where it will allow you to change the base URL of the media, it doesn't necessary have to upload that media to an external service/server.
Thanks
|
You just need to edit the URL's to the various media files throughout your WordPress theme.
For example, edit you "header.php" to change the css file to an alternate domain.
Change This:
```
print("<link rel="stylesheet" type="text/css" media="screen" href="<?php bloginfo('stylesheet_url'); ?>" />");
```
To something like this:
```
print("<link rel="stylesheet" type="text/css" media="screen" href="http://www.NEW_DOMAIN.com/theme/stylesheet.css" />");
```
All the media could then be placed on this alternate server and would be referenced by the stylesheet.
The same could be done for any pictures or other media. There are even several WP plugins for utilizing media services such as Flikr.com
If you actually have several physical servers to utilize, you would install WordPress on the base web server "www.DOMAIN.com" server. Then all your images could all reside on an second server "images.DOMAIN.com". Next you could place your stylesheets and JavaScript files on a third sub-domain/server, "scripts.DOMAIN.com". Then your 1st. server would refer to the stylesheet on the 3rd server which would access all the media files on the 2nd server.
If you owned all your own hardware, you could get really crazy and use some sort of script to mirror all the files between 2 servers and use a Hardware Load Balancer to split the web traffic and use Log shipping to mirror you database between multiple servers... But that is getting a bit ridiculous.
Hope this helps.
-Jordan
|
193,154 |
<p>I am getting the following error when I try to call a stored procedure that contains a SELECT Statement:</p>
<blockquote>
<p>The operation is not valid for the state of the transaction</p>
</blockquote>
<p>Here is the structure of my calls:</p>
<pre><code>public void MyAddUpdateMethod()
{
using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//do my first add update statement
//do my call to the select statement sp
bool DoesRecordExist = this.SelectStatementCall(id)
}
}
}
public bool SelectStatementCall(System.Guid id)
{
using(SQLServer Sql = new SQLServer(this.m_connstring)) //breaks on this line
{
//create parameters
//
}
}
</code></pre>
<p>Is the problem with me creating another connection to the same database within the transaction?</p>
|
[
{
"answer_id": 193167,
"author": "Wyatt",
"author_id": 26626,
"author_profile": "https://Stackoverflow.com/users/26626",
"pm_score": 3,
"selected": false,
"text": "<p>I've encountered this error when my Transaction is nested within another. Is it possible that the stored procedure declares its own transaction or that the calling function declares one?</p>\n"
},
{
"answer_id": 203394,
"author": "Michael Kniskern",
"author_id": 26327,
"author_profile": "https://Stackoverflow.com/users/26327",
"pm_score": 7,
"selected": true,
"text": "<p>After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:</p>\n\n<pre><code>public void MyAddUpdateMethod()\n{\n using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))\n {\n using(SQLServer Sql = new SQLServer(this.m_connstring))\n {\n //do my first add update statement \n }\n\n //removed the method call from the first sql server using statement\n bool DoesRecordExist = this.SelectStatementCall(id)\n }\n}\n\npublic bool SelectStatementCall(System.Guid id)\n{\n using(SQLServer Sql = new SQLServer(this.m_connstring))\n {\n //create parameters\n }\n}\n</code></pre>\n"
},
{
"answer_id": 4313273,
"author": "Sharique",
"author_id": 68238,
"author_profile": "https://Stackoverflow.com/users/68238",
"pm_score": 4,
"selected": false,
"text": "<p>I also come across same problem, I changed transaction timeout to 15 minutes and it works. \nI hope this helps.</p>\n\n<pre><code>TransactionOptions options = new TransactionOptions();\noptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;\noptions.Timeout = new TimeSpan(0, 15, 0);\nusing (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required,options))\n{\n sp1();\n sp2();\n ...\n\n}\n</code></pre>\n"
},
{
"answer_id": 9160763,
"author": "R. Schreurs",
"author_id": 456456,
"author_profile": "https://Stackoverflow.com/users/456456",
"pm_score": 4,
"selected": false,
"text": "<p>When I encountered this exception, there was an InnerException \"Transaction Timeout\". Since this was during a debug session, when I halted my code for some time inside the TransactionScope, I chose to ignore this issue.</p>\n\n<p>When this specific exception with a timeout appears in deployed code, I think that the following section in you .config file will help you out:</p>\n\n<pre><code><system.transactions> \n <machineSettings maxTimeout=\"00:05:00\" /> \n</system.transactions>\n</code></pre>\n"
},
{
"answer_id": 50176955,
"author": "Vishav Premlall",
"author_id": 2650359,
"author_profile": "https://Stackoverflow.com/users/2650359",
"pm_score": 2,
"selected": false,
"text": "<p>For me, this error came up when I was trying to rollback a transaction block after encountering an exception, inside another transaction block.</p>\n\n<p>All I had to do to fix it was to remove my inner transaction block.</p>\n\n<p>Things can get quite messy when using nested transactions, best to avoid this and just restructure your code.</p>\n"
},
{
"answer_id": 63486111,
"author": "J. Minjire",
"author_id": 343836,
"author_profile": "https://Stackoverflow.com/users/343836",
"pm_score": 3,
"selected": false,
"text": "<p>For any wanderer that comes across this in the future. If your application and database are on different machines and you are getting the above error especially when using TransactionScope, enable Network DTC access. Steps to do this are:</p>\n<ol>\n<li>Add firewall rules to allow your machines to talk to each other.</li>\n<li>Ensure the distributed transaction coordinator service is running</li>\n<li>Enable network dtc access. Run dcomcnfg. Go to Component sevices > My Computer > Distributed Transaction Coordinator > Local DTC. Right click properties.</li>\n<li>Enable network dtc access as shown.</li>\n</ol>\n<p><strong>Important</strong>: Do not edit/change the user account and password in the DTC Logon account field, leave it as is, you will end up re-installing windows if you do.</p>\n<p><a href=\"https://i.stack.imgur.com/2SaO0.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/2SaO0.png\" alt=\"DTC photo\" /></a></p>\n"
},
{
"answer_id": 67829049,
"author": "Angel Angeles",
"author_id": 13340588,
"author_profile": "https://Stackoverflow.com/users/13340588",
"pm_score": 2,
"selected": false,
"text": "<p>In my case, the solution was neither to increase the time of the "transactionscope" nor to increase the time of the "machineSettings" property of "system.transactions" of the machine.config file.</p>\n<p>In this case there was something strange because this error only happened when the volume of information was very high.</p>\n<p>So the problem was based on the fact that in the code inside the transaction there were many "foreach" that made updates for different tables (I had to solve this problem in a code developed by other personnel). If tests were performed with few records in the tables, the error was not displayed, but if the number of records was increased then the error was displayed.</p>\n<p>In the end the solution was to change from a single transaction to several separate ones in the different "foreach" that were within the transaction.</p>\n"
},
{
"answer_id": 68723124,
"author": "Cătălin Rădoi",
"author_id": 1131665,
"author_profile": "https://Stackoverflow.com/users/1131665",
"pm_score": 0,
"selected": false,
"text": "<p>You can't have two transactions open at the same time. What I do is that I specify <strong>transaction.Complete()</strong> before returning results that will be used by the 2nd transaction ;)</p>\n"
},
{
"answer_id": 69976002,
"author": "Louise",
"author_id": 2394276,
"author_profile": "https://Stackoverflow.com/users/2394276",
"pm_score": 0,
"selected": false,
"text": "<p>I updated some proprietary 3rd party libraries that handled part of the database process, and got this error on all calls to save. I had to change a value in the web.config transaction key section because (it turned out) the referenced transaction scope method had moved from one library to another.</p>\n<p>There was other errors previously connected with that key, but I got rid of them by commenting the key out (I know I should have been suspicious at that point, but I assumed it was now redundant as it wasn't in the shiny new library).</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26327/"
] |
I am getting the following error when I try to call a stored procedure that contains a SELECT Statement:
>
> The operation is not valid for the state of the transaction
>
>
>
Here is the structure of my calls:
```
public void MyAddUpdateMethod()
{
using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//do my first add update statement
//do my call to the select statement sp
bool DoesRecordExist = this.SelectStatementCall(id)
}
}
}
public bool SelectStatementCall(System.Guid id)
{
using(SQLServer Sql = new SQLServer(this.m_connstring)) //breaks on this line
{
//create parameters
//
}
}
```
Is the problem with me creating another connection to the same database within the transaction?
|
After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:
```
public void MyAddUpdateMethod()
{
using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//do my first add update statement
}
//removed the method call from the first sql server using statement
bool DoesRecordExist = this.SelectStatementCall(id)
}
}
public bool SelectStatementCall(System.Guid id)
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//create parameters
}
}
```
|
193,155 |
<p>SQL Server (2005/2008)</p>
<p>Each of the below statements have the same result. Does anyone know if one outperforms the other?</p>
<pre><code>insert into SOMETABLE
values ('FieldOneValue','FieldTwoValue',3,4.55,'10/10/2008 16:42:00.000')
insert into SOMETABLE
select 'FieldOneValue','FieldTwoValue',3,4.55,'10/10/2008 16:42:00.000'
insert into SOMETALBE
Select
Field1 = 'FieldOneValue',
Field2 = 'FieldTwoValue',
Field3 = 3,
Field4 = 4.55,
Field5 = '10/10/2008 16:42:00.000'
</code></pre>
<p>Assuming of course that the data types match the table appropriately...</p>
|
[
{
"answer_id": 193164,
"author": "Aaron Smith",
"author_id": 12969,
"author_profile": "https://Stackoverflow.com/users/12969",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like you're just mimicking</p>\n\n<pre><code>INSERT into SOMETABLE\n(\nSELECT * FROM SOMEOTHERTABLE\n)\n</code></pre>\n"
},
{
"answer_id": 193168,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 3,
"selected": false,
"text": "<p>i think, based on this question, you are to the point of <a href=\"http://en.wikipedia.org/wiki/Code_optimization#When_to_optimize\" rel=\"nofollow noreferrer\">premature optimization</a>. i'd stick to the standard insert () values () if you are just inserting 1 record and let the Sql Server team make it the most performant.</p>\n"
},
{
"answer_id": 193197,
"author": "Rob",
"author_id": 3542,
"author_profile": "https://Stackoverflow.com/users/3542",
"pm_score": 2,
"selected": false,
"text": "<p>I would suspect that if there were a performance difference, it would be in favour of the former, although I doubt there is one.</p>\n\n<p>Nevertheless, this is one of those cases where opting for the clearer version (i.e. with VALUES) provides a readability and maintainability benefit which outweighs the likely negligible performance impact. If you're specifying all the values, then stick to the usual convention, in case someone else reads the code, which at first glance might seem to be doing an INSERT...SELECT from another table, which is a misleading appearance.</p>\n"
},
{
"answer_id": 193202,
"author": "Miles",
"author_id": 21828,
"author_profile": "https://Stackoverflow.com/users/21828",
"pm_score": -1,
"selected": false,
"text": "<p><em>ignore this comment, its wrong. sorry about that :(</em></p>\n\n<p>I know you can't use INSERT VALUES() when you're entering more than one row.</p>\n\n<p>INSERT INTO Table\nSELECT 1, 2, 3, (SELECT 4 FROM Table2 WHERE columnA = columnB)</p>\n"
},
{
"answer_id": 193241,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 4,
"selected": true,
"text": "<p>I just tested this.</p>\n\n<p>5 million iterations of both approaches on two sets of hardware, one a server with 16GB RAM, one a notebook with 1GB.</p>\n\n<p>Result: They appear to be the same.</p>\n\n<p>The query plans for these are the same, and the performance differential is statistically insignificant.</p>\n"
},
{
"answer_id": 193501,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "<p>For SQL Server, just use this pattern</p>\n\n<p>INSERT INTO TableName (<em>fieldList</em>)\nSELECT (<em>valueList</em>/<em>columnList</em>)\n[<em>FROM and so on</em>]</p>\n\n<p>This is the only insert pattern you'll ever need. It does everything. Do specify the <em>fieldlist</em> to protect your statement from future table changes (where optional columns are added).</p>\n\n<p>There are some minor nuances to using INSERT INTO VALUES, which I don't remember because I don't have to.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7870/"
] |
SQL Server (2005/2008)
Each of the below statements have the same result. Does anyone know if one outperforms the other?
```
insert into SOMETABLE
values ('FieldOneValue','FieldTwoValue',3,4.55,'10/10/2008 16:42:00.000')
insert into SOMETABLE
select 'FieldOneValue','FieldTwoValue',3,4.55,'10/10/2008 16:42:00.000'
insert into SOMETALBE
Select
Field1 = 'FieldOneValue',
Field2 = 'FieldTwoValue',
Field3 = 3,
Field4 = 4.55,
Field5 = '10/10/2008 16:42:00.000'
```
Assuming of course that the data types match the table appropriately...
|
I just tested this.
5 million iterations of both approaches on two sets of hardware, one a server with 16GB RAM, one a notebook with 1GB.
Result: They appear to be the same.
The query plans for these are the same, and the performance differential is statistically insignificant.
|
193,185 |
<p>I've got a little problem that's slightly frustrating. Is it possible to set a default value when deserializing xml in C# (.NET 3.5)? Basically I'm trying to deserialize some xml that is not under my control and one element looks like this:</p>
<pre><code><assignee-id type="integer">38628</assignee-id>
</code></pre>
<p>it can also look like this:</p>
<pre><code><assignee-id type="integer" nil="true"></assignee-id>
</code></pre>
<p>Now, in my class I have the following property that should receive the data:</p>
<pre><code>[XmlElementAttribute("assignee-id")]
public int AssigneeId { get; set; }
</code></pre>
<p>This works fine for the first xml element example, but the second fails. I've tried changing the property type to be int? but this doesn't help. I'll need to serialize it back to that same xml format at some point too, but I'm trying to use the built in serialization support without having to resort to rolling my own. </p>
<p>Does anyone have experience with this kind of problem?</p>
|
[
{
"answer_id": 193195,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>XmlSerializer uses xsi:nil - so I expect you'd need to do custom IXmlSerializable serialization for this. Sorry.</p>\n"
},
{
"answer_id": 193210,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<p>You might want to take a look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.ondeserializedattribute.aspx\" rel=\"nofollow noreferrer\">OnDeserializedAttribute</a>,<a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.onserializingattribute.aspx\" rel=\"nofollow noreferrer\">OnSerializingAttribute</a>, <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.onserializedattribute.aspx\" rel=\"nofollow noreferrer\">OnSerializedAttribute</a>, and <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.ondeserializingattribute.aspx\" rel=\"nofollow noreferrer\">OnDeserializingAttribute</a> to add custom logic to the serialization process</p>\n"
},
{
"answer_id": 193874,
"author": "Timothy Walters",
"author_id": 14454,
"author_profile": "https://Stackoverflow.com/users/14454",
"pm_score": 3,
"selected": true,
"text": "<p>It looks like your source XML is using xsi:type and xsi:nil, but not prefixing them with a namespace.</p>\n\n<p>What you could do is process these with XSLT to turn this:</p>\n\n<pre><code><assignees>\n <assignee>\n <assignee-id type=\"integer\">123456</assignee-id>\n </assignee>\n <assignee>\n <assignee-id type=\"integer\" nil=\"true\"></assignee-id>\n </assignee>\n</assignees>\n</code></pre>\n\n<p>into this:</p>\n\n<pre><code><assignees xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <assignee>\n <assignee-id xsi:type=\"integer\">123456</assignee-id>\n </assignee>\n <assignee>\n <assignee-id xsi:type=\"integer\" xsi:nil=\"true\" />\n </assignee>\n</assignees>\n</code></pre>\n\n<p>This would then be handled correctly by the XmlSerializer without needing any custom code. The XSLT for this is rather trivial, and a fun exercise. Start with one of the many \"copy\" XSLT samples and simply add a template for the \"type\" and \"nil\" attributes to ouput a namespaced attribute.</p>\n\n<p>If you prefer you could load your XML document into memory and change the attributes but this is not a good idea as the XSLT engine is tuned for performance and can process quite large files without loading them entirely into memory.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15726/"
] |
I've got a little problem that's slightly frustrating. Is it possible to set a default value when deserializing xml in C# (.NET 3.5)? Basically I'm trying to deserialize some xml that is not under my control and one element looks like this:
```
<assignee-id type="integer">38628</assignee-id>
```
it can also look like this:
```
<assignee-id type="integer" nil="true"></assignee-id>
```
Now, in my class I have the following property that should receive the data:
```
[XmlElementAttribute("assignee-id")]
public int AssigneeId { get; set; }
```
This works fine for the first xml element example, but the second fails. I've tried changing the property type to be int? but this doesn't help. I'll need to serialize it back to that same xml format at some point too, but I'm trying to use the built in serialization support without having to resort to rolling my own.
Does anyone have experience with this kind of problem?
|
It looks like your source XML is using xsi:type and xsi:nil, but not prefixing them with a namespace.
What you could do is process these with XSLT to turn this:
```
<assignees>
<assignee>
<assignee-id type="integer">123456</assignee-id>
</assignee>
<assignee>
<assignee-id type="integer" nil="true"></assignee-id>
</assignee>
</assignees>
```
into this:
```
<assignees xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<assignee>
<assignee-id xsi:type="integer">123456</assignee-id>
</assignee>
<assignee>
<assignee-id xsi:type="integer" xsi:nil="true" />
</assignee>
</assignees>
```
This would then be handled correctly by the XmlSerializer without needing any custom code. The XSLT for this is rather trivial, and a fun exercise. Start with one of the many "copy" XSLT samples and simply add a template for the "type" and "nil" attributes to ouput a namespaced attribute.
If you prefer you could load your XML document into memory and change the attributes but this is not a good idea as the XSLT engine is tuned for performance and can process quite large files without loading them entirely into memory.
|
193,215 |
<p>I'm sorting out a series of SQL scripts for my company written in Oracle PL/SQL. I came across an essential script with a strangely placed slash near the bottom. It is checked into CVS this way. Is this a pure syntax error or does it have some function I'm not aware of. The slightly obfuscated script:</p>
<pre><code>set serveroutput on size 2000;
--PL/SQL block to link ISSN in serial base on a company's ISSN text file
declare
cursor ItemCursor is
select issn is2 from web.obfuscated1 where issn is not null
union
select eissn is2 from web.obfuscated1 where eissn is not null;
cursor ItemCursor1(aIS varchar2) is
select obfuscated1_uid from web.obfuscated1 where group_num is null and issn in (
select distinct issn from web.obfuscated1 where issn = aIS or eissn = aIS
union
select distinct eissn from web.obfuscated1 where issn = aIS or eissn = aIS
)
union
select obfuscated1_uid from web.obfuscated1 where eissn in (
select distinct issn from web.obfuscated1 where issn = aIS or eissn = aIS
union
select distinct eissn from web.obfuscated1 where issn = aIS or eissn = aIS
);
cursor ItemCursor2(aIS9 varchar2) is
select obfuscated1_uid from web.obfuscated1 where issn in (
select distinct issn from web.obfuscated1 where issn = aIS9 or eissn = aIS9
union
select distinct eissn from web.obfuscated1 where issn = aIS9 or eissn = aIS9
) and group_num is null;
agroup number(8);
processCount number(8);
------------------------------------------------------
-- MAIN BLOCK -----------------------------------
-------------------------------------------------
begin
processCount := 0;
agroup := null;
for itemRec in ItemCursor loop
agroup := null;
begin
select group_num into agroup from web.obfuscated1 where issn in (
select distinct issn from web.obfuscated1 where issn = itemRec.is2 or eissn = itemRec.is2
union
select distinct eissn from web.obfuscated1 where issn = itemRec.is2 or eissn = itemRec.is2
) and group_num is not null and issn is not null and eissn is not null and rownum <= 1;
exception
when no_data_found then
agroup := null;
when others then
agroup := null;
end;
if agroup is not null then
for itemRec2 in ItemCursor2(itemRec.is2) loop
update web.obfuscated1 set group_num = agroup where obfuscated1_uid = itemRec2.obfuscated1_uid;
commit;
end loop;
else
processCount := processCount + 1;
for itemRec1 in ItemCursor1(itemRec.is2) loop
update web.obfuscated1 set group_num = processCount where obfuscated1_uid = itemRec1.obfuscated1_uid;
commit;
end loop;
commit;
end if;
end loop;
dbms_output.put_line('Total record read: ' || processCount);
exception
when others then
dbms_output.put_line('ORA' || sqlcode);
dbms_output.put_line(substr(sqlerrm, 1, 255));
dbms_output.put_line('ORA- Error during processing ' );
end;
/
exit;
</code></pre>
|
[
{
"answer_id": 193223,
"author": "Eric",
"author_id": 6367,
"author_profile": "https://Stackoverflow.com/users/6367",
"pm_score": 3,
"selected": false,
"text": "<p>the / at the end is to tell the interpreter to execute the loaded script</p>\n\n<p>basicaly you type stuff then type \"/\" and what you just typed will execute</p>\n"
},
{
"answer_id": 193224,
"author": "Eddie Awad",
"author_id": 17273,
"author_profile": "https://Stackoverflow.com/users/17273",
"pm_score": 5,
"selected": true,
"text": "<p>The slash has <a href=\"http://download.oracle.com/docs/cd/B28359_01/server.111/b31189/ch12004.htm#SQPUG162\" rel=\"noreferrer\">a meaning</a>:</p>\n\n<blockquote>\n <p>Executes the most recently executed\n SQL command or PL/SQL block which is\n stored in the SQL buffer. You can\n enter a slash (/) at the command\n prompt or at a line number prompt of a\n multi-line command. The slash command\n functions similarly to RUN, but does\n not list the command.</p>\n</blockquote>\n"
},
{
"answer_id": 193259,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>It is not an error. It executes the script. </p>\n\n<p>It is useful when you concatenate various scripts together in one file and want each separate task to execute before the next one.</p>\n\n<p>ie Create function\n/ \nCreate stored procedure that uses the function </p>\n\n<p>Without the slash the stored procedure may get created with errors or may not get created.</p>\n"
},
{
"answer_id": 193267,
"author": "Nuno G",
"author_id": 20959,
"author_profile": "https://Stackoverflow.com/users/20959",
"pm_score": 2,
"selected": false,
"text": "<p>Both the slash and the \"exit\" make me suspect you are supposed to run this script from SQLPLUS. You may get an error if you try to submit it to Oracle in some other way. In that case, just get rid of both. </p>\n"
},
{
"answer_id": 15108312,
"author": "ibre5041",
"author_id": 836215,
"author_profile": "https://Stackoverflow.com/users/836215",
"pm_score": 3,
"selected": false,
"text": "<p>When using Oracle you \"mix\" three different grammars. </p>\n\n<ul>\n<li>SQL</li>\n<li>PL/SQL</li>\n<li>sqlplus (command line client)</li>\n</ul>\n\n<p>sqlplus can execute/process SQL and PL/SQL statements by sending them onto DB server. While sqlplus commands are interpreted by sqlplus itself.</p>\n\n<p>The semicolon \";\" is not part of the SQL grammar and sqlplus recognizes it as the end of the SQL statement. While for PL/SQL it is part of the grammar and must must explicitly tell sqlplus that the statement ends here and should be executed by using slash.</p>\n\n<p>The other sqlplus commands are \"EXIT\", \"DEFINE\" \"VARIABLE\" \"PRINT\" \"SET <something>\" (except SET ROLE).</p>\n\n<p>On the other hand the Toad for example recognizes the end of the PL/SQL block when it sees an empty line.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22452/"
] |
I'm sorting out a series of SQL scripts for my company written in Oracle PL/SQL. I came across an essential script with a strangely placed slash near the bottom. It is checked into CVS this way. Is this a pure syntax error or does it have some function I'm not aware of. The slightly obfuscated script:
```
set serveroutput on size 2000;
--PL/SQL block to link ISSN in serial base on a company's ISSN text file
declare
cursor ItemCursor is
select issn is2 from web.obfuscated1 where issn is not null
union
select eissn is2 from web.obfuscated1 where eissn is not null;
cursor ItemCursor1(aIS varchar2) is
select obfuscated1_uid from web.obfuscated1 where group_num is null and issn in (
select distinct issn from web.obfuscated1 where issn = aIS or eissn = aIS
union
select distinct eissn from web.obfuscated1 where issn = aIS or eissn = aIS
)
union
select obfuscated1_uid from web.obfuscated1 where eissn in (
select distinct issn from web.obfuscated1 where issn = aIS or eissn = aIS
union
select distinct eissn from web.obfuscated1 where issn = aIS or eissn = aIS
);
cursor ItemCursor2(aIS9 varchar2) is
select obfuscated1_uid from web.obfuscated1 where issn in (
select distinct issn from web.obfuscated1 where issn = aIS9 or eissn = aIS9
union
select distinct eissn from web.obfuscated1 where issn = aIS9 or eissn = aIS9
) and group_num is null;
agroup number(8);
processCount number(8);
------------------------------------------------------
-- MAIN BLOCK -----------------------------------
-------------------------------------------------
begin
processCount := 0;
agroup := null;
for itemRec in ItemCursor loop
agroup := null;
begin
select group_num into agroup from web.obfuscated1 where issn in (
select distinct issn from web.obfuscated1 where issn = itemRec.is2 or eissn = itemRec.is2
union
select distinct eissn from web.obfuscated1 where issn = itemRec.is2 or eissn = itemRec.is2
) and group_num is not null and issn is not null and eissn is not null and rownum <= 1;
exception
when no_data_found then
agroup := null;
when others then
agroup := null;
end;
if agroup is not null then
for itemRec2 in ItemCursor2(itemRec.is2) loop
update web.obfuscated1 set group_num = agroup where obfuscated1_uid = itemRec2.obfuscated1_uid;
commit;
end loop;
else
processCount := processCount + 1;
for itemRec1 in ItemCursor1(itemRec.is2) loop
update web.obfuscated1 set group_num = processCount where obfuscated1_uid = itemRec1.obfuscated1_uid;
commit;
end loop;
commit;
end if;
end loop;
dbms_output.put_line('Total record read: ' || processCount);
exception
when others then
dbms_output.put_line('ORA' || sqlcode);
dbms_output.put_line(substr(sqlerrm, 1, 255));
dbms_output.put_line('ORA- Error during processing ' );
end;
/
exit;
```
|
The slash has [a meaning](http://download.oracle.com/docs/cd/B28359_01/server.111/b31189/ch12004.htm#SQPUG162):
>
> Executes the most recently executed
> SQL command or PL/SQL block which is
> stored in the SQL buffer. You can
> enter a slash (/) at the command
> prompt or at a line number prompt of a
> multi-line command. The slash command
> functions similarly to RUN, but does
> not list the command.
>
>
>
|
193,257 |
<p>Assuming a Read Committed Snapshot transaction isolation setting, is the following statement "atomic" in the sense that you won't ever "lose" a concurrent increment?</p>
<pre><code>update mytable set counter = counter + 1
</code></pre>
<p>I would assume that in the general case, where this update statement is part of a larger transaction, that it wouldn't be. For example, I think this scenario is possible:</p>
<ul>
<li>update the counter within transaction #1</li>
<li>do some other stuff
in transaction #1</li>
<li>update the counter
with transaction #2</li>
<li>commit
transaction #2</li>
<li>commit transaction #1</li>
</ul>
<p>In this situation, wouldn't the counter end up only being incremented by 1? Does it make a difference if that is the only statement in a transaction?</p>
<p>How does a site like stackoverflow handle this for its question view counter? Or is the possibility of "losing" some increments just considered acceptable?</p>
|
[
{
"answer_id": 193265,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 2,
"selected": false,
"text": "<p>No, it's not. The value is read in shared mode and then updated in exclusive mode, so multiple reads can occur.</p>\n\n<p>Either use Serializable level or use something like</p>\n\n<pre><code>update t\nset counter = counter+1\nfrom t with(updlock, <some other hints maybe>)\nwhere foo = bar\n</code></pre>\n"
},
{
"answer_id": 193456,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 5,
"selected": true,
"text": "<p>Read Committed Snapshot only deals with locks on selecting data from tables.</p>\n\n<p>In t1 and t2 however, you're UPDATEing the data, which is a different scenario.</p>\n\n<p>When you UPDATE the counter you escalate to a write lock (on the row), preventing the other update from occurring. t2 could read, but t2 will block on its UPDATE until t1 is done, and t2 won't be able to commit before t1 (which is contrary to your timeline). Only one of the transactions will get to update the counter, therefore both will update the counter correctly given the code presented. (tested)</p>\n\n<ul>\n<li>counter = 0</li>\n<li>t1 update counter (counter => 1)</li>\n<li>t2 update counter (blocked)</li>\n<li>t1 commit (counter = 1)</li>\n<li>t2 unblocked (can now update counter) (counter => 2)</li>\n<li>t2 commit</li>\n</ul>\n\n<hr>\n\n<p>Read Committed just means you can only read committed values, but it doesn't mean you have Repeatable Reads. Thus, if you use and depend on the counter variable, and intend to update it later, you're might be running the transactions at the wrong isolation level. </p>\n\n<p>You can either use a repeatable read lock, or if you only sometimes will update the counter, you can do it yourself using an optimistic locking technique. e.g. a timestamp column with the counter table, or a conditional update.</p>\n\n<pre><code>DECLARE @CounterInitialValue INT\nDECLARE @NewCounterValue INT\nSELECT @CounterInitialValue = SELECT counter FROM MyTable WHERE MyID = 1234\n\n-- do stuff with the counter value\n\nUPDATE MyTable\n SET counter = counter + 1\nWHERE\n MyID = 1234\n AND \n counter = @CounterInitialValue -- prevents the update if counter changed.\n\n-- the value of counter must not change in this scenario.\n-- so we rollback if the update affected no rows\nIF( @@ROWCOUNT = 0 )\n ROLLBACK\n</code></pre>\n\n<p>This <a href=\"http://www.devx.com/codemag/Article/21570\" rel=\"noreferrer\">devx</a> article is informative, although it talks about the features while they were still in beta, so it may not be completely accurate.</p>\n\n<hr>\n\n<p>update: As Justice indicates, if t2 is a nested transaction in t1, the semantics are different. Again, both would update counter correctly (+2) because from t2's perspective inside t1, counter was already updated once. The nested t2 has no access to what counter was before t1 updated it.</p>\n\n<ul>\n<li>counter = 0</li>\n<li>t1 update counter (counter => 1)</li>\n<li>t2 update counter (nested transaction) (counter => 2)</li>\n<li>t2 commit</li>\n<li>t1 commit (counter = 2)</li>\n</ul>\n\n<p>With a nested transaction, if t1 issues ROLLBACK after t1 COMMIT, counter returns to it's original value because it also undoes t2's commit.</p>\n"
},
{
"answer_id": 193484,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 1,
"selected": false,
"text": "<p>There is at heart only one transaction, the outermost one. The inner transactions are more like checkpoints within a transaction. Isolation levels affect only sibling outermost transactions, not parent/child related transactions.</p>\n\n<p>The counter will be incremented by two. The following yields one row with a value of (Num = 3). (I opened up SMSS and pointed it to a local SQL Server 2008 Express instance. I have a database named Playground for testing stuff.)</p>\n\n<pre><code>use Playground\n\ndrop table C\ncreate table C (\n Num int not null)\n\ninsert into C (Num) values (1)\n\nbegin tran X\n update C set Num = Num + 1\n begin tran Y\n update C set Num = Num + 1\n commit tran Y\ncommit tran X\n\nselect * from C\n</code></pre>\n"
},
{
"answer_id": 2695823,
"author": "scott-pascoe",
"author_id": 195550,
"author_profile": "https://Stackoverflow.com/users/195550",
"pm_score": 5,
"selected": false,
"text": "<p>According to the MSSQL Help, you could do it like this:</p>\n\n<pre><code>UPDATE tablename SET counterfield = counterfield + 1 OUTPUT INSERTED.counterfield\n</code></pre>\n\n<p>This will update the field by one, and return the updated value as a SQL recordset.</p>\n"
},
{
"answer_id": 58123448,
"author": "shatl",
"author_id": 87055,
"author_profile": "https://Stackoverflow.com/users/87055",
"pm_score": 1,
"selected": false,
"text": "<p>I used this SP to handle the case where name does not have a counter initially</p>\n\n<pre><code>ALTER PROCEDURE [dbo].[GetNext](\n@name varchar(50) )\nAS BEGIN SET NOCOUNT ON\n\nDECLARE @Out TABLE(Id BIGINT)\n\nMERGE TOP (1) dbo.Counter as Target\n USING (SELECT 1 as C, @name as name) as Source ON Target.name = Source.Name\n WHEN MATCHED THEN UPDATE SET Target.[current] = Target.[current] + 1\n WHEN NOT MATCHED THEN INSERT (name, [current]) VALUES (@name, 1)\nOUTPUT\n INSERTED.[current];\nEND\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26651/"
] |
Assuming a Read Committed Snapshot transaction isolation setting, is the following statement "atomic" in the sense that you won't ever "lose" a concurrent increment?
```
update mytable set counter = counter + 1
```
I would assume that in the general case, where this update statement is part of a larger transaction, that it wouldn't be. For example, I think this scenario is possible:
* update the counter within transaction #1
* do some other stuff
in transaction #1
* update the counter
with transaction #2
* commit
transaction #2
* commit transaction #1
In this situation, wouldn't the counter end up only being incremented by 1? Does it make a difference if that is the only statement in a transaction?
How does a site like stackoverflow handle this for its question view counter? Or is the possibility of "losing" some increments just considered acceptable?
|
Read Committed Snapshot only deals with locks on selecting data from tables.
In t1 and t2 however, you're UPDATEing the data, which is a different scenario.
When you UPDATE the counter you escalate to a write lock (on the row), preventing the other update from occurring. t2 could read, but t2 will block on its UPDATE until t1 is done, and t2 won't be able to commit before t1 (which is contrary to your timeline). Only one of the transactions will get to update the counter, therefore both will update the counter correctly given the code presented. (tested)
* counter = 0
* t1 update counter (counter => 1)
* t2 update counter (blocked)
* t1 commit (counter = 1)
* t2 unblocked (can now update counter) (counter => 2)
* t2 commit
---
Read Committed just means you can only read committed values, but it doesn't mean you have Repeatable Reads. Thus, if you use and depend on the counter variable, and intend to update it later, you're might be running the transactions at the wrong isolation level.
You can either use a repeatable read lock, or if you only sometimes will update the counter, you can do it yourself using an optimistic locking technique. e.g. a timestamp column with the counter table, or a conditional update.
```
DECLARE @CounterInitialValue INT
DECLARE @NewCounterValue INT
SELECT @CounterInitialValue = SELECT counter FROM MyTable WHERE MyID = 1234
-- do stuff with the counter value
UPDATE MyTable
SET counter = counter + 1
WHERE
MyID = 1234
AND
counter = @CounterInitialValue -- prevents the update if counter changed.
-- the value of counter must not change in this scenario.
-- so we rollback if the update affected no rows
IF( @@ROWCOUNT = 0 )
ROLLBACK
```
This [devx](http://www.devx.com/codemag/Article/21570) article is informative, although it talks about the features while they were still in beta, so it may not be completely accurate.
---
update: As Justice indicates, if t2 is a nested transaction in t1, the semantics are different. Again, both would update counter correctly (+2) because from t2's perspective inside t1, counter was already updated once. The nested t2 has no access to what counter was before t1 updated it.
* counter = 0
* t1 update counter (counter => 1)
* t2 update counter (nested transaction) (counter => 2)
* t2 commit
* t1 commit (counter = 2)
With a nested transaction, if t1 issues ROLLBACK after t1 COMMIT, counter returns to it's original value because it also undoes t2's commit.
|
193,260 |
<p>We're currently running an <code>svnserve</code> instance as NT service. While this works, it's needlessly cumbersome to administer, and I'd like to move on to the much simpler VisualSVN Server. (Bonus side benefits include Windows-integrated authentication and, thanks to HTTP/WebDAV, browsing of the latest revision.)</p>
<p>That said, the current server offers up URLs that look like this:</p>
<pre><code>svn://oldserver/path/to/some/file.foo
</code></pre>
<p>Rather memorable.</p>
<p>The new one, as set up through VSVNS:</p>
<pre><code>https://newserver:8443/svn/Repos/path/to/some/file.foo
</code></pre>
<p>Ouch. For one, the <code>/svn</code> bit is <em>entirely</em> unnecessary. Since VSVNS runs its own HTTP server (that's why it's on the special port <code>8443</code>, after all), <em>of course</em> everything is related to <code>svn</code>. Moreover, we only have one repository (and no real need for more), so the repository name in <code>/Repos</code> shouldn't be there either — we could turn this off with <code>svnserve</code>, so there should be a way to do it now, too.</p>
<ul>
<li>Is it possible to configure VisualSVN Server to drop the <code>/svn</code>? (Why is it there to begin with?)</li>
<li>Given that there is only one repository, can I tell it not to make the repository name part of the URL?</li>
</ul>
|
[
{
"answer_id": 193265,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 2,
"selected": false,
"text": "<p>No, it's not. The value is read in shared mode and then updated in exclusive mode, so multiple reads can occur.</p>\n\n<p>Either use Serializable level or use something like</p>\n\n<pre><code>update t\nset counter = counter+1\nfrom t with(updlock, <some other hints maybe>)\nwhere foo = bar\n</code></pre>\n"
},
{
"answer_id": 193456,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 5,
"selected": true,
"text": "<p>Read Committed Snapshot only deals with locks on selecting data from tables.</p>\n\n<p>In t1 and t2 however, you're UPDATEing the data, which is a different scenario.</p>\n\n<p>When you UPDATE the counter you escalate to a write lock (on the row), preventing the other update from occurring. t2 could read, but t2 will block on its UPDATE until t1 is done, and t2 won't be able to commit before t1 (which is contrary to your timeline). Only one of the transactions will get to update the counter, therefore both will update the counter correctly given the code presented. (tested)</p>\n\n<ul>\n<li>counter = 0</li>\n<li>t1 update counter (counter => 1)</li>\n<li>t2 update counter (blocked)</li>\n<li>t1 commit (counter = 1)</li>\n<li>t2 unblocked (can now update counter) (counter => 2)</li>\n<li>t2 commit</li>\n</ul>\n\n<hr>\n\n<p>Read Committed just means you can only read committed values, but it doesn't mean you have Repeatable Reads. Thus, if you use and depend on the counter variable, and intend to update it later, you're might be running the transactions at the wrong isolation level. </p>\n\n<p>You can either use a repeatable read lock, or if you only sometimes will update the counter, you can do it yourself using an optimistic locking technique. e.g. a timestamp column with the counter table, or a conditional update.</p>\n\n<pre><code>DECLARE @CounterInitialValue INT\nDECLARE @NewCounterValue INT\nSELECT @CounterInitialValue = SELECT counter FROM MyTable WHERE MyID = 1234\n\n-- do stuff with the counter value\n\nUPDATE MyTable\n SET counter = counter + 1\nWHERE\n MyID = 1234\n AND \n counter = @CounterInitialValue -- prevents the update if counter changed.\n\n-- the value of counter must not change in this scenario.\n-- so we rollback if the update affected no rows\nIF( @@ROWCOUNT = 0 )\n ROLLBACK\n</code></pre>\n\n<p>This <a href=\"http://www.devx.com/codemag/Article/21570\" rel=\"noreferrer\">devx</a> article is informative, although it talks about the features while they were still in beta, so it may not be completely accurate.</p>\n\n<hr>\n\n<p>update: As Justice indicates, if t2 is a nested transaction in t1, the semantics are different. Again, both would update counter correctly (+2) because from t2's perspective inside t1, counter was already updated once. The nested t2 has no access to what counter was before t1 updated it.</p>\n\n<ul>\n<li>counter = 0</li>\n<li>t1 update counter (counter => 1)</li>\n<li>t2 update counter (nested transaction) (counter => 2)</li>\n<li>t2 commit</li>\n<li>t1 commit (counter = 2)</li>\n</ul>\n\n<p>With a nested transaction, if t1 issues ROLLBACK after t1 COMMIT, counter returns to it's original value because it also undoes t2's commit.</p>\n"
},
{
"answer_id": 193484,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 1,
"selected": false,
"text": "<p>There is at heart only one transaction, the outermost one. The inner transactions are more like checkpoints within a transaction. Isolation levels affect only sibling outermost transactions, not parent/child related transactions.</p>\n\n<p>The counter will be incremented by two. The following yields one row with a value of (Num = 3). (I opened up SMSS and pointed it to a local SQL Server 2008 Express instance. I have a database named Playground for testing stuff.)</p>\n\n<pre><code>use Playground\n\ndrop table C\ncreate table C (\n Num int not null)\n\ninsert into C (Num) values (1)\n\nbegin tran X\n update C set Num = Num + 1\n begin tran Y\n update C set Num = Num + 1\n commit tran Y\ncommit tran X\n\nselect * from C\n</code></pre>\n"
},
{
"answer_id": 2695823,
"author": "scott-pascoe",
"author_id": 195550,
"author_profile": "https://Stackoverflow.com/users/195550",
"pm_score": 5,
"selected": false,
"text": "<p>According to the MSSQL Help, you could do it like this:</p>\n\n<pre><code>UPDATE tablename SET counterfield = counterfield + 1 OUTPUT INSERTED.counterfield\n</code></pre>\n\n<p>This will update the field by one, and return the updated value as a SQL recordset.</p>\n"
},
{
"answer_id": 58123448,
"author": "shatl",
"author_id": 87055,
"author_profile": "https://Stackoverflow.com/users/87055",
"pm_score": 1,
"selected": false,
"text": "<p>I used this SP to handle the case where name does not have a counter initially</p>\n\n<pre><code>ALTER PROCEDURE [dbo].[GetNext](\n@name varchar(50) )\nAS BEGIN SET NOCOUNT ON\n\nDECLARE @Out TABLE(Id BIGINT)\n\nMERGE TOP (1) dbo.Counter as Target\n USING (SELECT 1 as C, @name as name) as Source ON Target.name = Source.Name\n WHEN MATCHED THEN UPDATE SET Target.[current] = Target.[current] + 1\n WHEN NOT MATCHED THEN INSERT (name, [current]) VALUES (@name, 1)\nOUTPUT\n INSERTED.[current];\nEND\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1600/"
] |
We're currently running an `svnserve` instance as NT service. While this works, it's needlessly cumbersome to administer, and I'd like to move on to the much simpler VisualSVN Server. (Bonus side benefits include Windows-integrated authentication and, thanks to HTTP/WebDAV, browsing of the latest revision.)
That said, the current server offers up URLs that look like this:
```
svn://oldserver/path/to/some/file.foo
```
Rather memorable.
The new one, as set up through VSVNS:
```
https://newserver:8443/svn/Repos/path/to/some/file.foo
```
Ouch. For one, the `/svn` bit is *entirely* unnecessary. Since VSVNS runs its own HTTP server (that's why it's on the special port `8443`, after all), *of course* everything is related to `svn`. Moreover, we only have one repository (and no real need for more), so the repository name in `/Repos` shouldn't be there either — we could turn this off with `svnserve`, so there should be a way to do it now, too.
* Is it possible to configure VisualSVN Server to drop the `/svn`? (Why is it there to begin with?)
* Given that there is only one repository, can I tell it not to make the repository name part of the URL?
|
Read Committed Snapshot only deals with locks on selecting data from tables.
In t1 and t2 however, you're UPDATEing the data, which is a different scenario.
When you UPDATE the counter you escalate to a write lock (on the row), preventing the other update from occurring. t2 could read, but t2 will block on its UPDATE until t1 is done, and t2 won't be able to commit before t1 (which is contrary to your timeline). Only one of the transactions will get to update the counter, therefore both will update the counter correctly given the code presented. (tested)
* counter = 0
* t1 update counter (counter => 1)
* t2 update counter (blocked)
* t1 commit (counter = 1)
* t2 unblocked (can now update counter) (counter => 2)
* t2 commit
---
Read Committed just means you can only read committed values, but it doesn't mean you have Repeatable Reads. Thus, if you use and depend on the counter variable, and intend to update it later, you're might be running the transactions at the wrong isolation level.
You can either use a repeatable read lock, or if you only sometimes will update the counter, you can do it yourself using an optimistic locking technique. e.g. a timestamp column with the counter table, or a conditional update.
```
DECLARE @CounterInitialValue INT
DECLARE @NewCounterValue INT
SELECT @CounterInitialValue = SELECT counter FROM MyTable WHERE MyID = 1234
-- do stuff with the counter value
UPDATE MyTable
SET counter = counter + 1
WHERE
MyID = 1234
AND
counter = @CounterInitialValue -- prevents the update if counter changed.
-- the value of counter must not change in this scenario.
-- so we rollback if the update affected no rows
IF( @@ROWCOUNT = 0 )
ROLLBACK
```
This [devx](http://www.devx.com/codemag/Article/21570) article is informative, although it talks about the features while they were still in beta, so it may not be completely accurate.
---
update: As Justice indicates, if t2 is a nested transaction in t1, the semantics are different. Again, both would update counter correctly (+2) because from t2's perspective inside t1, counter was already updated once. The nested t2 has no access to what counter was before t1 updated it.
* counter = 0
* t1 update counter (counter => 1)
* t2 update counter (nested transaction) (counter => 2)
* t2 commit
* t1 commit (counter = 2)
With a nested transaction, if t1 issues ROLLBACK after t1 COMMIT, counter returns to it's original value because it also undoes t2's commit.
|
193,288 |
<p>Most of Apples documentation seems to avoid using autoreleased objects especially when creating gui views, but I want to know what the cost of using autoreleased objects is?</p>
<pre><code>UIScrollView *timeline = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 20, 320, 34)];
[self addSubview:timeline];
[timeline release];
</code></pre>
<p>Ultimately should I use a strategy where everything is autoreleased and using retain/release should be the exception to the rule for specific cases? Or should I generally be using retain/release with autorelease being the exception for returned objects from convenience methods like [NSString stringWithEtc...] ?</p>
|
[
{
"answer_id": 193377,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 2,
"selected": false,
"text": "<p>As I understand it, the main downside to using autorelease is that you don't know when the object will finally be released and destroyed. This could potentially cause your app to use a lot more memory than it needs to if you have a lot of autoreleased objects hanging around but not yet released.</p>\n"
},
{
"answer_id": 193640,
"author": "mmalc",
"author_id": 23233,
"author_profile": "https://Stackoverflow.com/users/23233",
"pm_score": 5,
"selected": true,
"text": "<p>There are two costs:</p>\n\n<ol>\n<li><p>(Assuming you have an option to avoid autoreleased objects.) You effectively unnecessarily extend the lifetime of your objects. This can mean that your memory footprint grows -- unnecessarily. On a constrained platform, this can mean that your application is terminated if it exceeds a limit. Even if you don't exceed a limit, it may cause your system to start swapping, which is very inefficient.</p></li>\n<li><p>The additional overhead of finding the current autorelease pool, adding the autoreleased object to it, and then releasing the object at the end (an extra method call). This may not be a large overhead, but it can add up.</p></li>\n</ol>\n\n<p>Best practice on any platform is to try to avoid autorelease if you can.</p>\n\n<p>To answer the questions:</p>\n\n<blockquote>\n <p>Ultimately should I use a strategy where everything is autoreleased and using retain/release should be the exception to the rule for specific cases?</p>\n</blockquote>\n\n<p>Quite the opposite.</p>\n\n<blockquote>\n <p>Or should I generally be using retain/release with autorelease being the exception for returned objects from convenience methods like [NSString stringWithEtc...] ?</p>\n</blockquote>\n\n<p>You should <em>always</em> use retain/release if you can -- in the case of <code>NSString</code> there is typically no need to use <code>stringWithEtc</code> methods as there are <code>initWithEtc</code> equivalents.</p>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/155964/what-are-best-practices-that-you-use-when-writing-objective-c-and-cocoa#175874\">this question</a>.</p>\n"
},
{
"answer_id": 193812,
"author": "benzado",
"author_id": 10947,
"author_profile": "https://Stackoverflow.com/users/10947",
"pm_score": 3,
"selected": false,
"text": "<p>The costs are:</p>\n\n<ol>\n<li>The time to locate the current thread's autorelease pool and add the object to it.</li>\n<li>The memory occupied by the object until it is released at some later point.</li>\n</ol>\n\n<p>If you want to be very conservative with your memory usage, you should avoid autorelease. However, it is a useful technique that can make code more readable. Obsessively using retain/release falls under the umbrella of \"premature optimization.\"</p>\n\n<p>If you are in Cocoa's main event handling thread (which you are most of the time), the autorelease pool is emptied when control returns to the event handler. If your method is short and doesn't loop over large amounts of data, using autorelease to defer deallocation to the end of the run loop is fine.</p>\n\n<p>The time to be wary of autorelease is when you are in a loop. For example, you are iterating over a user's address book and perhaps loading an image file for each entry. If all of those image objects are autoreleased, they will accumulate in memory until you have visited the entire address book. If the address book is large enough, you may run out of memory. If you release the images as soon as you are done with them, within the loop, your app can recycle the memory.</p>\n\n<p>If you can't avoid autoreleasing inside a loop (it's being done by code you didn't write and can't change), you can also manage an NSAutoreleasePool within the loop yourself if needed.</p>\n\n<p>So, be mindful of using autorelease inside loops (or methods that may be called from loops), but don't avoid it when it can make code more readable.</p>\n"
},
{
"answer_id": 193818,
"author": "Jim Puls",
"author_id": 6010,
"author_profile": "https://Stackoverflow.com/users/6010",
"pm_score": 3,
"selected": false,
"text": "<p>I'm surprised nobody has mentioned this yet. The biggest reason to avoid autoreleased objects when you can has nothing to do with performance. Yes, all of the performance concerns mentioned here are <em>absolutely</em> valid, but the biggest downside to autorelease is that it makes debugging significantly more difficult.</p>\n\n<p>If you have an overreleased object that's never autoreleased, it's trivially easy to track down. If you have a user-reported crash that happens intermittently with a backtrace somewhere south of NSPopAutoreleasePool, good luck...</p>\n"
},
{
"answer_id": 195472,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Others have answered whether you should autorelease, but when you <em>must</em> autorelease, drain early and drain often: <a href=\"http://www.mikeash.com/?page=pyblog/autorelease-is-fast.html\" rel=\"nofollow noreferrer\">http://www.mikeash.com/?page=pyblog/autorelease-is-fast.html</a></p>\n"
},
{
"answer_id": 195658,
"author": "danwood",
"author_id": 25560,
"author_profile": "https://Stackoverflow.com/users/25560",
"pm_score": 4,
"selected": false,
"text": "<p>I have to disagree with Jim Puls - I think that <strong>not</strong> using Autorelease makes debugging more difficult, because you are more likely to find yourself accidentally leaking memory. Of course Clang static analyzer can pick up some of these instances, but for me, the slight overhead costs in habitually using autorelease are far overshadowed by my code being less likely to be buggy.</p>\n\n<p>And then, only if I have a tight loop I need to optimize will I start looking at performance. Otherwise this is all just premature optimization, which is generally considered to be a bad thing.</p>\n"
},
{
"answer_id": 204800,
"author": "lfalin",
"author_id": 28106,
"author_profile": "https://Stackoverflow.com/users/28106",
"pm_score": 0,
"selected": false,
"text": "<p>One side note to keep in mind is if you are spawning a new thread, you must setup a new Autorelease pool on that thread before you do anything else. Even if you are not using autorelease objects, chances are that something in the Cocoa APIs is.</p>\n"
},
{
"answer_id": 204875,
"author": "David Grant",
"author_id": 26829,
"author_profile": "https://Stackoverflow.com/users/26829",
"pm_score": 1,
"selected": false,
"text": "<p>I notice the code sample you provided is for the iPhone. Apple specifically recommends avoiding autoreleased objects for iPhone apps. I can't find the specific reasoning, but they were hammering this point at WWDC.</p>\n"
},
{
"answer_id": 224525,
"author": "Dave Dribin",
"author_id": 26825,
"author_profile": "https://Stackoverflow.com/users/26825",
"pm_score": 3,
"selected": false,
"text": "<p>One <em>benefit</em> to using autorelease pools is that they are exception safe without using <code>@try</code>/<code>@finally</code>. Greg Parker ('Mr. Objective-C') has a <a href=\"http://sealiesoftware.com/blog/archive/2008/09/16/objc_explain_Exceptions_and_autorelease_pools.html\" rel=\"nofollow noreferrer\">great post</a> explaining the details of this.</p>\n\n<p>I tend to use <code>autorelease</code> a lot as its less code and makes it more readable, IMO. The downside, as others have pointed out, is that you extend the lifetime of objects, thus temporarily using more memory. In practice, I have yet to find overuse of <code>autorelease</code> to be a significant issue in any Mac app I've written. If high memory usage does seem to be an issue (that isn't caused by a genuine leak), I just add in more autorelease pools (after profiling to show me where I need them). But, in general, this is quite rare. As Mike Ash's post shows (Graham Lee linked to it), autorelease pools have very little overhead and are fast. There's almost zero cost to adding more autorelease pools.</p>\n\n<p>Granted, this is all for Mac apps. In iPhone apps, where memory is more tight, you may want to be conservative in your use of autorelease. But as always, write readable code first, and then optimize later, <em>by measuring</em> where the slow/memory intensive parts are.</p>\n"
},
{
"answer_id": 227272,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 3,
"selected": false,
"text": "<p>I generally use autoreleased objects these days because they tend to result in simpler, easier to read code. You declare and initialize them, then let the drop out of scope. Mechanically they exist quite a bit longer, but from the perspective of the person writing the code it is equivalent to a stack declared object in C++ automatically being destructed when the function returns and its frame is destroyed.</p>\n\n<p>While there is an efficiency loss, in most cases it is not significant. The bigger issue is the more extant objects and later memory recovery can lead to a more fragmented address space. If that is an issue it usually is fairly simple to go in and switch to manual retain/release in a few hot methods and improve it.</p>\n\n<p>As others have said, readability trumps performance in nonperformance sensitive code. There are a number of cases where using autoreleased objects leads to more memory fragmentation, but in any case where the object will outlive the pool it will not. In those cases the only price you are paying is finding the cost of finding the correct autorelease pool.</p>\n"
},
{
"answer_id": 2546636,
"author": "Dev Kanchen",
"author_id": 303179,
"author_profile": "https://Stackoverflow.com/users/303179",
"pm_score": 0,
"selected": false,
"text": "<p>Old thread, but chipping on for the benefit of newer readers.</p>\n\n<p>I use autorelease vs retain/release depending on the risk of autorelease bugs specific to an object and the size of the object. If I'm just adding some tiny UIImageViews, or a couple of UILabels to my view, autorelease keeps the code readable and manageable. And when the view is removed and dealloced, these subviews should get released soon enough. </p>\n\n<p>If on the other hand we're talking about a UIWebView (high risk of autorelease bugs), or of course some data that needs to be persistent till the 'death' of the object, retain/release is the way to go.</p>\n\n<p>Honestly, my projects have not gotten that big yet, where the additional 'staying-time' of autoreleased objects would create a memory problem. For complex apps, that concern is legitimate.</p>\n\n<p>In any case, I don't think a one-size-fits-all approach would be right. You use whatever approach - or combination of approaches - is right for the project, keeping all the factors mentioned above in mind.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26986/"
] |
Most of Apples documentation seems to avoid using autoreleased objects especially when creating gui views, but I want to know what the cost of using autoreleased objects is?
```
UIScrollView *timeline = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 20, 320, 34)];
[self addSubview:timeline];
[timeline release];
```
Ultimately should I use a strategy where everything is autoreleased and using retain/release should be the exception to the rule for specific cases? Or should I generally be using retain/release with autorelease being the exception for returned objects from convenience methods like [NSString stringWithEtc...] ?
|
There are two costs:
1. (Assuming you have an option to avoid autoreleased objects.) You effectively unnecessarily extend the lifetime of your objects. This can mean that your memory footprint grows -- unnecessarily. On a constrained platform, this can mean that your application is terminated if it exceeds a limit. Even if you don't exceed a limit, it may cause your system to start swapping, which is very inefficient.
2. The additional overhead of finding the current autorelease pool, adding the autoreleased object to it, and then releasing the object at the end (an extra method call). This may not be a large overhead, but it can add up.
Best practice on any platform is to try to avoid autorelease if you can.
To answer the questions:
>
> Ultimately should I use a strategy where everything is autoreleased and using retain/release should be the exception to the rule for specific cases?
>
>
>
Quite the opposite.
>
> Or should I generally be using retain/release with autorelease being the exception for returned objects from convenience methods like [NSString stringWithEtc...] ?
>
>
>
You should *always* use retain/release if you can -- in the case of `NSString` there is typically no need to use `stringWithEtc` methods as there are `initWithEtc` equivalents.
See also [this question](https://stackoverflow.com/questions/155964/what-are-best-practices-that-you-use-when-writing-objective-c-and-cocoa#175874).
|
193,341 |
<p>I have a Trac project installed on top of a Subversion implementation (easy to do thanks to Webfaction's control panel), but now I have configuration work to do. With that in mind, are there <em>easy</em> ways to do the following in Trac:</p>
<p>1) Ensure that customers can only see a high level progress indicator.<br>
2) Give daily summary reports on tickets, testing, and tasks.</p>
<p>Also, I am interested in knowing if there are any <strong>highly</strong> recommended plugins that I would be sorry I forgot to install.</p>
|
[
{
"answer_id": 193445,
"author": "Dave Dunkin",
"author_id": 453303,
"author_profile": "https://Stackoverflow.com/users/453303",
"pm_score": 4,
"selected": false,
"text": "<p>I would not recommend using the same Trac project for tracking development tasks and showing the customer progress. You want to be able to be candid with your development tickets, comments, etc. Customers can focus on the wrong things and misinterpret data you put in the tickets. I would recommend providing the customer with a separate project that contains high level tasks and only shows the progress on those tasks, not the nitty gritty.</p>\n"
},
{
"answer_id": 194053,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 2,
"selected": false,
"text": "<p>@Dave Dunkin is right. Use Trac for your internal use, and use a system like <a href=\"http://www.basecamphq.com/\" rel=\"nofollow noreferrer\">Basecamp</a> to give your clients a high-level overview of what's going on in the project.</p>\n"
},
{
"answer_id": 218132,
"author": "Jon Topper",
"author_id": 6945,
"author_profile": "https://Stackoverflow.com/users/6945",
"pm_score": 3,
"selected": false,
"text": "<p>As far as additional plugins are concerned, we install TocMacro, XmlRpcPlugin, WysiwygPlugin and TracRedirect. In particular, the WYSIWYG plugin is really good for encouraging less technical staff to maintain their own documents in the wiki - you can even C&P from MS Word whilst retaining formatting, which helps.</p>\n\n<p>Take a look at the custom ticket workflow stuff that Trac gives you, if your own workflow isn't well represented by Trac's defaults. This has allowed us to add code review and integration testing steps to the workflow.</p>\n\n<p>I'd recommend making your Trac server authenticate against some central authentication framework. We run an LDAP tree with auth credentials in it, and this is used by all our internal systems - including trac, svn, samba, openvpn etc.</p>\n"
},
{
"answer_id": 218211,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 2,
"selected": false,
"text": "<p>If it's a stock install, the database is just an SQLite3, so you can easily write scripts to fetch \"safe\" info, like the number of tickets, or why not one of the reports. That way, you can discuss freely as long as the ticket name is ok. Revisions, milestones, wikipages, tags (if you use that plugin) are also available.</p>\n"
},
{
"answer_id": 524915,
"author": "Oliver Giesen",
"author_id": 9784,
"author_profile": "https://Stackoverflow.com/users/9784",
"pm_score": 2,
"selected": false,
"text": "<p>You could probably withdraw all permissions except <code>ROADMAP_VIEW</code> from the anonymous user but that will probably be a bit <strong>too</strong> high-level, no? Access control at the individual ticket or comment level is currently not supported AFAIK. See <a href=\"http://trac.edgewall.org/wiki/TracPermissions\" rel=\"nofollow noreferrer\">http://trac.edgewall.org/wiki/TracPermissions</a> for details about trac permissions.</p>\n"
},
{
"answer_id": 530173,
"author": "Bob Nadler",
"author_id": 2514,
"author_profile": "https://Stackoverflow.com/users/2514",
"pm_score": 2,
"selected": false,
"text": "<p>As mentioned in one of the comments, you can't restrict ticket or comment access based on the user. Finding or creating an external reporting system is your best bet.</p>\n\n<p>A couple of things based on experience with Trac:</p>\n\n<ol>\n<li><p>Creating a custom <a href=\"http://trac.edgewall.org/wiki/TracWorkflow\" rel=\"nofollow noreferrer\">workflow</a> is\npretty straight froward. The use of\n<a href=\"http://www.graphviz.org/\" rel=\"nofollow noreferrer\">GraphViz</a> is a huge help for\ncommunicating states and actions. A workflow plugin (like <a href=\"http://trac-hacks.org/wiki/AdvancedTicketWorkflowPlugin\" rel=\"nofollow noreferrer\">AdvancedTicketWorkflowPlugin</a>) that further extends the built-in functionality isn't too hard to do if you need more complex state interaction.</p></li>\n<li><p>For custom reporting, you can write\nSQL queries that take named parameters,\nthen link to these from a wiki page:</p></li>\n</ol>\n\n<p>For example, the query can contain a WHERE clause like this:</p>\n\n<pre><code>WHERE datetime(t.changetime, 'unixepoch') >= datetime('now','-$DAYS days')\n</code></pre>\n\n<p>and the wiki page can have this:</p>\n\n<pre><code>Show activity for last [http://server.com/trac/report/9?DAYS=8 8] days.\n</code></pre>\n"
},
{
"answer_id": 534447,
"author": "Lena Schimmel",
"author_id": 39946,
"author_profile": "https://Stackoverflow.com/users/39946",
"pm_score": 4,
"selected": true,
"text": "<p><strong>1) high level progress indicator:</strong></p>\n\n<p>The roadmap tab gives you kind of a high level progress indicator. It lists all milestones, and for each milestone it shows you:</p>\n\n<ul>\n<li>milestone title</li>\n<li>short description</li>\n<li>date on which the milestone is due</li>\n<li>how much time is left until then (or how long you are behind you schedule)</li>\n<li>how many tickets are assigned to that milestone and how many of them have been closed, visualized as a nice green progress bar. This bar is drawn on the assumtion that each ticket has the same weight, which might be misleading</li>\n</ul>\n\n<p>You can restrict your permissions in a way that your customer can only access this view.</p>\n\n<p>Depending on the relationship between you and your customer, you might want to give him the ability to create new tickets (permission TICKET_CREATE), which should be possible without giving him read access to other tickets (TICKET_VIEW and TICKET_MODIFY). Sorry, but I can't currently test if this really works, maybe someone can comment on this.</p>\n\n<p><strong>2) daily summary reports</strong></p>\n\n<p>trac offers you RSS feeds for everything you can think of. It should be possible to generate daily reports from this, or you simply tell your RSS client to check the feed once a day.</p>\n\n<p>Trac also has the abilty to inform a ticket-owner via mail if that ticket changed, but it will happen instantly, not as a daily summary. You can comment on tickets, and sometimes we use them like a discussion board or mailing list, and in this case it's good to be notified instantly.</p>\n\n<p><strong>Other configuration</strong></p>\n\n<p>In each project I do with trac, I create a custom query to list all tickets that nobody owns:</p>\n\n<pre>\nSELECT p.value AS __color__,\n owner AS __group__,\nstatus,\n id AS ticket, summary, component, milestone, t.type AS type, time AS created,\n changetime AS _changetime, description AS _description,\n reporter AS _reporter\n FROM ticket t\n LEFT JOIN enum p ON p.name = t.priority AND p.type = 'priority'\n WHERE status = 'new' AND (owner = '' OR owner = 'somebody' OR owner = 'None' )\n ORDER BY owner, p.value, t.type, time\n</pre>\n\n<p>Each ticket may have an owner and several people in the cc field, but the report for <em>my tickets</em> only lists those where you are the owner. To overcome this, I add a query like this:</p>\n\n<pre>\n SELECT p.value AS __color__,\n (CASE owner WHEN '$USER' THEN \n (CASE status \n WHEN 'assigned' \n THEN 'Tickets that you accepted' \n ELSE 'Tickets that were assigned to you, please accept or reassign' \n END) \n ELSE 'Tickets, that have your name in the cc' END) \n AS __group__,\n id AS ticket, summary, component, version, milestone,\n t.type AS type, priority, time AS created,\n changetime AS _changetime, description AS _description,\n reporter AS _reporter\n FROM ticket t\n LEFT JOIN enum p ON p.name = t.priority AND p.type = 'priority'\n WHERE t.status 'closed' AND (owner = '$USER' OR cc like '%$USER%')\n ORDER BY owner, (status = 'assigned') DESC, p.value, milestone, t.type, time\n</pre>\n\n<p><em>(this code works in trac 0.11b)</em></p>\n\n<p>That's my favorite ticket report. It goups tickets by three classes:</p>\n\n<ul>\n<li>Tickets you own and accepted</li>\n<li>Tickets that were assigned to you, but you didn't accept yet</li>\n<li>Tickets that have you in the cc (that the fancy thing you don't get without that query)</li>\n</ul>\n\n<p>The queries might look scary, but they are simple modifications of the queries that are already there. You don't have to hack the trac source code, the webinterface lets you edit queries.</p>\n\n<p><strong>Plugins</strong></p>\n\n<p>I recommend the <a href=\"http://trac-hacks.org/wiki/XmlRpcPlugin\" rel=\"noreferrer\">XML RPC plugin</a> if you work with eclipse. It enables tight integration with <a href=\"http://www.eclipse.org/mylyn/start/\" rel=\"noreferrer\">Mylin</a>. (I think basic integration works even without the plugin), so your developers can do many tasks from within eclipse without switching to the trac webinterface.</p>\n\n<p>(If you use eclipse, but don't know mylin, you should have a look at it. You can test it without any configuration because it comes with most eclipse distributions and can work as standalone without trac.)</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13990/"
] |
I have a Trac project installed on top of a Subversion implementation (easy to do thanks to Webfaction's control panel), but now I have configuration work to do. With that in mind, are there *easy* ways to do the following in Trac:
1) Ensure that customers can only see a high level progress indicator.
2) Give daily summary reports on tickets, testing, and tasks.
Also, I am interested in knowing if there are any **highly** recommended plugins that I would be sorry I forgot to install.
|
**1) high level progress indicator:**
The roadmap tab gives you kind of a high level progress indicator. It lists all milestones, and for each milestone it shows you:
* milestone title
* short description
* date on which the milestone is due
* how much time is left until then (or how long you are behind you schedule)
* how many tickets are assigned to that milestone and how many of them have been closed, visualized as a nice green progress bar. This bar is drawn on the assumtion that each ticket has the same weight, which might be misleading
You can restrict your permissions in a way that your customer can only access this view.
Depending on the relationship between you and your customer, you might want to give him the ability to create new tickets (permission TICKET\_CREATE), which should be possible without giving him read access to other tickets (TICKET\_VIEW and TICKET\_MODIFY). Sorry, but I can't currently test if this really works, maybe someone can comment on this.
**2) daily summary reports**
trac offers you RSS feeds for everything you can think of. It should be possible to generate daily reports from this, or you simply tell your RSS client to check the feed once a day.
Trac also has the abilty to inform a ticket-owner via mail if that ticket changed, but it will happen instantly, not as a daily summary. You can comment on tickets, and sometimes we use them like a discussion board or mailing list, and in this case it's good to be notified instantly.
**Other configuration**
In each project I do with trac, I create a custom query to list all tickets that nobody owns:
```
SELECT p.value AS __color__,
owner AS __group__,
status,
id AS ticket, summary, component, milestone, t.type AS type, time AS created,
changetime AS _changetime, description AS _description,
reporter AS _reporter
FROM ticket t
LEFT JOIN enum p ON p.name = t.priority AND p.type = 'priority'
WHERE status = 'new' AND (owner = '' OR owner = 'somebody' OR owner = 'None' )
ORDER BY owner, p.value, t.type, time
```
Each ticket may have an owner and several people in the cc field, but the report for *my tickets* only lists those where you are the owner. To overcome this, I add a query like this:
```
SELECT p.value AS __color__,
(CASE owner WHEN '$USER' THEN
(CASE status
WHEN 'assigned'
THEN 'Tickets that you accepted'
ELSE 'Tickets that were assigned to you, please accept or reassign'
END)
ELSE 'Tickets, that have your name in the cc' END)
AS __group__,
id AS ticket, summary, component, version, milestone,
t.type AS type, priority, time AS created,
changetime AS _changetime, description AS _description,
reporter AS _reporter
FROM ticket t
LEFT JOIN enum p ON p.name = t.priority AND p.type = 'priority'
WHERE t.status 'closed' AND (owner = '$USER' OR cc like '%$USER%')
ORDER BY owner, (status = 'assigned') DESC, p.value, milestone, t.type, time
```
*(this code works in trac 0.11b)*
That's my favorite ticket report. It goups tickets by three classes:
* Tickets you own and accepted
* Tickets that were assigned to you, but you didn't accept yet
* Tickets that have you in the cc (that the fancy thing you don't get without that query)
The queries might look scary, but they are simple modifications of the queries that are already there. You don't have to hack the trac source code, the webinterface lets you edit queries.
**Plugins**
I recommend the [XML RPC plugin](http://trac-hacks.org/wiki/XmlRpcPlugin) if you work with eclipse. It enables tight integration with [Mylin](http://www.eclipse.org/mylyn/start/). (I think basic integration works even without the plugin), so your developers can do many tasks from within eclipse without switching to the trac webinterface.
(If you use eclipse, but don't know mylin, you should have a look at it. You can test it without any configuration because it comes with most eclipse distributions and can work as standalone without trac.)
|
193,351 |
<p>Is it possible to break at runtime when a particular file has been modified? </p>
<p>ie. monitor the file and break into a debugger once a change has been made to it.</p>
<p>This is for a windows app...is this possible in visual studio or windbg?</p>
<p>edit: i should have mentioned that this is for a Win32 app..</p>
|
[
{
"answer_id": 193360,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming this is .NET, the System.IO.<strong>FileSystemWatcher</strong> class is what you need.</p>\n\n<pre><code>FileSystemWatcher watcher = new FileSystemWatcher(\"c:filename.txt\");\nwatcher.Changed += new FileSystemEventHandler(watcher_Changed);\n// \nvoid watcher_Changed(object sender, FileSystemEventArgs e)\n{\n // put a breakpoint here\n}\n</code></pre>\n"
},
{
"answer_id": 193381,
"author": "Enrico Murru",
"author_id": 68336,
"author_profile": "https://Stackoverflow.com/users/68336",
"pm_score": 3,
"selected": true,
"text": "<p>you can use the System.IO.FileSystemWatcher class.</p>\n\n<pre><code>FileSystemWatcher watcher = = new FileSystemWatcher();\nwatcher.Filter = @\"myFile.ini\";\nwatcher.Changed += new FileSystemEventHandler(watcher_Changed);\n</code></pre>\n\n<p>and then you implement the delegate of type FileSystemEventHandler:</p>\n\n<pre><code>static void watcher_Changed(object sender, FileSystemArgs e)\n{\n Console.WriteLine(\"File {0} has changed.\", e.FullPath );\n}\n</code></pre>\n\n<p>every time the file you have selected in the filter is modified, you get an alert (you can use both a Debug class or Trace class to output data).\nMoreover the FileSystemWatcher class has more events (Renamed, Deleted, Created).</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19263/"
] |
Is it possible to break at runtime when a particular file has been modified?
ie. monitor the file and break into a debugger once a change has been made to it.
This is for a windows app...is this possible in visual studio or windbg?
edit: i should have mentioned that this is for a Win32 app..
|
you can use the System.IO.FileSystemWatcher class.
```
FileSystemWatcher watcher = = new FileSystemWatcher();
watcher.Filter = @"myFile.ini";
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
```
and then you implement the delegate of type FileSystemEventHandler:
```
static void watcher_Changed(object sender, FileSystemArgs e)
{
Console.WriteLine("File {0} has changed.", e.FullPath );
}
```
every time the file you have selected in the filter is modified, you get an alert (you can use both a Debug class or Trace class to output data).
Moreover the FileSystemWatcher class has more events (Renamed, Deleted, Created).
|
193,398 |
<p>Is there an algorithm for accurately multiplying two arbitrarily long integers together? The language I am working with is limited to 64-bit unsigned integer length (maximum integer size of 18446744073709551615). Realistically, I would like to be able to do this by breaking up each number, processing them somehow using the unsigned 64-bit integers, and then being able to put them back together in to a string (which would solve the issue of multiplied result storage).</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 193411,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, you do it using a datatype that is effectively a string of digits (just like a normal 'string' is a string of characters). How you do this is highly language-dependent. For instance, Java uses BigDecimal. What language are you using?</p>\n"
},
{
"answer_id": 193412,
"author": "ejgottl",
"author_id": 9808,
"author_profile": "https://Stackoverflow.com/users/9808",
"pm_score": 2,
"selected": false,
"text": "<p>This is often given as a homework assignment. The algorithm you learned in grade school will work. Use a library (several are mentioned in other posts) if you need this for a real application.</p>\n"
},
{
"answer_id": 193416,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 5,
"selected": true,
"text": "<p>Most languages have functions or libraries that do this, usually called a Bignum library (<a href=\"http://gmplib.org/\" rel=\"noreferrer\">GMP</a> is a good one.)</p>\n\n<p>If you want to do it yourself, I would do it the same way that people do long multiplication on paper. To do this you could either work with strings containing the number, or do it in binary using bitwise operations.</p>\n\n<p>Example:</p>\n\n<pre><code> 45\n x67\n ---\n 315\n+270\n----\n 585\n</code></pre>\n\n<p>Or in binary:</p>\n\n<pre><code> 101\n x101\n ----\n 101\n 000\n+101\n------\n 11001\n</code></pre>\n\n<p><strong>Edit:</strong> After doing it in binary I realized that it would be much simpler (and faster of course) to code using bitwise operations instead of strings containing the base-10 numbers. I've edited my binary multiplying example to show a pattern: for each 1-bit in the bottom number, add the top number, bit-shifted left <em>the position of the 1-bit</em> times to a variable. At the end, that variable will contain the product.</p>\n\n<p>To store the product, you'll have to have two 64-bit numbers and imagine one of them being the first 64 bits and the other one the second 64 bits of the product. You'll have to write code that carries the addition from bit 63 of the second number to bit 0 of the first number.</p>\n"
},
{
"answer_id": 193690,
"author": "Procedural Throwback",
"author_id": 24404,
"author_profile": "https://Stackoverflow.com/users/24404",
"pm_score": 2,
"selected": false,
"text": "<p>The simplest way would be to use the schoolbook mechanism, splitting your arbitrarily sized numbers into chunks of 32-bit each.</p>\n\n<p>Given A B C D * E F G H (each chunk 32-bit, for a total 128 bit)<br>\n You need an output array 9 dwords wide.\n Set Out[0..8] to 0 </p>\n\n<p>You'd start by doing: H * D + out[8] => 64 bit result.<br>\n Store the low 32-bits in out[8] and take the high 32-bits as carry<br>\n Next: (H * C) + out[7] + carry<br>\n Again, store low 32-bit in out[7], use the high 32-bits as carry<br>\n after doing H*A + out[4] + carry, you need to continue looping until you have no carry.</p>\n\n<p>Then repeat with G, F, E.<br>\n For G, you'd start at out[7] instead of out[8], and so forth. </p>\n\n<p>Finally, walk through and convert the large integer into digits (which will require a \"divide large number by a single word\" routine)</p>\n"
},
{
"answer_id": 193915,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 3,
"selected": false,
"text": "<p>If you can't use an existing bignum library like GMP, check out <a href=\"http://en.wikipedia.org/wiki/Multiplication_algorithm#Multiplication_algorithms_for_computer_algebra\" rel=\"noreferrer\">Wikipedia's article on binary multiplication with computers</a>. There are a number of good, efficient algorithms for this.</p>\n"
},
{
"answer_id": 18036443,
"author": "ron",
"author_id": 2649254,
"author_profile": "https://Stackoverflow.com/users/2649254",
"pm_score": 1,
"selected": false,
"text": "<p>Here is my code piece in C. Good old multiply method</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>char *multiply(char s1[], char s2[]) {\n int l1 = strlen(s1);\n int l2 = strlen(s2);\n int i, j, k = 0, c = 0;\n char *r = (char *) malloc (l1+l2+1); // add one byte for the zero terminating string\n int temp;\n\n strrev(s1);\n strrev(s2);\n for (i = 0;i <l1+l2; i++) {\n r[i] = 0 + '0';\n }\n\n for (i = 0; i <l1; i ++) {\n c = 0; k = i;\n for (j = 0; j < l2; j++) {\n temp = get_int(s1[i]) * get_int(s2[j]);\n temp = temp + c + get_int(r[k]);\n c = temp /10;\n r[k] = temp%10 + '0';\n\n k++;\n }\n if (c!=0) {\n r[k] = c + '0';\n k++;\n }\n }\n\n r[k] = '\\0';\n strrev(r);\n return r;\n}\n</code></pre>\n"
},
{
"answer_id": 52869819,
"author": "Pianistprogrammer",
"author_id": 5546672,
"author_profile": "https://Stackoverflow.com/users/5546672",
"pm_score": 1,
"selected": false,
"text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> //Here is a JavaScript version of an Karatsuba Algorithm running with less time than the usual multiplication method\r\n \r\n function range(start, stop, step) {\r\n if (typeof stop == 'undefined') {\r\n // one param defined\r\n stop = start;\r\n start = 0;\r\n }\r\n if (typeof step == 'undefined') {\r\n step = 1;\r\n }\r\n if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {\r\n return [];\r\n }\r\n var result = [];\r\n for (var i = start; step > 0 ? i < stop : i > stop; i += step) {\r\n result.push(i);\r\n }\r\n return result;\r\n };\r\n function zeroPad(numberString, zeros, left = true) {\r\n //Return the string with zeros added to the left or right.\r\n for (var i in range(zeros)) {\r\n if (left)\r\n numberString = '0' + numberString\r\n else\r\n numberString = numberString + '0'\r\n }\r\n \r\n return numberString\r\n }\r\n function largeMultiplication(x, y) {\r\n x = x.toString();\r\n y = y.toString();\r\n \r\n if (x.length == 1 && y.length == 1)\r\n return parseInt(x) * parseInt(y)\r\n \r\n if (x.length < y.length)\r\n x = zeroPad(x, y.length - x.length);\r\n \r\n else\r\n y = zeroPad(y, x.length - y.length);\r\n \r\n n = x.length\r\n j = Math.floor(n/2);\r\n \r\n //for odd digit integers\r\n if ( n % 2 != 0)\r\n j += 1 \r\n var BZeroPadding = n - j\r\n var AZeroPadding = BZeroPadding * 2\r\n \r\n a = parseInt(x.substring(0,j));\r\n b = parseInt(x.substring(j));\r\n c = parseInt(y.substring(0,j));\r\n d = parseInt(y.substring(j));\r\n \r\n //recursively calculate\r\n ac = largeMultiplication(a, c)\r\n bd = largeMultiplication(b, d)\r\n k = largeMultiplication(a + b, c + d)\r\n A = parseInt(zeroPad(ac.toString(), AZeroPadding, false))\r\n B = parseInt(zeroPad((k - ac - bd).toString(), BZeroPadding, false))\r\n return A + B + bd\r\n }\r\n //testing the function here\r\n example = largeMultiplication(12, 34)\r\n console.log(example)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/193398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14322/"
] |
Is there an algorithm for accurately multiplying two arbitrarily long integers together? The language I am working with is limited to 64-bit unsigned integer length (maximum integer size of 18446744073709551615). Realistically, I would like to be able to do this by breaking up each number, processing them somehow using the unsigned 64-bit integers, and then being able to put them back together in to a string (which would solve the issue of multiplied result storage).
Any ideas?
|
Most languages have functions or libraries that do this, usually called a Bignum library ([GMP](http://gmplib.org/) is a good one.)
If you want to do it yourself, I would do it the same way that people do long multiplication on paper. To do this you could either work with strings containing the number, or do it in binary using bitwise operations.
Example:
```
45
x67
---
315
+270
----
585
```
Or in binary:
```
101
x101
----
101
000
+101
------
11001
```
**Edit:** After doing it in binary I realized that it would be much simpler (and faster of course) to code using bitwise operations instead of strings containing the base-10 numbers. I've edited my binary multiplying example to show a pattern: for each 1-bit in the bottom number, add the top number, bit-shifted left *the position of the 1-bit* times to a variable. At the end, that variable will contain the product.
To store the product, you'll have to have two 64-bit numbers and imagine one of them being the first 64 bits and the other one the second 64 bits of the product. You'll have to write code that carries the addition from bit 63 of the second number to bit 0 of the first number.
|
193,440 |
<pre><code>func()
{
Object* pNext;
func1(pNext);
}
func1(Object* pNext)
{
pNext = Segement->GetFirstPara(0);
}
</code></pre>
<p>I was expecting it to be pointer to firstpara returned from func1() but I'm seeing NULL can some explain and how to fix it to actually return the firstpara() pointer?</p>
|
[
{
"answer_id": 193450,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 2,
"selected": false,
"text": "<p>To change a pointer, you need to pass a pointer to the pointer, ie <code>Object** pNext</code>. To change the value of a variable inside a function, you pass a pointer. Hence, by extension, to change the value of a pointer inside a function, pass a pointer to the pointer.</p>\n\n<pre><code>func() { \n Object* pNext;\n func1(&pNext);\n}\n\nfunc1(Object** pNext) { *pNext = Segement->GetFirstPara(0); }\n</code></pre>\n"
},
{
"answer_id": 193454,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 0,
"selected": false,
"text": "<p>It should be</p>\n\n<pre><code>\nfunc()\n{\n Object *pNext;\n func1(&pNext);\n}\n\nvoid func1(Object **pNext)\n{\n *pNext = Segment->GetFirstPara(0);\n}\n</code></pre>\n"
},
{
"answer_id": 193455,
"author": "ejgottl",
"author_id": 9808,
"author_profile": "https://Stackoverflow.com/users/9808",
"pm_score": 3,
"selected": false,
"text": "<p>In c, you would want:</p>\n\n<pre><code>func1(&pNext);\nfunc1(Object** pNext) { *pNext = ... }\n</code></pre>\n\n<p>In C++</p>\n\n<pre><code>func1(pNext);\nfunc1(Object*& pNext) { pNext = ... }\n</code></pre>\n\n<p>In either language, your example would pass an uninitialized <code>Object*</code> to <code>func1</code>, which would copy it, assign a value to the copy and then return. Note that the original pNext never gets modified (it would help if you used different names for your variables).</p>\n\n<p>In both languages you need to explicitly pass references if pass-by-reference rather than pass-by-value is desired.</p>\n"
},
{
"answer_id": 193461,
"author": "Diastrophism",
"author_id": 18093,
"author_profile": "https://Stackoverflow.com/users/18093",
"pm_score": 4,
"selected": false,
"text": "<p>For C++ only, you can make the parameter a reference</p>\n\n<pre><code>func()\n{\n Object* pNext;\n func1(pNext);\n}\n\nfunc1(Object*& pNext)\n{\n pNext = Segement->GetFirstPara(0);\n}\n</code></pre>\n\n<p>What is going on here is the difference between passing parameters by value and passing by reference. C always passes by value. In order to get a value back, the value needs to be a reference value (e.g. Object** refers to Object* as a pointer). C++ adds reference parameters (signified by the &).\nPass by value only passes a copy of the data and never the actual data itself. That is why the variable used in the function call was not updated in the function.</p>\n"
},
{
"answer_id": 194043,
"author": "John Dibling",
"author_id": 241536,
"author_profile": "https://Stackoverflow.com/users/241536",
"pm_score": 1,
"selected": false,
"text": "<p>Please initialize pNext when you instantiate it. It might be NULL now when you're debugging, but in the field it will be 0x12AbD468, or something. The if you have a test like:</p>\n\n<pre><code>if( NULL != pNext )\n{\n pNext->DoSomething();\n}\n</code></pre>\n\n<p>...and your program will explode, users will get mad, call support and somehow get your phone extension, call you directly and give you an earful.</p>\n\n<p>In your case, since 'func1()' doesnt use pNext as an in-parameter, you can simply return it from the function:</p>\n\n<pre><code>func()\n{\n Object *pNext = func1();\n}\n\nObject* func1()\n{\n return Segment->GetFirstPara(0);\n}\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22535/"
] |
```
func()
{
Object* pNext;
func1(pNext);
}
func1(Object* pNext)
{
pNext = Segement->GetFirstPara(0);
}
```
I was expecting it to be pointer to firstpara returned from func1() but I'm seeing NULL can some explain and how to fix it to actually return the firstpara() pointer?
|
For C++ only, you can make the parameter a reference
```
func()
{
Object* pNext;
func1(pNext);
}
func1(Object*& pNext)
{
pNext = Segement->GetFirstPara(0);
}
```
What is going on here is the difference between passing parameters by value and passing by reference. C always passes by value. In order to get a value back, the value needs to be a reference value (e.g. Object\*\* refers to Object\* as a pointer). C++ adds reference parameters (signified by the &).
Pass by value only passes a copy of the data and never the actual data itself. That is why the variable used in the function call was not updated in the function.
|
193,457 |
<p>I have subclassed <a href="https://docs.oracle.com/javase/9/docs/api/java/awt/Frame.html" rel="nofollow noreferrer"><code>java.awt.Frame</code></a> and have overridden the <a href="https://docs.oracle.com/javase/9/docs/api/java/awt/Window.html#paint-java.awt.Graphics-" rel="nofollow noreferrer"><code>paint()</code></a> method as I wish to draw the entire contents of the window manually.</p>
<p>However, on the graphics object, (0,0) corresponds to the upper left hand corner of the window <strong>inside</strong> the title bar decoration, not the first drawable pixel.</p>
<p>Can I determine the co-ordinate of the first drawable pixel (ie, the height of the decoration) in a cross-platform manner, avoiding using a Mac OS X-specific <a href="https://en.wikipedia.org/wiki/Fudge_factor" rel="nofollow noreferrer">fudge factor</a>? Will I be forced to nest a <a href="https://docs.oracle.com/javase/9/docs/api/java/awt/Panel.html" rel="nofollow noreferrer">Panel</a> component in order to find the actual drawable area of the window?</p>
<p>Here, my code fails to centre the blue square inside the paintable area of the window:</p>
<pre><code>@Override
public void paint (Graphics g) {
g.setColor(Color.BLUE);
g.setPaintMode();
g.fillRect(30, 30, getWidth()-60, getHeight()-60);
}
</code></pre>
|
[
{
"answer_id": 193450,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 2,
"selected": false,
"text": "<p>To change a pointer, you need to pass a pointer to the pointer, ie <code>Object** pNext</code>. To change the value of a variable inside a function, you pass a pointer. Hence, by extension, to change the value of a pointer inside a function, pass a pointer to the pointer.</p>\n\n<pre><code>func() { \n Object* pNext;\n func1(&pNext);\n}\n\nfunc1(Object** pNext) { *pNext = Segement->GetFirstPara(0); }\n</code></pre>\n"
},
{
"answer_id": 193454,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 0,
"selected": false,
"text": "<p>It should be</p>\n\n<pre><code>\nfunc()\n{\n Object *pNext;\n func1(&pNext);\n}\n\nvoid func1(Object **pNext)\n{\n *pNext = Segment->GetFirstPara(0);\n}\n</code></pre>\n"
},
{
"answer_id": 193455,
"author": "ejgottl",
"author_id": 9808,
"author_profile": "https://Stackoverflow.com/users/9808",
"pm_score": 3,
"selected": false,
"text": "<p>In c, you would want:</p>\n\n<pre><code>func1(&pNext);\nfunc1(Object** pNext) { *pNext = ... }\n</code></pre>\n\n<p>In C++</p>\n\n<pre><code>func1(pNext);\nfunc1(Object*& pNext) { pNext = ... }\n</code></pre>\n\n<p>In either language, your example would pass an uninitialized <code>Object*</code> to <code>func1</code>, which would copy it, assign a value to the copy and then return. Note that the original pNext never gets modified (it would help if you used different names for your variables).</p>\n\n<p>In both languages you need to explicitly pass references if pass-by-reference rather than pass-by-value is desired.</p>\n"
},
{
"answer_id": 193461,
"author": "Diastrophism",
"author_id": 18093,
"author_profile": "https://Stackoverflow.com/users/18093",
"pm_score": 4,
"selected": false,
"text": "<p>For C++ only, you can make the parameter a reference</p>\n\n<pre><code>func()\n{\n Object* pNext;\n func1(pNext);\n}\n\nfunc1(Object*& pNext)\n{\n pNext = Segement->GetFirstPara(0);\n}\n</code></pre>\n\n<p>What is going on here is the difference between passing parameters by value and passing by reference. C always passes by value. In order to get a value back, the value needs to be a reference value (e.g. Object** refers to Object* as a pointer). C++ adds reference parameters (signified by the &).\nPass by value only passes a copy of the data and never the actual data itself. That is why the variable used in the function call was not updated in the function.</p>\n"
},
{
"answer_id": 194043,
"author": "John Dibling",
"author_id": 241536,
"author_profile": "https://Stackoverflow.com/users/241536",
"pm_score": 1,
"selected": false,
"text": "<p>Please initialize pNext when you instantiate it. It might be NULL now when you're debugging, but in the field it will be 0x12AbD468, or something. The if you have a test like:</p>\n\n<pre><code>if( NULL != pNext )\n{\n pNext->DoSomething();\n}\n</code></pre>\n\n<p>...and your program will explode, users will get mad, call support and somehow get your phone extension, call you directly and give you an earful.</p>\n\n<p>In your case, since 'func1()' doesnt use pNext as an in-parameter, you can simply return it from the function:</p>\n\n<pre><code>func()\n{\n Object *pNext = func1();\n}\n\nObject* func1()\n{\n return Segment->GetFirstPara(0);\n}\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8779/"
] |
I have subclassed [`java.awt.Frame`](https://docs.oracle.com/javase/9/docs/api/java/awt/Frame.html) and have overridden the [`paint()`](https://docs.oracle.com/javase/9/docs/api/java/awt/Window.html#paint-java.awt.Graphics-) method as I wish to draw the entire contents of the window manually.
However, on the graphics object, (0,0) corresponds to the upper left hand corner of the window **inside** the title bar decoration, not the first drawable pixel.
Can I determine the co-ordinate of the first drawable pixel (ie, the height of the decoration) in a cross-platform manner, avoiding using a Mac OS X-specific [fudge factor](https://en.wikipedia.org/wiki/Fudge_factor)? Will I be forced to nest a [Panel](https://docs.oracle.com/javase/9/docs/api/java/awt/Panel.html) component in order to find the actual drawable area of the window?
Here, my code fails to centre the blue square inside the paintable area of the window:
```
@Override
public void paint (Graphics g) {
g.setColor(Color.BLUE);
g.setPaintMode();
g.fillRect(30, 30, getWidth()-60, getHeight()-60);
}
```
|
For C++ only, you can make the parameter a reference
```
func()
{
Object* pNext;
func1(pNext);
}
func1(Object*& pNext)
{
pNext = Segement->GetFirstPara(0);
}
```
What is going on here is the difference between passing parameters by value and passing by reference. C always passes by value. In order to get a value back, the value needs to be a reference value (e.g. Object\*\* refers to Object\* as a pointer). C++ adds reference parameters (signified by the &).
Pass by value only passes a copy of the data and never the actual data itself. That is why the variable used in the function call was not updated in the function.
|
193,471 |
<p>As I recall <code>BOOST_MPL_ASSERT</code> was once preferred. Is this still true? Anyone know why?</p>
|
[
{
"answer_id": 193592,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 2,
"selected": false,
"text": "<p><code>BOOST_MPL_ASSERT</code> is (still) generally considered better. The messages from it are somewhat easier to see (and understand, if you use <code>BOOST_MPL_ASSERT_MSG</code>). There was some talk a few months ago about deprecating <code>BOOST_STATIC_ASSERT</code>, though I think everyone eventually agreed that there's still room for it in the world.</p>\n"
},
{
"answer_id": 687302,
"author": "jwfearn",
"author_id": 10559,
"author_profile": "https://Stackoverflow.com/users/10559",
"pm_score": 5,
"selected": true,
"text": "<p><em>[Answering my own question]</em></p>\n\n<p>It depends. This is an apples to oranges comparison. Although similar, these macros are NOT interchangeable. Here's a summary of how each works:</p>\n\n<p><code>BOOST_STATIC_ASSERT( P )</code> generates a compilation error if <code>P != true</code>.</p>\n\n<p><code>BOOST_MPL_ASSERT(( P ))</code> generates a compilation error if <code>P::type::value != true</code>.</p>\n\n<p>The latter form, despite <em>requiring double parentheses</em>, is especially useful because it can generate more informative error messages <em>if</em> one uses <em>Boolean nullary Metafunctions</em> from Boost.MPL or TR1's <code><type_traits></code> as predicates.</p>\n\n<p>Here is an example program that demonstrates how to use (and misuse) these macros:</p>\n\n<pre><code>#include <boost/static_assert.hpp>\n#include <boost/mpl/assert.hpp>\n#include <type_traits>\nusing namespace ::boost::mpl;\nusing namespace ::std::tr1;\n\nstruct A {};\nstruct Z {};\n\nint main() {\n // boolean predicates\n BOOST_STATIC_ASSERT( true ); // OK\n BOOST_STATIC_ASSERT( false ); // assert\n// BOOST_MPL_ASSERT( false ); // syntax error!\n// BOOST_MPL_ASSERT(( false )); // syntax error!\n BOOST_MPL_ASSERT(( bool_< true > )); // OK\n BOOST_MPL_ASSERT(( bool_< false > )); // assert\n\n // metafunction predicates\n BOOST_STATIC_ASSERT(( is_same< A, A >::type::value ));// OK\n BOOST_STATIC_ASSERT(( is_same< A, Z >::type::value ));// assert, line 19\n BOOST_MPL_ASSERT(( is_same< A, A > )); // OK\n BOOST_MPL_ASSERT(( is_same< A, Z > )); // assert, line 21\n return 0;\n}\n</code></pre>\n\n<p>For comparison, here are the error messages my compiler (Microsoft Visual C++ 2008) generated for lines 19 and 21 above:</p>\n\n<pre><code>1>static_assert.cpp(19) : error C2027: use of undefined type 'boost::STATIC_ASSERTION_FAILURE<x>'\n1> with\n1> [\n1> x=false\n1> ]\n1>static_assert.cpp(21) : error C2664: 'boost::mpl::assertion_failed' : cannot convert parameter 1 from 'boost::mpl::failed ************std::tr1::is_same<_Ty1,_Ty2>::* ***********' to 'boost::mpl::assert<false>::type'\n1> with\n1> [\n1> _Ty1=A,\n1> _Ty2=Z\n1> ]\n1> No constructor could take the source type, or constructor overload resolution was ambiguous\n</code></pre>\n\n<p>So if you're using metafunctions (as defined <a href=\"http://www.boost.org/doc/libs/1_38_0/libs/mpl/doc/refmanual/metafunction.html\" rel=\"noreferrer\">here</a>) as predicates then <code>BOOST_MPL_ASSERT</code> is both less verbose to code and more informative when it asserts.</p>\n\n<p>For simple boolean predicates, <code>BOOST_STATIC_ASSERT</code> is less verbose to code although its error messages may be less clear (depending on your compiler.)</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10559/"
] |
As I recall `BOOST_MPL_ASSERT` was once preferred. Is this still true? Anyone know why?
|
*[Answering my own question]*
It depends. This is an apples to oranges comparison. Although similar, these macros are NOT interchangeable. Here's a summary of how each works:
`BOOST_STATIC_ASSERT( P )` generates a compilation error if `P != true`.
`BOOST_MPL_ASSERT(( P ))` generates a compilation error if `P::type::value != true`.
The latter form, despite *requiring double parentheses*, is especially useful because it can generate more informative error messages *if* one uses *Boolean nullary Metafunctions* from Boost.MPL or TR1's `<type_traits>` as predicates.
Here is an example program that demonstrates how to use (and misuse) these macros:
```
#include <boost/static_assert.hpp>
#include <boost/mpl/assert.hpp>
#include <type_traits>
using namespace ::boost::mpl;
using namespace ::std::tr1;
struct A {};
struct Z {};
int main() {
// boolean predicates
BOOST_STATIC_ASSERT( true ); // OK
BOOST_STATIC_ASSERT( false ); // assert
// BOOST_MPL_ASSERT( false ); // syntax error!
// BOOST_MPL_ASSERT(( false )); // syntax error!
BOOST_MPL_ASSERT(( bool_< true > )); // OK
BOOST_MPL_ASSERT(( bool_< false > )); // assert
// metafunction predicates
BOOST_STATIC_ASSERT(( is_same< A, A >::type::value ));// OK
BOOST_STATIC_ASSERT(( is_same< A, Z >::type::value ));// assert, line 19
BOOST_MPL_ASSERT(( is_same< A, A > )); // OK
BOOST_MPL_ASSERT(( is_same< A, Z > )); // assert, line 21
return 0;
}
```
For comparison, here are the error messages my compiler (Microsoft Visual C++ 2008) generated for lines 19 and 21 above:
```
1>static_assert.cpp(19) : error C2027: use of undefined type 'boost::STATIC_ASSERTION_FAILURE<x>'
1> with
1> [
1> x=false
1> ]
1>static_assert.cpp(21) : error C2664: 'boost::mpl::assertion_failed' : cannot convert parameter 1 from 'boost::mpl::failed ************std::tr1::is_same<_Ty1,_Ty2>::* ***********' to 'boost::mpl::assert<false>::type'
1> with
1> [
1> _Ty1=A,
1> _Ty2=Z
1> ]
1> No constructor could take the source type, or constructor overload resolution was ambiguous
```
So if you're using metafunctions (as defined [here](http://www.boost.org/doc/libs/1_38_0/libs/mpl/doc/refmanual/metafunction.html)) as predicates then `BOOST_MPL_ASSERT` is both less verbose to code and more informative when it asserts.
For simple boolean predicates, `BOOST_STATIC_ASSERT` is less verbose to code although its error messages may be less clear (depending on your compiler.)
|
193,474 |
<p>I want to create an ini file to store some settings for my application. Is it a good idea to find where the jar file is located and create an ini file there? If yes, then how can I find the location of the jar file? </p>
<p>But if you know a better solution for something like this, I would like to hear some of them.</p>
<p><strong>EDIT</strong>: I'm using mac and I want to run the same application in windows. I could write something in the System.getProperty("user.home") directory, but I want to keep the system clean, if the user decides to remove the app. There is no a better way to store the settings file, for example in the same directory with the application?</p>
|
[
{
"answer_id": 193479,
"author": "BoltBait",
"author_id": 20848,
"author_profile": "https://Stackoverflow.com/users/20848",
"pm_score": 1,
"selected": false,
"text": "<p>You should not be storing temp files in the install directory of an application. Remember, the user running the application may not have write access to that directory. The safest place to put stuff like that is in C:\\Documents and Settings\\username\\Application Data\\ApplicationName folder (adjusting the name as necessary).</p>\n\n<p>That said, however, I would probably store that type of stuff in the registry instead of a file on their computer. (But, that's just me.)</p>\n"
},
{
"answer_id": 193480,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 1,
"selected": false,
"text": "<p>It depends whether your ini needs to be human readable/writable under normal circumstances. If not, you can use a properties file rather than an ini file, and store it in the \"user\" directory.</p>\n\n<p>As for finding the jar file, you would have to find the ClassLoader for a class known to be loaded from the jar, check that it was the appropriate type of ClassLoader (ie that it's <em>really</em> been loaded from a jar), and you can extract the path from that. I can probably dig out the code to do this if that's really what you want. I wouldn't necessarily recommend it.</p>\n\n<p><strong>EDIT</strong> The user.home property will give you the user directory, which you can safely use.</p>\n"
},
{
"answer_id": 193486,
"author": "Chris Boran",
"author_id": 25660,
"author_profile": "https://Stackoverflow.com/users/25660",
"pm_score": 1,
"selected": false,
"text": "<p>Typically Java programmers don't use .ini files, but .properties files (different format). You can use the java.lang.Properties class as a nice programmatic wrapper if you do. </p>\n\n<p>While you <strong>can</strong> get the location of your jar file by calling getProtectionDomain().getCodeSource().getLocation() on your class's .class member, I <strong>do not</strong> recommend that you do this. </p>\n\n<p>I would instead write the file to the System.getProperty(\"user.home\") directory - the users' home directory, or if it is truly temporary, System.getProperty(\"java.io.tmpdir\") </p>\n"
},
{
"answer_id": 193987,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 6,
"selected": true,
"text": "<p>You can locate your application directory using the ClassLoader. See: <a href=\"http://illegalargumentexception.blogspot.com/2008/04/java-finding-application-directory.html\" rel=\"noreferrer\">Java: finding the application directory</a>. Rather than an <em>.INI</em> file, use a <em>.properties</em> file - you can load and save this via the <a href=\"http://java.sun.com/javase/6/docs/api/java/util/Properties.html\" rel=\"noreferrer\">Properties</a> class.</p>\n\n<p>As others have noted, you should not write user settings to your application directory. What if the user does not have write access to the application directory? What if your application is being used by multiple users on the same system at the same time? Neither of these situations are unusual, even on Windows.</p>\n\n<p>You might still want to load some settings from the application directory - perhaps the administrator has configured default settings there.</p>\n\n<p>A common convention is to save user settings to the user's home directory:</p>\n\n<pre><code>/home/user/.eclipse\nC:\\Documents and Settings\\User\\.eclipse\n</code></pre>\n\n<p>Although this means you might leave stray files behind, this can be beneficial if the user re-installs the app. Document such things in a README. Here is how to create and get a reference to the directory:</p>\n\n<pre><code>public static File getSettingsDirectory() {\n String userHome = System.getProperty(\"user.home\");\n if(userHome == null) {\n throw new IllegalStateException(\"user.home==null\");\n }\n File home = new File(userHome);\n File settingsDirectory = new File(home, \".myappdir\");\n if(!settingsDirectory.exists()) {\n if(!settingsDirectory.mkdir()) {\n throw new IllegalStateException(settingsDirectory.toString());\n }\n }\n return settingsDirectory;\n}\n</code></pre>\n\n<p>On unix-like operating systems, starting the directory name with a period (\".myappdir\") will make the directory hidden. On Windows, it will be located below <em>My Documents</em>, so users will not see the directory unless they go looking for it.</p>\n"
},
{
"answer_id": 194010,
"author": "Dan Dyer",
"author_id": 5171,
"author_profile": "https://Stackoverflow.com/users/5171",
"pm_score": 3,
"selected": false,
"text": "<p>If the settings are only written by your application (rather than edited manually), consider using the <a href=\"http://docs.oracle.com/javase/8/docs/technotes/guides/preferences/index.html\" rel=\"nofollow noreferrer\">Preferences API</a>.</p>\n"
},
{
"answer_id": 8930384,
"author": "Radu Murzea",
"author_id": 995822,
"author_profile": "https://Stackoverflow.com/users/995822",
"pm_score": 1,
"selected": false,
"text": "<p>The idea with the .properties file instead of the INI file is good. Also, if you store some sensitive data in there, you may consider encrypting it. Check this out:</p>\n\n<p><a href=\"https://www.owasp.org/index.php/How_to_encrypt_a_properties_file\" rel=\"nofollow noreferrer\">https://www.owasp.org/index.php/How_to_encrypt_a_properties_file</a></p>\n\n<p>or this:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/3769622/encrypt-and-decrypt-property-file-value-in-java\">encrypt and decrypt property file value in java</a></p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8418/"
] |
I want to create an ini file to store some settings for my application. Is it a good idea to find where the jar file is located and create an ini file there? If yes, then how can I find the location of the jar file?
But if you know a better solution for something like this, I would like to hear some of them.
**EDIT**: I'm using mac and I want to run the same application in windows. I could write something in the System.getProperty("user.home") directory, but I want to keep the system clean, if the user decides to remove the app. There is no a better way to store the settings file, for example in the same directory with the application?
|
You can locate your application directory using the ClassLoader. See: [Java: finding the application directory](http://illegalargumentexception.blogspot.com/2008/04/java-finding-application-directory.html). Rather than an *.INI* file, use a *.properties* file - you can load and save this via the [Properties](http://java.sun.com/javase/6/docs/api/java/util/Properties.html) class.
As others have noted, you should not write user settings to your application directory. What if the user does not have write access to the application directory? What if your application is being used by multiple users on the same system at the same time? Neither of these situations are unusual, even on Windows.
You might still want to load some settings from the application directory - perhaps the administrator has configured default settings there.
A common convention is to save user settings to the user's home directory:
```
/home/user/.eclipse
C:\Documents and Settings\User\.eclipse
```
Although this means you might leave stray files behind, this can be beneficial if the user re-installs the app. Document such things in a README. Here is how to create and get a reference to the directory:
```
public static File getSettingsDirectory() {
String userHome = System.getProperty("user.home");
if(userHome == null) {
throw new IllegalStateException("user.home==null");
}
File home = new File(userHome);
File settingsDirectory = new File(home, ".myappdir");
if(!settingsDirectory.exists()) {
if(!settingsDirectory.mkdir()) {
throw new IllegalStateException(settingsDirectory.toString());
}
}
return settingsDirectory;
}
```
On unix-like operating systems, starting the directory name with a period (".myappdir") will make the directory hidden. On Windows, it will be located below *My Documents*, so users will not see the directory unless they go looking for it.
|
193,483 |
<p>When using Maven to build an executable JAR, how do I specify the JVM arguments that are used when the JAR is executed?</p>
<p>I can specify the main class using <code><mainClass></code>. I suspect there's a similar attribute for JVM arguments. Specially I need to specify the maximum memory (example -Xmx500m).</p>
<p>Here's my assembly plugin:</p>
<pre><code> <plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.me.myApplication</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</code></pre>
<p>Edit/Follow-up: It seems that it might not be possible to specify JVM arguments for an executable JAR according to <a href="http://forums.sun.com/thread.jspa?threadID=633125&messageID=3667132" rel="noreferrer">this</a> and <a href="http://www.javalobby.org/forums/thread.jspa?threadID=15486&tstart=0#91817576" rel="noreferrer">this</a> post.</p>
|
[
{
"answer_id": 195007,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 4,
"selected": true,
"text": "<p>I don't know of any such mechanism. The JVM configuration is specified by the calling java command. </p>\n\n<p>Here's the jar file specification which conspicuously doesn't mention any attribute other than Main-Class for stand-alone execution:</p>\n\n<p><a href=\"http://java.sun.com/javase/6/docs/technotes/guides/jar/jar.html\" rel=\"noreferrer\">http://java.sun.com/javase/6/docs/technotes/guides/jar/jar.html</a></p>\n"
},
{
"answer_id": 195815,
"author": "David Carlson",
"author_id": 4901,
"author_profile": "https://Stackoverflow.com/users/4901",
"pm_score": 2,
"selected": false,
"text": "<p>First off, let me say that anything this tricky is probably hard for a reason.</p>\n\n<p>This approach that may work for you if you really need it. As written, it assumes \"java\" is on the caller's path.</p>\n\n<p>Overview:</p>\n\n<ol>\n<li><p>Declare a Bootstrapper class as the main class in the jar's manifest. </p></li>\n<li><p>The bootstrapper spawns another process in which we call java (passing in any command-line arguments you want) on the \"real\" main class.</p></li>\n<li><p>Redirect the child processes System.out and System.err to the bootstrapper's respective streams</p></li>\n<li><p>Wait for the child process to finish</p></li>\n</ol>\n\n<p>Here's a <a href=\"http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html\" rel=\"nofollow noreferrer\">good background article</a>.</p>\n\n<p><strong>src/main/java/scratch/Bootstrap.java</strong> - this class is defined in pom.xml as\nthe jar's mainclass: <code><mainClass>scratch.Bootstrap</mainClass></code></p>\n\n<pre><code>package scratch;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.PrintStream;\n\npublic class Bootstrap {\n class StreamProxy extends Thread {\n final InputStream is;\n final PrintStream os;\n\n StreamProxy(InputStream is, PrintStream os) {\n this.is = is;\n this.os = os;\n }\n\n public void run() {\n try {\n InputStreamReader isr = new InputStreamReader(is);\n BufferedReader br = new BufferedReader(isr);\n String line = null;\n while ((line = br.readLine()) != null) {\n os.println(line);\n }\n } catch (IOException ex) {\n throw new RuntimeException(ex.getMessage(), ex);\n }\n }\n }\n\n private void go(){\n try {\n /*\n * Spin up a separate java process calling a non-default Main class in your Jar. \n */\n Process process = Runtime.getRuntime().exec(\"java -cp scratch-1.0-SNAPSHOT-jar-with-dependencies.jar -Xmx500m scratch.App\");\n\n /*\n * Proxy the System.out and System.err from the spawned process back to the user's window. This\n * is important or the spawned process could block.\n */\n StreamProxy errorStreamProxy = new StreamProxy(process.getErrorStream(), System.err);\n StreamProxy outStreamProxy = new StreamProxy(process.getInputStream(), System.out);\n\n errorStreamProxy.start();\n outStreamProxy.start();\n\n System.out.println(\"Exit:\" + process.waitFor());\n } catch (Exception ex) {\n System.out.println(\"There was a problem execting the program. Details:\");\n ex.printStackTrace(System.err);\n\n if(null != process){\n try{\n process.destroy();\n } catch (Exception e){\n System.err.println(\"Error destroying process: \"+e.getMessage());\n }\n }\n }\n }\n\n public static void main(String[] args) {\n new Bootstrap().go();\n }\n\n}\n</code></pre>\n\n<p><strong>src/main/java/scratch/App.java</strong> - this is the normal entry point for your program</p>\n\n<pre><code>package scratch;\n\npublic class App \n{\n public static void main( String[] args )\n {\n System.out.println( \"Hello World! maxMemory:\"+Runtime.getRuntime().maxMemory() );\n }\n}\n</code></pre>\n\n<p>Calling: <code>java -jar scratch-1.0-SNAPSHOT-jar-with-dependencies.jar</code>\nReturns:</p>\n\n<pre><code>Hello World! maxMemory:520290304\nExit:0\n</code></pre>\n"
},
{
"answer_id": 7848011,
"author": "Leonard Hagger",
"author_id": 1006883,
"author_profile": "https://Stackoverflow.com/users/1006883",
"pm_score": -1,
"selected": false,
"text": "<p>Ancient question but came up on my Google search for this exact problem so I'm answering it.</p>\n\n<p>Try </p>\n\n<pre><code><configuation>\n...\n<argLine> -Xmx500m </argLine>\n...\n</configuation>\n</code></pre>\n"
},
{
"answer_id": 16945702,
"author": "jgibson",
"author_id": 600441,
"author_profile": "https://Stackoverflow.com/users/600441",
"pm_score": 0,
"selected": false,
"text": "<p>In response to David Carlson's answer, you can make it less brittle by using the java.home system property to locate the java executable instead of relying on the user's path to find it. In addition you should probably be redirecting standard input to the child process as well.</p>\n"
},
{
"answer_id": 49866558,
"author": "Dmitriy Ryabin",
"author_id": 8340633,
"author_profile": "https://Stackoverflow.com/users/8340633",
"pm_score": 0,
"selected": false,
"text": "<p>I think this can be done if you think of it this way. \nGenerate a <code>.bat</code> file that will have a command:</p>\n\n<p><code>> java .. yourClass.. -D<jvmOption1> -D<jvmOption2>...</code></p>\n\n<p>You can try looking on this <a href=\"http://www.mojohaus.org/appassembler/appassembler-maven-plugin/usage-program-jvmsettings.html\" rel=\"nofollow noreferrer\">app assembler plugin</a> for maven.</p>\n\n<p>I tried it, and seems to work. I am still not clear how to make .bat file to be generated with the somewhat different content, but I think it is doable.</p>\n\n<p>As another option, you may always try to create the .bat file in the resource sub folder of your project and include that sub folder with your distribution.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24396/"
] |
When using Maven to build an executable JAR, how do I specify the JVM arguments that are used when the JAR is executed?
I can specify the main class using `<mainClass>`. I suspect there's a similar attribute for JVM arguments. Specially I need to specify the maximum memory (example -Xmx500m).
Here's my assembly plugin:
```
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.me.myApplication</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
```
Edit/Follow-up: It seems that it might not be possible to specify JVM arguments for an executable JAR according to [this](http://forums.sun.com/thread.jspa?threadID=633125&messageID=3667132) and [this](http://www.javalobby.org/forums/thread.jspa?threadID=15486&tstart=0#91817576) post.
|
I don't know of any such mechanism. The JVM configuration is specified by the calling java command.
Here's the jar file specification which conspicuously doesn't mention any attribute other than Main-Class for stand-alone execution:
<http://java.sun.com/javase/6/docs/technotes/guides/jar/jar.html>
|
193,488 |
<p>I've just started tinkering with XML manipulation with PHP, and i've stumbled into something unexpected. Here's the XML i'm using as a test input:</p>
<pre><code><list>
<activity1> running </activity1>
<activity2> swimming </activity2>
<activity3> soccer </activity3>
</list>
</code></pre>
<p>Now, i was expecting that this PHP code would output 'activity1':</p>
<pre><code>$xmldoc = new DOMDocument();
$xmldoc->load('file.xml');
//the line below would make $root the <list> node
$root = $xmldoc->firstChild;
//the line below would make $cnode the first child
//of the <list> node, which is <activity1>
$cnode = $root->firstChild;
//this should output 'activity1'
echo 'element name: ' . $cnode->nodeName;
</code></pre>
<p>Instead, this code outputs #text. I could fix that by inserting a new line in the code, before printing the node name:</p>
<pre><code>$cnode = $cnode->nextSibling;
</code></pre>
<p>Now, i would have expected that to print 'activity2' instead, but is printing 'activity1'. What is going on?</p>
|
[
{
"answer_id": 193506,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 1,
"selected": false,
"text": "<p>The first <em>node</em> is the text (in this case whitespace) between the opening list tag and activity1 tag, the next <em>node</em> is the activity1 <em>element</em>. elements are not the same as nodes.</p>\n"
},
{
"answer_id": 193571,
"author": "Czimi",
"author_id": 3906,
"author_profile": "https://Stackoverflow.com/users/3906",
"pm_score": 1,
"selected": false,
"text": "<p>To get the behaviour you expected, you need to pass in LIBXML_NOBLANKS as the second parameter of your load() call</p>\n\n<pre><code><?php\n$xmldoc = new DOMDocument();\n$xmldoc->load('file.xml', LIBXML_NOBLANKS);\n?>\n</code></pre>\n"
},
{
"answer_id": 193736,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 0,
"selected": false,
"text": "<p>A note on Czimi's answer: removing whitespace-only nodes will not prevent you from having to check the type of node (whether it is an element, a text node, a comment...). In general if you're interested in only selecting element nodes, you'll want to do something like this:</p>\n\n<pre><code>while($nodeInQuestion->nodeType != 1 && $nodeInQuestion->nextSibling) {\n $nodeInQuestion = $nodeInQuestion->nextSibling;\n}\n</code></pre>\n\n<p>This is sort of pseudo-code. Obviously you'll need to handle failure somehow if you're looking for an element and reach the end of the parentNode's childNodes before you find it.</p>\n"
},
{
"answer_id": 194494,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 1,
"selected": false,
"text": "<p>If you use XPath to query your document, you don't need to worry about this kind of arcana. Use <code>DOMDocument::xpath_eval()</code> to evaluate the pattern <code>/list/*</code> and all you'll get back are the child elements of the top-level <code>list</code> element no matter what.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I've just started tinkering with XML manipulation with PHP, and i've stumbled into something unexpected. Here's the XML i'm using as a test input:
```
<list>
<activity1> running </activity1>
<activity2> swimming </activity2>
<activity3> soccer </activity3>
</list>
```
Now, i was expecting that this PHP code would output 'activity1':
```
$xmldoc = new DOMDocument();
$xmldoc->load('file.xml');
//the line below would make $root the <list> node
$root = $xmldoc->firstChild;
//the line below would make $cnode the first child
//of the <list> node, which is <activity1>
$cnode = $root->firstChild;
//this should output 'activity1'
echo 'element name: ' . $cnode->nodeName;
```
Instead, this code outputs #text. I could fix that by inserting a new line in the code, before printing the node name:
```
$cnode = $cnode->nextSibling;
```
Now, i would have expected that to print 'activity2' instead, but is printing 'activity1'. What is going on?
|
The first *node* is the text (in this case whitespace) between the opening list tag and activity1 tag, the next *node* is the activity1 *element*. elements are not the same as nodes.
|
193,499 |
<p>What's the easiest way to get the UTC offset in PHP, relative to the current (system) timezone?</p>
|
[
{
"answer_id": 193516,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://us.php.net/manual/en/function.timezone-offset-get.php\" rel=\"noreferrer\"><code>timezone_offset_get()</code></a></p>\n\n<pre><code>$this_tz_str = date_default_timezone_get();\n$this_tz = new DateTimeZone($this_tz_str);\n$now = new DateTime(\"now\", $this_tz);\n$offset = $this_tz->getOffset($now);\n</code></pre>\n\n<p>Untested, but should work</p>\n"
},
{
"answer_id": 193517,
"author": "Czimi",
"author_id": 3906,
"author_profile": "https://Stackoverflow.com/users/3906",
"pm_score": 8,
"selected": true,
"text": "<pre><code> date('Z');\n</code></pre>\n\n<p>returns the UTC offset in seconds.</p>\n"
},
{
"answer_id": 14173489,
"author": "Amr",
"author_id": 458204,
"author_profile": "https://Stackoverflow.com/users/458204",
"pm_score": -1,
"selected": false,
"text": "<p><code>date(\"Z\")</code> will return the UTC offset relative to the server timezone not the user's machine timezone. To get the user's machine timezone you could use the javascript <code>getTimezoneOffset()</code> function which returns the time difference between UTC time and local time, in minutes.</p>\n\n<pre><code><script type=\"text/javascript\">\n d = new Date();\n window.location.href = \"page.php?offset=\" + d.getTimezoneOffset();\n</script>\n</code></pre>\n\n<p>And in <code>page.php</code> which holds your php code, you can do whatever you want with that offset value. Or instead of redirecting to another page, you can send the offset value to your php script through Ajax, according to your needs.</p>\n"
},
{
"answer_id": 30735962,
"author": "Kenny",
"author_id": 810607,
"author_profile": "https://Stackoverflow.com/users/810607",
"pm_score": 4,
"selected": false,
"text": "<p>I did a slightly modified version of what Oscar did.</p>\n\n<pre><code>date_default_timezone_set('America/New_York');\n$utc_offset = date('Z') / 3600;\n</code></pre>\n\n<p>This gave me the offset from my timezone, EST, to UTC, in hours. </p>\n\n<p>The value of $utc_offset was -4.</p>\n"
},
{
"answer_id": 36021293,
"author": "Tuhin Bepari",
"author_id": 3046071,
"author_profile": "https://Stackoverflow.com/users/3046071",
"pm_score": 6,
"selected": false,
"text": "<pre><code>// will output something like +02:00 or -04:00\necho date('P');\n</code></pre>\n"
},
{
"answer_id": 44250551,
"author": "زياد",
"author_id": 6316770,
"author_profile": "https://Stackoverflow.com/users/6316770",
"pm_score": 3,
"selected": false,
"text": "<p>This is same JavaScript <code>date.getTimezoneOffset()</code> function:</p>\n\n<pre><code><?php\necho date('Z')/-60;\n?>\n</code></pre>\n"
},
{
"answer_id": 49455413,
"author": "HMagdy",
"author_id": 1665955,
"author_profile": "https://Stackoverflow.com/users/1665955",
"pm_score": 3,
"selected": false,
"text": "<p>Simply you can do this:</p>\n\n<pre><code>//Object oriented style\nfunction getUTCOffset_OOP($timezone)\n{\n $current = timezone_open($timezone);\n $utcTime = new \\DateTime('now', new \\DateTimeZone('UTC'));\n $offsetInSecs = $current->getOffset($utcTime);\n $hoursAndSec = gmdate('H:i', abs($offsetInSecs));\n return stripos($offsetInSecs, '-') === false ? \"+{$hoursAndSec}\" : \"-{$hoursAndSec}\";\n}\n\n//Procedural style\nfunction getUTCOffset($timezone)\n{\n $current = timezone_open($timezone);\n $utcTime = new \\DateTime('now', new \\DateTimeZone('UTC'));\n $offsetInSecs = timezone_offset_get( $current, $utcTime);\n $hoursAndSec = gmdate('H:i', abs($offsetInSecs));\n return stripos($offsetInSecs, '-') === false ? \"+{$hoursAndSec}\" : \"-{$hoursAndSec}\";\n}\n\n\n$timezone = 'America/Mexico_City';\n\necho \"Procedural style<br>\";\necho getUTCOffset($timezone); //-06:00\necho \"<br>\";\necho \"(UTC \" . getUTCOffset($timezone) . \") \" . $timezone; // (UTC -06:00) America/Mexico_City\necho \"<br>--------------<br>\";\necho \"Object oriented style<br>\";\necho getUTCOffset_OOP($timezone); //-06:00\necho \"<br>\";\necho \"(UTC \" . getUTCOffset_OOP($timezone) . \") \" . $timezone; // (UTC -06:00) America/Mexico_City\n</code></pre>\n"
},
{
"answer_id": 71776737,
"author": "Jesse",
"author_id": 10343144,
"author_profile": "https://Stackoverflow.com/users/10343144",
"pm_score": 2,
"selected": false,
"text": "<p>This will output something formatted as: <code>+0200</code> or <code>-0400</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>echo date('O');\n</code></pre>\n<p>This may be useful for a proper <a href=\"https://validator.w3.org/feed/docs/rss2.html\" rel=\"nofollow noreferrer\">RSS RFC822 format</a></p>\n<pre class=\"lang-xml prettyprint-override\"><code><pubDate>Sat, 07 Sep 2002 00:00:01 -0500</pubDate>\n</code></pre>\n<p>GMT offsets (like this) shouldn't use a colon (<code>+02:00</code> from <code>date('P');</code>).</p>\n<p>And, although it is acceptable for RSS RFC833, we don't want output like <code>PDT</code> and <code>CST</code> because these are arbitraty and "CST" can mean many things:</p>\n<ul>\n<li>CST = <a href=\"https://www.timeanddate.com/time/zones/cst\" rel=\"nofollow noreferrer\">Central Standard Time</a></li>\n<li>CST = <a href=\"https://www.timeanddate.com/time/zones/cst-china\" rel=\"nofollow noreferrer\">China Standard Time</a></li>\n<li>CST = <a href=\"https://www.timeanddate.com/time/zones/cst-cuba\" rel=\"nofollow noreferrer\">Cuba Standard Time</a></li>\n</ul>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/79/"
] |
What's the easiest way to get the UTC offset in PHP, relative to the current (system) timezone?
|
```
date('Z');
```
returns the UTC offset in seconds.
|
193,514 |
<p>There is another recent Project Euler question but I think this is a bit more specific (I'm only really interested in PHP based solutions) so I'm asking anyway.</p>
<p><a href="http://projecteuler.net/index.php?section=problems&id=5" rel="nofollow noreferrer">Question #5</a> tasks you with: "What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?"</p>
<p>Now, I have solved it twice. Once very inefficiently and once much more efficiently but I am still far away from an especially sophisticated answer (and I am not especially solid in math hence my brute force solution). I can see a couple of areas where I could improve this but I am wondering if any of you could demonstrate a more efficient solution to this problem. </p>
<p>*spoiler: Here is my less than optimal (7 seconds to run) but still tolerable solution (not sure what to do about the double $... just pretend you only see 1...</p>
<pre><code> function euler5(){
$x = 20;
for ($y = 1; $y < 20; $y++) {
if (!($x%$y)) {
} else {
$x+=20;
$y = 1;
}
}echo $x;
};
</code></pre>
|
[
{
"answer_id": 193521,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": false,
"text": "<p>Collect prime factors for all numbers between 1 and 20. Counting the maximal exponents of each prime factor, we have <code>16 = 2**4</code>, <code>9 = 3**2</code>, as well as 5, 7, 11, 13, 17, 19 (each appearing only once). Multiply the lot, and you have your answer.</p>\n"
},
{
"answer_id": 193532,
"author": "Jamie",
"author_id": 22748,
"author_profile": "https://Stackoverflow.com/users/22748",
"pm_score": 2,
"selected": false,
"text": "<p>Chris Jester-Young is right.</p>\n\n<p>In general if you wanted the smallest number that is evenly divisible by all of the numbers from 1 to N, you would want to find all the prime numbers from 2 to N, and for each one, find the greatest number of times it divides any number in the range. This can be calculated by finding the greatest power of the prime that's not greater than N.</p>\n\n<p>In the case of 20, as Chris pointed out, 2^4 is the greatest power of 2 not greater than 20, and 3^2 is the greatest power of 3 not greater than 20, and for all other primes, only the first power is not greater than 20.</p>\n"
},
{
"answer_id": 193566,
"author": "Czimi",
"author_id": 3906,
"author_profile": "https://Stackoverflow.com/users/3906",
"pm_score": 3,
"selected": true,
"text": "<p>in php it will look like this:</p>\n\n<pre><code><?php\nfunction gcd($a,$b) {\n while($a>0 && $b>0) {\n if($a>$b) $a=$a-$b; else $b=$b-$a; \n }\n if($a==0) return $b;\n return $a;\n}\nfunction euler5($i=20) {\n $euler=$x=1;\n while($x++<$i) {\n $euler*=$x/gcd($euler,$x);\n }\n return $euler;\n}\n\n?>\n</code></pre>\n\n<p>Its at least twice as fast than what you posted.</p>\n"
},
{
"answer_id": 193644,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 2,
"selected": false,
"text": "<p>You can remove some numbers that are divided with, for example 1 is unnecessary, all natural numbers are divisible by 1.you don’t need 2 either, and therefore, all numbers are divisible by multiples of 2 (4, 8, 16, etc) are divisible by 2, also. So the relevant numbers will be 11, 12, 13, 14, 15, 16, 17, 18, and 19.</p>\n\n<p>So: </p>\n\n<pre><code><?\nfunction eulerPuzzle()\n{\n $integers = array( 11,12,13,14,15,16,17,18,19 );\n\n for ($n = 20; 1; $n += 20 ) {\n foreach ($integers as $int) { \n if ( $n % $int ) { \n break; \n }\n if ( $int == 19 ) { \n die (\"Result:\" . $n); \n }\n }\n }\n}\n\neulerPuzzle();\n?>\n</code></pre>\n"
},
{
"answer_id": 193669,
"author": "Kirk Strauser",
"author_id": 32538,
"author_profile": "https://Stackoverflow.com/users/32538",
"pm_score": -1,
"selected": false,
"text": "<p>I know you said PHP, but here's my rough draft in Python.</p>\n\n<pre><code>#!/usr/bin/env python\n\nfrom operator import mul\n\ndef factor(n):\n factors = {}\n i = 2\n while i < n and n != 1:\n while n % i == 0:\n try:\n factors[i] += 1\n except KeyError:\n factors[i] = 1\n n = n / i\n i += 1\n if n != 1:\n factors[n] = 1\n return factors\n\nbase = {}\nfor i in range(2, 2000):\n for f, n in factor(i).items():\n try:\n base[f] = max(base[f], n)\n except KeyError:\n base[f] = n\n\nprint reduce(mul, [f**n for f, n in base.items()], 1)\n</code></pre>\n\n<p>It's not as elegant as I could have made it, but it calculates the least common multiple of the numbers from 2 to 2000 in .15s. If your iterative solution could process a billion candidates per second, it would take 10^849 years to finish.</p>\n\n<p>In other words, don't bother optimizing the wrong algorithm.</p>\n"
},
{
"answer_id": 475010,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre><code><?php\n$i=20;\nwhile ($i+=20) {\n for ($j=19;$j!==10;--$j){\n if ($i%$j) continue 2;\n }\n die (\"result: $i\\n\");\n}\n</code></pre>\n\n<p>Is the fastest and shortest php solution so far. About 1.4x faster than Czimi's on my comp. But check out the python solution, thats a nice algo.</p>\n"
},
{
"answer_id": 1010761,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Some people really over-think this...</p>\n\n<p>In Ruby:</p>\n\n<pre><code>puts 5*7*9*11*13*16*17*19\n</code></pre>\n"
},
{
"answer_id": 6262882,
"author": "Tjirp",
"author_id": 392851,
"author_profile": "https://Stackoverflow.com/users/392851",
"pm_score": 0,
"selected": false,
"text": "<p>@People doing simple math; I'm not sure if that is the goal of the exercise. You are to learn new languages and new ways to perform stuff. Just doing it by a calculator isn't the right way going about things.</p>\n\n<p>And I know this is a post in an old old thread but it still comes up in google results :)</p>\n\n<p>Doing it in code (PHP that is) I found this to be the fastest solution:</p>\n\n<pre><code>function eulerPuzzle() {\n $integers = array (11, 12, 13, 14, 15, 16, 17, 18, 19 );\n\n for($n = 2520; 1; $n += 2520) {\n foreach ( $integers as $int ) {\n if ($n % $int) {\n break;\n }\n if ($int == 19) {\n die ( \"Result:\" . $n );\n }\n }\n }\n}\n\neulerPuzzle ();\n</code></pre>\n\n<p>Yes, it's a modified piece from CMS. The main reason it is faster is because when you read the question, they already state that the lowest possible number for the first 10 integers is 2520. therefor, you can just increment by 2520 instead of 20. resulting in 126 times less loops</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11252/"
] |
There is another recent Project Euler question but I think this is a bit more specific (I'm only really interested in PHP based solutions) so I'm asking anyway.
[Question #5](http://projecteuler.net/index.php?section=problems&id=5) tasks you with: "What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?"
Now, I have solved it twice. Once very inefficiently and once much more efficiently but I am still far away from an especially sophisticated answer (and I am not especially solid in math hence my brute force solution). I can see a couple of areas where I could improve this but I am wondering if any of you could demonstrate a more efficient solution to this problem.
\*spoiler: Here is my less than optimal (7 seconds to run) but still tolerable solution (not sure what to do about the double $... just pretend you only see 1...
```
function euler5(){
$x = 20;
for ($y = 1; $y < 20; $y++) {
if (!($x%$y)) {
} else {
$x+=20;
$y = 1;
}
}echo $x;
};
```
|
in php it will look like this:
```
<?php
function gcd($a,$b) {
while($a>0 && $b>0) {
if($a>$b) $a=$a-$b; else $b=$b-$a;
}
if($a==0) return $b;
return $a;
}
function euler5($i=20) {
$euler=$x=1;
while($x++<$i) {
$euler*=$x/gcd($euler,$x);
}
return $euler;
}
?>
```
Its at least twice as fast than what you posted.
|
193,547 |
<p>I have stumbled into several methods of looping in JavaScript, what I like the most is:</p>
<pre><code>for(var i = 0; i < a.length; i++){
var element = a[i];
}
</code></pre>
<p>But as tested here (<a href="http://www.robertnyman.com/2008/04/11/javascript-loop-performance/" rel="noreferrer">http://www.robertnyman.com/2008/04/11/javascript-loop-performance/</a>), it should probably be written so that the length is only calculated once. </p>
<p>In jQuery there is a .each that you can stick a function. I like this a little better, because I don't have to type the array twice, like in the above solution. </p>
<p>If JavaScript supported macros it would be a piece of cake to roll your own, but sadly it does not. </p>
<p>So what do you guys use?</p>
|
[
{
"answer_id": 193553,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 2,
"selected": false,
"text": "<p>You could just always use a while loop, and compute the array limit before hand.</p>\n\n<pre><code>Var max = a.length-1;\nvar i = 0;\n\nwhile(i <= max)\n{\nvar element = a[i];\ni++;\n}\n</code></pre>\n"
},
{
"answer_id": 193563,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 6,
"selected": true,
"text": "<p>I've started using iterators where relevant. Performance is reasonable, however more importantly it allows you to encapsulate the looping logic:</p>\n\n<pre><code>function createIterator(x) {\n var i = 0;\n\n return function(){\n return x[i++];\n };\n}\n</code></pre>\n\n<p>Then to use:</p>\n\n<pre><code>var iterator=createIterator(['a','b','c','d','e','f','g']);\n\niterator();\n</code></pre>\n\n<p>returns \"a\";</p>\n\n<pre><code>iterator();\n</code></pre>\n\n<p>returns \"b\";</p>\n\n<p>and so on.</p>\n\n<p>To iterate the whole list and display each item:</p>\n\n<pre>\nvar current;\n\nwhile(current=iterator())\n{\n console.log(current);\n}\n</pre>\n\n<p>Be aware that the above is only acceptable for iterating a list that contains \"non-falsy\" values. If this array contained any of: </p>\n\n<ul>\n<li>0</li>\n<li>false</li>\n<li>\"\"</li>\n<li>null</li>\n<li>NaN</li>\n</ul>\n\n<p>the previous loop would stop at that item, not always what you want/expect. </p>\n\n<p>To avoid this use:</p>\n\n<pre><code>var current;\n\nwhile((current=iterator())!==undefined)\n{\n console.log(current);\n}\n</code></pre>\n"
},
{
"answer_id": 193584,
"author": "Chase Seibert",
"author_id": 7679,
"author_profile": "https://Stackoverflow.com/users/7679",
"pm_score": 3,
"selected": false,
"text": "<p>Small improvement to the original, to only calculate the array size once:</p>\n\n<pre><code>for(var i = 0, len = a.length; i < len; i++){ var element = a[i]; }\n</code></pre>\n\n<p>Also, I see a lot of for..in loops. Though keep in mind that it's not technically kosher, and will cause problems with Prototype specifically:</p>\n\n<pre><code>for (i in a) { var element = a[i]; }\n</code></pre>\n"
},
{
"answer_id": 193595,
"author": "Randy Sugianto 'Yuku'",
"author_id": 11238,
"author_profile": "https://Stackoverflow.com/users/11238",
"pm_score": 3,
"selected": false,
"text": "<p>Just store the length in a variable first.</p>\n\n<pre><code> var len = a.length;\n for (var i = 0; i < len; i++) {\n var element = a[i];\n }\n</code></pre>\n"
},
{
"answer_id": 194437,
"author": "Mr. Muskrat",
"author_id": 2657951,
"author_profile": "https://Stackoverflow.com/users/2657951",
"pm_score": 1,
"selected": false,
"text": "<p>If you have many elements in the array and speed is an issue then you want to use a while loop that iterates from highest to lowest.</p>\n\n<pre><code> var i = a.length;\n while( --i >= 0 ) {\n var element = a[i];\n // do stuff with element\n } \n</code></pre>\n"
},
{
"answer_id": 195303,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 1,
"selected": false,
"text": "<p>I don't use it myself, but one of my colleagues uses this style:</p>\n\n<pre><code>var myArray = [1,2,3,4];\nfor (var i = 0, item; item = myArray[i]; ++i) {\n alert(item);\n}\n</code></pre>\n\n<p>like Ash's answer, this will hit issues if you've got \"falsey\" values in your array. To avoid that problem change it to <code>(item = myArray[i]) != undefined</code></p>\n"
},
{
"answer_id": 201580,
"author": "Remy Sharp",
"author_id": 22617,
"author_profile": "https://Stackoverflow.com/users/22617",
"pm_score": 3,
"selected": false,
"text": "<p>I know I'm late to the party, but I use reverse loops for loops that don't depend on the order. </p>\n\n<p>Very similar to @Mr. Muskrat's - but simplifying the test:</p>\n\n<pre><code>var i = a.length, element = null;\nwhile (i--) {\n element = a[i];\n}\n</code></pre>\n"
},
{
"answer_id": 421922,
"author": "nes1983",
"author_id": 52573,
"author_profile": "https://Stackoverflow.com/users/52573",
"pm_score": -1,
"selected": false,
"text": "<p>So, first you identify the perfect javascript loop, I believe it should look like this:</p>\n\n<p>ary.each(function() {$arguments[0]).remove();})</p>\n\n<p>This may require the prototype.js library.</p>\n\n<p>Next, you get disgustet with the arguments[0] part and have the code be produced automatically from your server framework. This works only if the ladder is Seaside. </p>\n\n<p>Now, you have the above generated by:</p>\n\n<p>ary do: [:each | each element remove].</p>\n\n<p>This comes complete with syntax completion and translates exactly to the above javascript. And it will make people's head spin that haven't used seasides prototype integration before, as they read your code. It sure makes you feel cool, too. Not to mention the gain in geekiness you can get here. The girls love it!</p>\n"
},
{
"answer_id": 422566,
"author": "meouw",
"author_id": 12161,
"author_profile": "https://Stackoverflow.com/users/12161",
"pm_score": 0,
"selected": false,
"text": "<p>I don't see what the problem with using a standard for(;;) loop is.\nA little test</p>\n\n<pre><code>var x;\nvar a = [];\n// filling array\nvar t0 = new Date().getTime();\nfor( var i = 0; i < 100000; i++ ) {\n a[i] = Math.floor( Math.random()*100000 );\n}\n\n// normal loop\nvar t1 = new Date().getTime();\nfor( var i = 0; i < 100000; i++ ) {\n x = a[i];\n}\n\n// using length\nvar t2 = new Date().getTime();\nfor( var i = 0; i < a.length; i++ ) {\n x = a[i];\n}\n\n// storing length (pollution - we now have a global l as well as an i )\nvar t3 = new Date().getTime();\nfor( var i = 0, l = a.length; i < l; i++ ) {\n x = a[i];\n}\n\n// for in\nvar t4 = new Date().getTime();\nfor( var i in a ) {\n x = a[i];\n}\n\n// checked for in\nvar t5 = new Date().getTime();\nfor( var i in a ) {\n if (a.hasOwnProperty(i)) {\n x = a[i];\n }\n}\n\nvar t6 = new Date().getTime();\nvar msg = 'filling array: '+(t1-t0)+'ms\\n'+\n 'normal loop: '+(t2-t1)+'ms\\n'+\n 'using length: '+(t3-t2)+'ms\\n'+\n 'storing length: '+(t4-t3)+'ms\\n'+\n 'for in: '+(t5-t4)+'ms\\n'+\n 'checked for in: '+(t6-t5)+'ms';\nconsole.log( msg );\n</code></pre>\n\n<p>results in:</p>\n\n<pre><code>filling array: 227ms\nnormal loop: 21ms\nusing length: 26ms\nstoring length: 24ms \nfor in: 154ms\nchecked for in: 176ms\n</code></pre>\n\n<p>So:- for in's take the longest, using the length property (which is a property and doesn't need to be calculated) is nearly as fast as storing it first - which is only a whisker slower than using an integer.\n<br>AND a for() is the usual way to loop over an array, which everyone expects and understands.<br></p>\n\n<p>All of them add a variable to the scope they run in - i - which is a common name for this use and so shouldn't be used for other things. Storing the length first adds another var - l - to the scope, which is unnecesary</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13995/"
] |
I have stumbled into several methods of looping in JavaScript, what I like the most is:
```
for(var i = 0; i < a.length; i++){
var element = a[i];
}
```
But as tested here (<http://www.robertnyman.com/2008/04/11/javascript-loop-performance/>), it should probably be written so that the length is only calculated once.
In jQuery there is a .each that you can stick a function. I like this a little better, because I don't have to type the array twice, like in the above solution.
If JavaScript supported macros it would be a piece of cake to roll your own, but sadly it does not.
So what do you guys use?
|
I've started using iterators where relevant. Performance is reasonable, however more importantly it allows you to encapsulate the looping logic:
```
function createIterator(x) {
var i = 0;
return function(){
return x[i++];
};
}
```
Then to use:
```
var iterator=createIterator(['a','b','c','d','e','f','g']);
iterator();
```
returns "a";
```
iterator();
```
returns "b";
and so on.
To iterate the whole list and display each item:
```
var current;
while(current=iterator())
{
console.log(current);
}
```
Be aware that the above is only acceptable for iterating a list that contains "non-falsy" values. If this array contained any of:
* 0
* false
* ""
* null
* NaN
the previous loop would stop at that item, not always what you want/expect.
To avoid this use:
```
var current;
while((current=iterator())!==undefined)
{
console.log(current);
}
```
|
193,561 |
<p>I have managed to create an <a href="http://docs.sencha.com/ext-js/3-4/#!/api/Ext.tree.TreeNode" rel="nofollow noreferrer">Ext.tree.TreePanel</a> that loads child nodes dynamically, but I'm having a difficult time clearing the tree and loading it with new data. Can someone help me with the code to do this?</p>
|
[
{
"answer_id": 193617,
"author": "slmcmahon",
"author_id": 26233,
"author_profile": "https://Stackoverflow.com/users/26233",
"pm_score": 1,
"selected": false,
"text": "<p>I finally found an answer in their forums. For anyone interested it is here:</p>\n\n<pre><code>if (tree)\n{\n var delNode;\n while (delNode = tree.root.childNodes[0])\n tree.root.removeChild(delNode);\n}\n</code></pre>\n"
},
{
"answer_id": 193678,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n<pre><code>if (tree) { var delNode; while (delNode = tree.root.childNodes[0]) tree.root.removeChild(delNode); }\n</code></pre>\n</blockquote>\n\n<p>I don't know Ext, but I'm guessing that they have DOM abstraction that might make that easier. An equivalent in Prototype would be something like:</p>\n\n<pre><code>tree.root.immediateDescendants().invoke('remove'); // or\ntree.root.select('> *').invoke('remove');\n</code></pre>\n\n<p>Unless <code>tree.root</code> refers to a collection object rather than the tree's root DOM node, but is borrowing DOM API method names? That seems really unlikely, especially for a modern JS library.</p>\n"
},
{
"answer_id": 194734,
"author": "Joel Mueller",
"author_id": 24380,
"author_profile": "https://Stackoverflow.com/users/24380",
"pm_score": 2,
"selected": false,
"text": "<p>In my case, my Ext tree has a hidden root node of type AsyncTreeNode. If I want to clear the tree and repopulate from the server, it's pretty simple:</p>\n\n<pre><code>tree.getRootNode().reload();\n</code></pre>\n"
},
{
"answer_id": 649801,
"author": "jDempster",
"author_id": 78504,
"author_profile": "https://Stackoverflow.com/users/78504",
"pm_score": 3,
"selected": false,
"text": "<p>From the wonderful blog of Saki an ExtJS guru.</p>\n\n<pre><code>while (node.firstChild) {\n node.removeChild(node.firstChild);\n}\n</code></pre>\n\n<p><a href=\"http://blog.extjs.eu/know-how/how-to-remove-all-children-of-a-tree-node/\" rel=\"nofollow noreferrer\">http://blog.extjs.eu/know-how/how-to-remove-all-children-of-a-tree-node/</a></p>\n"
},
{
"answer_id": 1412677,
"author": "J Sidhu",
"author_id": 111641,
"author_profile": "https://Stackoverflow.com/users/111641",
"pm_score": 0,
"selected": false,
"text": "<p>I ran into a similar problem and the solution i came up with was to 'tag' the node has having not loaded when it was collapsed thus forcing a reload when it was re-expanded.</p>\n\n<pre><code>listeners: {\n collapsenode: function(node){\n node.loaded = false;\n},\n</code></pre>\n"
},
{
"answer_id": 6573037,
"author": "Farish",
"author_id": 346880,
"author_profile": "https://Stackoverflow.com/users/346880",
"pm_score": 2,
"selected": false,
"text": "<p>In Ext JS 4:</p>\n\n<p>if you want to reload the data of the tree panel, you need to reload the tree store:</p>\n\n<pre><code>getCmp('treeId').getStore().load();\n</code></pre>\n\n<p>where treeId is the id of the tree. If you have a store id, you may directly use load() on store id.</p>\n\n<p>to remove all child nodes:</p>\n\n<pre><code>getCmp('treeId').getRootNode().removeAll();\n</code></pre>\n\n<p>However, removing child nodes is not necessary for reloading the tree nodes from its store.</p>\n"
},
{
"answer_id": 17356169,
"author": "zzg",
"author_id": 1982267,
"author_profile": "https://Stackoverflow.com/users/1982267",
"pm_score": 1,
"selected": false,
"text": "<p>you can simply use <code>node.removeAll()</code> to remove all child nodes from this node.</p>\n\n<p><a href=\"http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.data.NodeInterface-method-removeAll\" rel=\"nofollow\">http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.data.NodeInterface-method-removeAll</a></p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26233/"
] |
I have managed to create an [Ext.tree.TreePanel](http://docs.sencha.com/ext-js/3-4/#!/api/Ext.tree.TreeNode) that loads child nodes dynamically, but I'm having a difficult time clearing the tree and loading it with new data. Can someone help me with the code to do this?
|
From the wonderful blog of Saki an ExtJS guru.
```
while (node.firstChild) {
node.removeChild(node.firstChild);
}
```
<http://blog.extjs.eu/know-how/how-to-remove-all-children-of-a-tree-node/>
|
193,602 |
<p>Does anyone know of a really simple way of publishing Java methods as web services? I don't really want the overhead of using Tomcat or Jetty or any of the other container frameworks.</p>
<p>Scenario: I've got a set of Java methods in a service type application that I want to access from other machines on the local LAN.</p>
|
[
{
"answer_id": 193607,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 1,
"selected": false,
"text": "<p>Jetty's pretty lightweight. Otherwise, I think XML-RPC is your only sensible option.</p>\n"
},
{
"answer_id": 193611,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>Web services depend on HTTP. You might not want tomcat or Jetty. In that case, you have to implement HTTP yourself.</p>\n"
},
{
"answer_id": 193623,
"author": "Simon Lehmann",
"author_id": 27011,
"author_profile": "https://Stackoverflow.com/users/27011",
"pm_score": 4,
"selected": true,
"text": "<p>Well, Tomcat or Jetty may be overkill for publishing just some methods as a web service. But on the other hand its not too complicated and they do the job, so why not?</p>\n\n<p>I had a similar problem not too long ago and used a Tomcat together with Axis2. Just download Tomcat, unpack it, deploy the Axis2 WAR. To publish a webservice, there are several aproaches, the one I took is probably one of the easiest:</p>\n\n<p>Just build your application as usual and annotate the web service class and methods with the appropriate annotaions from javax.jws.*. Package everything into a jar. Create a service.xml in the META-INF directory of your jar file and put this into it:</p>\n\n<pre><code><service name=\"name of the service\" scope=\"<one of request, session or application>\">\n <description>\n optional description of your service\n </description>\n\n <messageReceivers>\n <messageReceiver mep=\"http://www.w3.org/2004/08/wsdl/in-only\" class=\"org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver\" />\n <messageReceiver mep=\"http://www.w3.org/2004/08/wsdl/in-out\" class=\"org.apache.axis2.rpc.receivers.RPCMessageReceiver\"/>\n </messageReceivers>\n\n <parameter name=\"ServiceClass\" locked=\"false\">put here the fully qualified name of your service class (e.g. x.y.z.FooService)</parameter>\n\n</service>\n</code></pre>\n\n<p>Rename the .jar to .aar and put it into the /webapps/axis2/WEB-INF/services/ directory. Start tomcat and the service will be deployed. You can check if it is running by visiting the axis2 page (<a href=\"http://localhost:8080/axis2/\" rel=\"nofollow noreferrer\">http://localhost:8080/axis2/</a>). There you will see which services are deployed and which methods are exported. Also you can get the WSDL url there to connect to your service.</p>\n\n<p>Read <a href=\"http://ws.apache.org/axis2/1_4_1/contents.html\" rel=\"nofollow noreferrer\">http://ws.apache.org/axis2/1_4_1/contents.html</a> for more about using Axis2. The approach I described here is not found exactly like this in the docs, but it works very well.</p>\n\n<p><strong>Update:</strong> If you just want to provide web services and really don't need any of the other features of Tomcat (e.g. serving of plain old web pages, jsps or other stuff), you can also use the Axis2 standalone server. But except for the setup part it doesn't change anything I described.</p>\n\n<p>I've written a slightly more detailed version of this, which can be found at: <a href=\"http://www.slashslash.de/lang/en/2008/10/java-webservices-mit-apache-tomcat-und-axis2/\" rel=\"nofollow noreferrer\">http://www.slashslash.de/lang/en/2008/10/java-webservices-mit-apache-tomcat-und-axis2/</a> (don't let the German in URL irritate you, it's written in English)</p>\n"
},
{
"answer_id": 194082,
"author": "Aleksandar Dimitrov",
"author_id": 11797,
"author_profile": "https://Stackoverflow.com/users/11797",
"pm_score": 2,
"selected": false,
"text": "<p>Erhm. Why not just use <a href=\"http://java.sun.com/javase/technologies/core/basic/rmi/index.jsp\" rel=\"nofollow noreferrer\">RMI</a>?</p>\n"
},
{
"answer_id": 300395,
"author": "Red33mer",
"author_id": 38721,
"author_profile": "https://Stackoverflow.com/users/38721",
"pm_score": 0,
"selected": false,
"text": "<p>The simplier solution than the one that Simon has discribed, ist to use the tools that alrady do that. If you use eclipse you could use <a href=\"http://ws.apache.org/axis2/tools/1_2/eclipse/servicearchiver-plugin.html\" rel=\"nofollow noreferrer\">http://ws.apache.org/axis2/tools/1_2/eclipse/servicearchiver-plugin.html</a></p>\n\n<p>to generate the aar file.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/826/"
] |
Does anyone know of a really simple way of publishing Java methods as web services? I don't really want the overhead of using Tomcat or Jetty or any of the other container frameworks.
Scenario: I've got a set of Java methods in a service type application that I want to access from other machines on the local LAN.
|
Well, Tomcat or Jetty may be overkill for publishing just some methods as a web service. But on the other hand its not too complicated and they do the job, so why not?
I had a similar problem not too long ago and used a Tomcat together with Axis2. Just download Tomcat, unpack it, deploy the Axis2 WAR. To publish a webservice, there are several aproaches, the one I took is probably one of the easiest:
Just build your application as usual and annotate the web service class and methods with the appropriate annotaions from javax.jws.\*. Package everything into a jar. Create a service.xml in the META-INF directory of your jar file and put this into it:
```
<service name="name of the service" scope="<one of request, session or application>">
<description>
optional description of your service
</description>
<messageReceivers>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</messageReceivers>
<parameter name="ServiceClass" locked="false">put here the fully qualified name of your service class (e.g. x.y.z.FooService)</parameter>
</service>
```
Rename the .jar to .aar and put it into the /webapps/axis2/WEB-INF/services/ directory. Start tomcat and the service will be deployed. You can check if it is running by visiting the axis2 page (<http://localhost:8080/axis2/>). There you will see which services are deployed and which methods are exported. Also you can get the WSDL url there to connect to your service.
Read <http://ws.apache.org/axis2/1_4_1/contents.html> for more about using Axis2. The approach I described here is not found exactly like this in the docs, but it works very well.
**Update:** If you just want to provide web services and really don't need any of the other features of Tomcat (e.g. serving of plain old web pages, jsps or other stuff), you can also use the Axis2 standalone server. But except for the setup part it doesn't change anything I described.
I've written a slightly more detailed version of this, which can be found at: <http://www.slashslash.de/lang/en/2008/10/java-webservices-mit-apache-tomcat-und-axis2/> (don't let the German in URL irritate you, it's written in English)
|
193,630 |
<p>I've implemented a few poor solutions for bringing up an AJAX loader before dynamically updating a content DIV, but none seem to be "universal", and I find each time I do it I'm reworking it. If I have a DIV with content that updates depending on what a user clicks on the page, and I want to display the loader over this content DIV, what is the best approach? I've seen some developers have the loader always on the page, and they just display it block or none, and I've seen others append it to the DIV. What about when you also have multiple areas that can update? I'm thinking something repeatable that I can call with a function, maybe passing a few parameters.</p>
|
[
{
"answer_id": 193648,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>You could use a <a href=\"http://ui.jquery.com/repository/latest/demos/functional/#ui.progressbar\" rel=\"nofollow noreferrer\">JQuery progress bar</a> or something similar in a different library.</p>\n"
},
{
"answer_id": 194262,
"author": "Dimitry",
"author_id": 27073,
"author_profile": "https://Stackoverflow.com/users/27073",
"pm_score": 3,
"selected": true,
"text": "<p>Some JavaScript libraries allow listening to opening and closing requests. Check out Prototype's request Responder <a href=\"http://www.prototypejs.org/api/ajax/responders\" rel=\"nofollow noreferrer\">http://www.prototypejs.org/api/ajax/responders</a>.</p>\n\n<p>You would do something like this:</p>\n\n<pre><code>Ajax.Responders.register({\n onCreate: function() {\n $('loader').show();\n Ajax.activeRequestCount++;\n },\n onComplete: function() {\n Ajax.activeRequestCount--;\n if (Ajax.activeRequestCount < 1) $('loader').hide();\n }\n});\n</code></pre>\n\n<p>As for visual representation of loading, you may want to identify the different parts of your page which may require separate loading graphics and subclass the Request object, each time indicating the type of request.</p>\n\n<p>E.g.<br />\nIs it a field being saved? <code>new FieldUpdateRequest(field)</code><br />\nIs it the page being loaded? <code>new Request();</code><br />\nIs a container being updated? <code>new PartialRequest(div);</code></p>\n\n<p>Then capture each subclasses type and show or hide a different loader graphic.</p>\n\n<p>There is unfortunately no quick solution, hal. You could build a generic script for appending loader graphics to containers, that should save you some repetition. If you do, mind posting it here :)?</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I've implemented a few poor solutions for bringing up an AJAX loader before dynamically updating a content DIV, but none seem to be "universal", and I find each time I do it I'm reworking it. If I have a DIV with content that updates depending on what a user clicks on the page, and I want to display the loader over this content DIV, what is the best approach? I've seen some developers have the loader always on the page, and they just display it block or none, and I've seen others append it to the DIV. What about when you also have multiple areas that can update? I'm thinking something repeatable that I can call with a function, maybe passing a few parameters.
|
Some JavaScript libraries allow listening to opening and closing requests. Check out Prototype's request Responder <http://www.prototypejs.org/api/ajax/responders>.
You would do something like this:
```
Ajax.Responders.register({
onCreate: function() {
$('loader').show();
Ajax.activeRequestCount++;
},
onComplete: function() {
Ajax.activeRequestCount--;
if (Ajax.activeRequestCount < 1) $('loader').hide();
}
});
```
As for visual representation of loading, you may want to identify the different parts of your page which may require separate loading graphics and subclass the Request object, each time indicating the type of request.
E.g.
Is it a field being saved? `new FieldUpdateRequest(field)`
Is it the page being loaded? `new Request();`
Is a container being updated? `new PartialRequest(div);`
Then capture each subclasses type and show or hide a different loader graphic.
There is unfortunately no quick solution, hal. You could build a generic script for appending loader graphics to containers, that should save you some repetition. If you do, mind posting it here :)?
|
193,634 |
<p>Is it possible to create a footer div that sits at the bottom of a site regardless of how much information is present in the middle?</p>
<p>Currently the div I have is positioned depending on how much content i have in the body.</p>
<blockquote>
<h3>See also:</h3>
<p><a href="https://stackoverflow.com/questions/42294/how-do-you-get-the-footer-to-stay-at-the-bottom-of-a-web-page">How do you get the footer to stay at the bottom of a Web page?</a></p>
</blockquote>
|
[
{
"answer_id": 193637,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 5,
"selected": true,
"text": "<p>I am by no means a css expert, but this works for me across the major browsers:</p>\n\n<pre><code>.d_footer\n{\n position:fixed;\n bottom:0px;\n background-color: #336699;\n width:100%;\n text-align:center;\n padding-top:5px;\n padding-bottom:5px;\n color:#ffffff;\n}\n</code></pre>\n"
},
{
"answer_id": 193655,
"author": "Jonathan Mueller",
"author_id": 13832,
"author_profile": "https://Stackoverflow.com/users/13832",
"pm_score": 2,
"selected": false,
"text": "<p>Float the content div and have the footer div use <code>clear: both</code>.</p>\n"
},
{
"answer_id": 197442,
"author": "Razor",
"author_id": 17211,
"author_profile": "https://Stackoverflow.com/users/17211",
"pm_score": 1,
"selected": false,
"text": "<p>I know I marked this as being answered but I've run into another problem as a result. The footer sits nicely at the bottom of the page, however, if the content goes past the footer, the footer simply floats over the content.</p>\n\n<p>Is there a way to keep the footer at the bottom of the page without it overlapping if the content goes past the bottom?</p>\n\n<p>My gut feel is using an iframe but Im not sure how to do it.</p>\n"
},
{
"answer_id": 2790496,
"author": "Meta",
"author_id": 335639,
"author_profile": "https://Stackoverflow.com/users/335639",
"pm_score": 0,
"selected": false,
"text": "<p>JonathanMueller is right, that works perfectly.</p>\n\n<p>I had been looking through posts trying to do it like this. All I could find was fixed to the bottom of the window.\nThanks!</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17211/"
] |
Is it possible to create a footer div that sits at the bottom of a site regardless of how much information is present in the middle?
Currently the div I have is positioned depending on how much content i have in the body.
>
> ### See also:
>
>
> [How do you get the footer to stay at the bottom of a Web page?](https://stackoverflow.com/questions/42294/how-do-you-get-the-footer-to-stay-at-the-bottom-of-a-web-page)
>
>
>
|
I am by no means a css expert, but this works for me across the major browsers:
```
.d_footer
{
position:fixed;
bottom:0px;
background-color: #336699;
width:100%;
text-align:center;
padding-top:5px;
padding-bottom:5px;
color:#ffffff;
}
```
|
193,651 |
<p>I've had my first go at writing a DLL in Delphi. So far so good. By using a typelib I've been able to pass Widestrings to and from the DLL without difficulty.</p>
<p>What's curious at the moment is that I'm using VB6 as the testbed, and every time I run a test within the IDE, the program runs and then the IDE process suddenly disappears from memory - no error messages, nothing. If I step through the code, everything works fine until I execute the last line, then the IDE disappears. </p>
<p>By contrast, when I compile the test to an EXE the program runs to its end, without error messages etc.</p>
<p>Has anyone had this problem before and is there an obvious solution that's staring me in the face?</p>
<p>Source code below, in case it matters:</p>
<p>-- project</p>
<pre><code>library BOSLAD;
uses
ShareMem,
SysUtils,
Classes,
BOSLADCode in 'BOSLADCode.pas';
exports
version,
DMesg,
foo;
{$R *.res}
begin
end.
</code></pre>
<p>-- unit</p>
<pre><code>unit BOSLADCode;
interface
function version() : Double; stdcall;
procedure DMesg(sText : WideString; sHead : WideString ); stdcall;
function foo() : PWideString; stdcall;
implementation
uses Windows;
function version() : Double;
var
s : String;
begin
result := 0.001;
end;
procedure DMesg( sText : WideString; sHead : WideString);
begin
Windows.MessageBoxW(0, PWideChar(sText), PWideChar(sHead), 0);
end;
function foo() : PWideString;
var s : WideString;
begin
s := 'My dog''s got fleas';
result := PWideString(s);
end;
end.
</code></pre>
<p>-- typelib</p>
<pre><code> // This is the type library for BOSLAD.dll
[
// Use GUIDGEN.EXE to create the UUID that uniquely identifies
// this library on the user's system. NOTE: This must be done!!
uuid(0C55D7DA-0840-40c0-B77C-DC72BE9D109E),
// This helpstring defines how the library will appear in the
// References dialog of VB.
helpstring("BOSLAD TypeLib"),
// Assume standard English locale.
lcid(0x0409),
// Assign a version number to keep track of changes.
version(1.0)
]
library BOSLAD
{
// Now define the module that will "declare" your C functions.
[
helpstring("Functions in BOSLAD.DLL"),
version(1.0),
// Give the name of your DLL here.
dllname("BOSLAD.dll")
]
module BOSLADFunctions
{
[helpstring("version"), entry("version")] void __stdcall version( [out,retval] double* res );
[helpstring("DMesg"), entry("DMesg")] void __stdcall DMesg( [in] BSTR msg, [in] BSTR head );
[helpstring("foo"), entry("foo")] void __stdcall foo( [out,retval] BSTR* msg );
} // End of Module
}; // End of Library
</code></pre>
<hr>
<p>I moved the declaration of the WideString outside of the function in which I had declared it, in the expectation that that would increase the lifetime of the variable to longer than just the lifetime of the <code>foo</code> function. It made no difference whatsoever.</p>
<p>Likewise I commented out of the VB6 the call to the <code>foo</code> function. That made no difference either. No matter what I do, VB6 IDE dies after the last line of code is executed.</p>
<p>Something apart from pointers to local variables is the cause. But what?</p>
|
[
{
"answer_id": 193774,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 2,
"selected": false,
"text": "<pre><code>result := PWideString(s);\n</code></pre>\n\n<p>You are returning pointer to a local variable here. It immediately becomes invalid.</p>\n"
},
{
"answer_id": 193972,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 2,
"selected": true,
"text": "<p>To elaborate on GSerg's answer:</p>\n\n<pre><code>result := PWideString(s);\n</code></pre>\n\n<p>you'd think it would be ok because s was initialized with a string literal... but wide strings in Delphi are not reference counted like normal strings, so s actually holds a bit of dynamically allocated heap memory, and as soon as the function returns this memory can be reused :(</p>\n\n<p>The following should be ok though:</p>\n\n<pre><code>function foo() : PWideString;\nconst s : WideString = 'My dog''s got fleas';\nbegin\n result := PWideString(s);\nend;\n</code></pre>\n"
},
{
"answer_id": 194173,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://delphi.wikia.com/wiki/Creating_DLLs#Notes_about_memory_management\" rel=\"nofollow noreferrer\">Creating DLLs</a> on the delphi.wikia.com site has the answer I've been looking for. And the solution too.</p>\n\n<p><em>For example, Delphi automatically allocates and frees the memory for storing your strings, it knows when they are no longer needed etc. The same applies for e.g. Visual Basic, but both do it in different ways. So, if you were to pass a string that was allocated by Visual Basic to a DLL written in Delphi you would end up in big trouble, because both would now try to manage the string and would get into each other's hair.</em></p>\n\n<p>The solution is to use <a href=\"http://sourceforge.net/projects/fastmm/\" rel=\"nofollow noreferrer\">FastMM</a> and it works brilliantly!! I now have a replacement <code>BORLNDMM.DLL</code> in with my project and everything just works. </p>\n"
},
{
"answer_id": 203706,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 0,
"selected": false,
"text": "<p>I just got thoroughly straightened out on this one, thanks to Rob Kennedy on news:comp.lang.pascal.delphi.misc</p>\n\n<p>He said, amongst other things that:</p>\n\n<ol>\n<li>This DLL does not need ShareMem, SysUtils, or Classes. </li>\n<li>You've taken a WideString and told the compiler that it's really a pointer to a WideString. You're lying to the compiler. It doesn't care, but the caller of this function probably does.</li>\n</ol>\n\n<p>So the revised code, which works fine without ShareMem (and SysUtils and Classes which were added by the DLL Wizard as it happens) is as follows:</p>\n\n<pre><code>library BOSLAD;\nuses\n BOSLADCode in 'BOSLADCode.pas';\nexports\n version,\n DMesg,\n foo;\n{$R *.res}\nbegin\nend.\n</code></pre>\n\n<p>BOSLADCode.pas:</p>\n\n<pre><code>unit BOSLADCode;\n\ninterface\n function version() : Double; stdcall;\n procedure DMesg(sText : PWideChar; sHead : PWideChar ); stdcall;\n function foo() : PWideChar; stdcall;\n\nimplementation\n uses Windows;\n\n var s : WideString;\n\n function version() : Double;\n begin\n result := 0.001;\n end;\n\n procedure DMesg( sText : PWideChar; sHead : PWideChar);\n begin\n Windows.MessageBoxW(0, sText, sHead, 0);\n end;\n\n function foo() : PWideChar;\n begin\n s := 'My dog''s got fleas';\n result := PWideChar(s);\n end;\nend.\n</code></pre>\n\n<p>boslad.odl:</p>\n\n<pre><code>// This is the type library for BOSLAD.dll\n[\nuuid(0C55D7DA-0840-40c0-B77C-DC72BE9D109E),\nhelpstring(\"BOSLAD TypeLib\"),\nlcid(0x0409),\nversion(1.0)\n]\nlibrary BOSLAD\n{\n[\nhelpstring(\"Functions in BOSLAD.DLL\"),\nversion(1.0),\ndllname(\"BOSLAD.dll\")\n]\nmodule BOSLADFunctions\n{\n[helpstring(\"version\"), entry(\"version\")] \n void __stdcall version( [out,retval] double* res );\n[helpstring(\"DMesg\"), entry(\"DMesg\")] \n void __stdcall DMesg( [in] BSTR msg, [in] BSTR head );\n[helpstring(\"foo\"), entry(\"foo\")] \n void __stdcall foo( [out,retval] BSTR* msg );\n} \n}; \n</code></pre>\n\n<p>test.bas:</p>\n\n<pre><code>Sub Main()\n Dim cfg As New CFGProject.cfg\n cfg.Load \"test.cfg\"\n Dim s As String\n s = cfg.Recall(\"msg\")\n DMesg s, \"\" & version\n s = foo\n DMesg s, \"\" & version\nEnd Sub\n</code></pre>\n\n<p>test.cfg</p>\n\n<pre><code>msg=毅訜訝\n</code></pre>\n\n<p>All of that works perfectly. VB6's IDE happily runs the DLL and the MsgBoxs appear with everything as it should be. </p>\n"
},
{
"answer_id": 212746,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 0,
"selected": false,
"text": "<p>I think we can close this one. The code below seems to be enough to keep the folk on <code>news:comp.lang.pascal.delphi.misc</code> happy and I really need to move on from concept testing to actually doing something with it.</p>\n\n<p>BOSLAD.bdsproj:</p>\n\n<pre><code>library BOSLAD;\n\nuses\n BOSLADCode in 'BOSLADCode.pas';\n\nexports\n version,\n DMesg,\n foo;\n{$R *.res}\n\nbegin\nend.\n</code></pre>\n\n<p>BOSLADCode.pas:</p>\n\n<pre><code>unit BOSLADCode;\n\ninterface\n function version() : Double; stdcall;\n procedure DMesg(const sText : WideString; const sHead : WideString ); stdcall;\n function foo() : PWideChar; stdcall;\n\nimplementation\n uses Windows, ActiveX;\n\n\n function version() : Double;\n begin\n result := 0.001;\n end;\n\n procedure DMesg( const sText : WideString; const sHead : WideString);\n begin\n Windows.MessageBoxW(0, PWideChar(sText), PWideChar(sHead), 0);\n end;\n\n function foo() : PWideChar;\n var s : WideString;\n begin\n s := 'My dog''s got fleas';\n result := SysAllocString(PWideChar(s));\n end;\nend.\n</code></pre>\n\n<p>Now VB's happy and I don't get weird IDE crashes.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/426/"
] |
I've had my first go at writing a DLL in Delphi. So far so good. By using a typelib I've been able to pass Widestrings to and from the DLL without difficulty.
What's curious at the moment is that I'm using VB6 as the testbed, and every time I run a test within the IDE, the program runs and then the IDE process suddenly disappears from memory - no error messages, nothing. If I step through the code, everything works fine until I execute the last line, then the IDE disappears.
By contrast, when I compile the test to an EXE the program runs to its end, without error messages etc.
Has anyone had this problem before and is there an obvious solution that's staring me in the face?
Source code below, in case it matters:
-- project
```
library BOSLAD;
uses
ShareMem,
SysUtils,
Classes,
BOSLADCode in 'BOSLADCode.pas';
exports
version,
DMesg,
foo;
{$R *.res}
begin
end.
```
-- unit
```
unit BOSLADCode;
interface
function version() : Double; stdcall;
procedure DMesg(sText : WideString; sHead : WideString ); stdcall;
function foo() : PWideString; stdcall;
implementation
uses Windows;
function version() : Double;
var
s : String;
begin
result := 0.001;
end;
procedure DMesg( sText : WideString; sHead : WideString);
begin
Windows.MessageBoxW(0, PWideChar(sText), PWideChar(sHead), 0);
end;
function foo() : PWideString;
var s : WideString;
begin
s := 'My dog''s got fleas';
result := PWideString(s);
end;
end.
```
-- typelib
```
// This is the type library for BOSLAD.dll
[
// Use GUIDGEN.EXE to create the UUID that uniquely identifies
// this library on the user's system. NOTE: This must be done!!
uuid(0C55D7DA-0840-40c0-B77C-DC72BE9D109E),
// This helpstring defines how the library will appear in the
// References dialog of VB.
helpstring("BOSLAD TypeLib"),
// Assume standard English locale.
lcid(0x0409),
// Assign a version number to keep track of changes.
version(1.0)
]
library BOSLAD
{
// Now define the module that will "declare" your C functions.
[
helpstring("Functions in BOSLAD.DLL"),
version(1.0),
// Give the name of your DLL here.
dllname("BOSLAD.dll")
]
module BOSLADFunctions
{
[helpstring("version"), entry("version")] void __stdcall version( [out,retval] double* res );
[helpstring("DMesg"), entry("DMesg")] void __stdcall DMesg( [in] BSTR msg, [in] BSTR head );
[helpstring("foo"), entry("foo")] void __stdcall foo( [out,retval] BSTR* msg );
} // End of Module
}; // End of Library
```
---
I moved the declaration of the WideString outside of the function in which I had declared it, in the expectation that that would increase the lifetime of the variable to longer than just the lifetime of the `foo` function. It made no difference whatsoever.
Likewise I commented out of the VB6 the call to the `foo` function. That made no difference either. No matter what I do, VB6 IDE dies after the last line of code is executed.
Something apart from pointers to local variables is the cause. But what?
|
To elaborate on GSerg's answer:
```
result := PWideString(s);
```
you'd think it would be ok because s was initialized with a string literal... but wide strings in Delphi are not reference counted like normal strings, so s actually holds a bit of dynamically allocated heap memory, and as soon as the function returns this memory can be reused :(
The following should be ok though:
```
function foo() : PWideString;
const s : WideString = 'My dog''s got fleas';
begin
result := PWideString(s);
end;
```
|
193,656 |
<p>Can I put the painter into the class variables? :</p>
<pre><code>protected:
QPainter *myPainter;
...
void MyWidget::paintEvent(QPaintEvent *event)
{
myPainter = new QPainter(this);
</code></pre>
|
[
{
"answer_id": 193658,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>don't do that. just put it on the stack so that when it is destroyed in the destructor it will perform the painting automatically.</p>\n\n<pre><code>void MyWidget::paintEvent(QPaintEvent *event)\n{\n QPainter painter(this);\n // use painter\n ...\n // paint object automatically closes and paint on desctruction\n}\n</code></pre>\n"
},
{
"answer_id": 195755,
"author": "Caleb Huitt - cjhuitt",
"author_id": 9876,
"author_profile": "https://Stackoverflow.com/users/9876",
"pm_score": 1,
"selected": false,
"text": "<p>If you are trying to avoid passing the painter widget to a number of subroutine calls, you can probably get away with a pointer to the painter as a class variable. As mentioned, you should still create/destroy it in the paintEvent function. Personally, I would probably just pass it to the helper functions, but you could do it this way.</p>\n\n<p>Also, I'm not sure how your question related to reentrancy. All of the painting of UI elements should only be in the UI thread, if you have multiple threads. You can do a painter on an image in a different thread, but in that case you'd probably want to only be painting that image in that thread, not in multiple threads. Either way, I don't think you'd run into problems with reentrancy in the Qt functions you would call on a painter as long as you kept to those conditions.</p>\n"
},
{
"answer_id": 232165,
"author": "Caleb Huitt - cjhuitt",
"author_id": 9876,
"author_profile": "https://Stackoverflow.com/users/9876",
"pm_score": 3,
"selected": true,
"text": "<p>A new anser to address more reentrancy more specifically...</p>\n\n<p><a href=\"https://stackoverflow.com/users/19884/danatel\">danatel</a> left the following comment to <a href=\"https://stackoverflow.com/questions/193656/is-it-necessary-for-qtpaintevent-to-be-reentrant#195755\">this message</a> (in part):</p>\n\n<blockquote>\n <p>By reentrancy I mean this specific situation: 1) paintEvent handler saves a QPainter to a class variable. 2) paintEvent handler calls subroutines to draw something 3) one of the subroutines calls a Qt method 4) this Qt method generates another paintEvent recursively</p>\n</blockquote>\n\n<p>The answer to this is that it should likely be acceptable, unless you do something really odd. (And if you do something that odd, Qt will likely warn you or abort.) I think there might still be some confusion over what you mean by reentrant, but generating a paintEvent won't stop the execution flow of the current action to immediately process that event. Instead (like all events), it will be queued up for later processing. As long as you aren't doing multi-threading or calling processEvents, the execution order of the code while you are in one of your own functions should be very straightforward.</p>\n\n<p>As an example, let's follow your steps and examine them in more detail. </p>\n\n<ol>\n<li><code>Foo::paintEvent()</code> handler\ncreates a QPainter and sets\n<code>Foo::m_painter_p</code> at it. </li>\n<li><code>Foo::paintEvent()</code> calls\n<code>Foo::paintAntarticaFlag()</code>.</li>\n<li><code>Foo::paintAntarticaFlag()</code>: a) uses <code>Foo::m_painter_p</code>, then b) calls something that calls <code>Foo::update()</code>, then c) uses <code>Foo::m_painter_p</code> some more.</li>\n<li><code>Foo::update()</code>, which is really a Qt method, generates a paintEvent for Foo.</li>\n</ol>\n\n<p>The above sequence is fine, since update creates <strong>an event</strong>, which means delayed processing. If instead you called Foo::repaint(), that would cause an immediate recursion into Foo::paintEvent(), which would either cause Qt to abort because you are creating more than 1 painter for the same object, or your program to abort because it eventually (you know, in a few hundred milliseconds) blew out the stack.</p>\n\n<p>If you are doing multiple threads and just want to trigger a redraw, you can still do that from the other thread, since it will just put a paintEvent on the queue to be handled by the proper thread at the proper time. If you are doing multiple threads and want to draw those flags using the same painter, well, don't. Just don't. In that case, you might consider drawing each flag to a shared image, and drawing that image where you are using the QPainter now.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19884/"
] |
Can I put the painter into the class variables? :
```
protected:
QPainter *myPainter;
...
void MyWidget::paintEvent(QPaintEvent *event)
{
myPainter = new QPainter(this);
```
|
A new anser to address more reentrancy more specifically...
[danatel](https://stackoverflow.com/users/19884/danatel) left the following comment to [this message](https://stackoverflow.com/questions/193656/is-it-necessary-for-qtpaintevent-to-be-reentrant#195755) (in part):
>
> By reentrancy I mean this specific situation: 1) paintEvent handler saves a QPainter to a class variable. 2) paintEvent handler calls subroutines to draw something 3) one of the subroutines calls a Qt method 4) this Qt method generates another paintEvent recursively
>
>
>
The answer to this is that it should likely be acceptable, unless you do something really odd. (And if you do something that odd, Qt will likely warn you or abort.) I think there might still be some confusion over what you mean by reentrant, but generating a paintEvent won't stop the execution flow of the current action to immediately process that event. Instead (like all events), it will be queued up for later processing. As long as you aren't doing multi-threading or calling processEvents, the execution order of the code while you are in one of your own functions should be very straightforward.
As an example, let's follow your steps and examine them in more detail.
1. `Foo::paintEvent()` handler
creates a QPainter and sets
`Foo::m_painter_p` at it.
2. `Foo::paintEvent()` calls
`Foo::paintAntarticaFlag()`.
3. `Foo::paintAntarticaFlag()`: a) uses `Foo::m_painter_p`, then b) calls something that calls `Foo::update()`, then c) uses `Foo::m_painter_p` some more.
4. `Foo::update()`, which is really a Qt method, generates a paintEvent for Foo.
The above sequence is fine, since update creates **an event**, which means delayed processing. If instead you called Foo::repaint(), that would cause an immediate recursion into Foo::paintEvent(), which would either cause Qt to abort because you are creating more than 1 painter for the same object, or your program to abort because it eventually (you know, in a few hundred milliseconds) blew out the stack.
If you are doing multiple threads and just want to trigger a redraw, you can still do that from the other thread, since it will just put a paintEvent on the queue to be handled by the proper thread at the proper time. If you are doing multiple threads and want to draw those flags using the same painter, well, don't. Just don't. In that case, you might consider drawing each flag to a shared image, and drawing that image where you are using the QPainter now.
|
193,686 |
<p>I enabled PHP5 on my website and my webhost needs me to add the following to .htaccess files for PHP5 to work:</p>
<blockquote>
<p>AddHandler application/x-httpd-php5 .php5 .php4 .php .php3 .php2 .phtml<br>
AddType application/x-httpd-php5 .php5 .php4 .php .php3 .php2 .phtml </p>
</blockquote>
<p>Locally, I am running XAMPP to develop code, but XAMPP does not want to work with the .htaccess file above.</p>
<p>I think it is an issue with XAMPP not recognizing php5 (but it does recognize php if I use "application/x-httpd-php" instead of "application/x-httpd-php5")</p>
<p>How do I resolve this?! I need the .htaccess files to look like above so they work with my webhost, but I need XAMPP to work locally with the same files without making changes!</p>
|
[
{
"answer_id": 193702,
"author": "Edward Z. Yang",
"author_id": 23845,
"author_profile": "https://Stackoverflow.com/users/23845",
"pm_score": 0,
"selected": false,
"text": "<p>So, you're in kind of a tough place; ideally speaking your webhost should not need you to put extra gunk in your htaccess files. Not knowing XAMPP too well, I can't offer a specific solution, but I can give you some pointers:</p>\n\n<ol>\n<li><p>Your webhost is running a custom compiled version of PHP that uses application/x-httpd-php5; while it is totally possible to build PHP yourself or find a custom build that has the SAPI layer configured appropriately, you probably <em>don't</em> want to do this.</p></li>\n<li><p>Depending on how much leeway your host is giving htaccess files, it may be possible to use <IfDefine> or <IfModule> to only conditionally execute the PHP fudge code. I haven't tested, and your webhost may have disabled this functionality. Also, you will have to find an appropriate conditional to test against.</p></li>\n<li><p>My favorite answer would be to suck it up, and maintain separate htaccess files. I do this on my website; I have a .htaccess.in file which contains \"global\" declarations, and an htaccess.php file which generates the real .htaccess file based on configuration, etc.</p></li>\n</ol>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 194006,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 2,
"selected": false,
"text": "<p>Apache has <a href=\"http://httpd.apache.org/docs/2.0/mod/core.html#ifdefine\" rel=\"nofollow noreferrer\"><code><IfDefine></code></a> directive. You can use it to hide <code>AddType</code> from your own server:</p>\n\n<pre><code><IfDefine !MyServer>\nAddType application/x-httpd-php5 .php5 …\n…\n</IfDefine>\n</code></pre>\n\n<p>And start apache with </p>\n\n<pre><code>apachectl -D MyServer\n</code></pre>\n"
},
{
"answer_id": 692232,
"author": "Steve Clay",
"author_id": 3779,
"author_profile": "https://Stackoverflow.com/users/3779",
"pm_score": 0,
"selected": false,
"text": "<p>Another simple solution: <a href=\"http://httpd.apache.org/docs/2.2/mod/core.html#accessfilename\" rel=\"nofollow noreferrer\">change the config file name</a> at home. E.g. in httpd.conf:</p>\n\n<pre><code><Directory />\n #existing stuff here...\n AccessFileName .htaccess.home\n</Directory>\n</code></pre>\n\n<p>Now your home server will ignore your \".htaccess\" files. You'll configure it with \".htaccess.home\" files.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I enabled PHP5 on my website and my webhost needs me to add the following to .htaccess files for PHP5 to work:
>
> AddHandler application/x-httpd-php5 .php5 .php4 .php .php3 .php2 .phtml
>
> AddType application/x-httpd-php5 .php5 .php4 .php .php3 .php2 .phtml
>
>
>
Locally, I am running XAMPP to develop code, but XAMPP does not want to work with the .htaccess file above.
I think it is an issue with XAMPP not recognizing php5 (but it does recognize php if I use "application/x-httpd-php" instead of "application/x-httpd-php5")
How do I resolve this?! I need the .htaccess files to look like above so they work with my webhost, but I need XAMPP to work locally with the same files without making changes!
|
Apache has [`<IfDefine>`](http://httpd.apache.org/docs/2.0/mod/core.html#ifdefine) directive. You can use it to hide `AddType` from your own server:
```
<IfDefine !MyServer>
AddType application/x-httpd-php5 .php5 …
…
</IfDefine>
```
And start apache with
```
apachectl -D MyServer
```
|
193,703 |
<p>recently I've been reading through Scott Meyers's excellent <a href="https://rads.stackoverflow.com/amzn/click/com/0321334876" rel="noreferrer" rel="nofollow noreferrer">Effective C++</a> book. In one of the last tips he covered some of the features from TR1 - I knew many of them via Boost. </p>
<p>However, there was one that I definitely did NOT recognize: tr1::reference_wrapper. </p>
<p>How and when would I use tr1::reference_wrapper?</p>
|
[
{
"answer_id": 193752,
"author": "Nick",
"author_id": 26240,
"author_profile": "https://Stackoverflow.com/users/26240",
"pm_score": 5,
"selected": true,
"text": "<p>It's like boost::ref, as far as I know. Basically, a reference which can be copied. Very useful when binding to functions where you need to pass parameters by reference.</p>\n\n<p>For example (using boost syntax):</p>\n\n<pre><code>void Increment( int& iValue )\n{\n iValue++;\n}\n\nint iVariable = 0;\nboost::function< void () > fIncrementMyVariable = boost::bind( &Increment, boost::ref( iVariable ));\n\nfIncrementMyVariable();\n</code></pre>\n\n<p><a href=\"http://www.ddj.com/cpp/184401949\" rel=\"noreferrer\">This Dr. Dobbs article</a> has some info.</p>\n\n<p>Hope this is right, and helpful. :)</p>\n"
},
{
"answer_id": 1011382,
"author": "amit kumar",
"author_id": 19501,
"author_profile": "https://Stackoverflow.com/users/19501",
"pm_score": 4,
"selected": false,
"text": "<p><code>reference_wrapper<T></code> is an immensely useful and simple library. Internally the <code>reference_wrapper<T></code> stores a pointer to T. But the interface it exposes does not contain any pointer notation. </p>\n\n<ul>\n<li>It allows the reference to behave like other simple objects - a <code>reference_wrapper<T></code> can be stored in a STL container.</li>\n<li>It helps avoid the dreadful pointer notation - the cause of so many segmentation faults. Replace a pointer to T with a <code>reference_wrapper<T></code>, pointers by references and <code>T->f()</code> by <code>T.f()</code> wherever possible (ofcourse pointers need to be stored for deleting a heap-allocated objects, but for memory management Boost Pointer Containers are quite useful).</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>class A\n{\n //...\n};\n\nclass B\n{\n public:\n void setA(A& a) \n {\n a_ = boost::ref(a); // use boost::cref if using/storing const A&\n }\n A& getA()\n {\n return a_;\n }\n B(A& a): a_(a) {}\nprivate:\n boost::reference_wrapper<A> a_; \n};\n\nint main()\n{\n A a1;\n B b(a1);\n A a2;\n b.setA(a2);\n return 0;\n}\n</code></pre>\n\n<p>Here I have used the boost implementation of reference wrapper, but C++0x standard is going to have it too. See also <a href=\"http://aszt.inf.elte.hu/~gsd/halado_cpp/ch11.html#Bind-ref\" rel=\"noreferrer\">http://aszt.inf.elte.hu/~gsd/halado_cpp/ch11.html#Bind-ref</a></p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14069/"
] |
recently I've been reading through Scott Meyers's excellent [Effective C++](https://rads.stackoverflow.com/amzn/click/com/0321334876) book. In one of the last tips he covered some of the features from TR1 - I knew many of them via Boost.
However, there was one that I definitely did NOT recognize: tr1::reference\_wrapper.
How and when would I use tr1::reference\_wrapper?
|
It's like boost::ref, as far as I know. Basically, a reference which can be copied. Very useful when binding to functions where you need to pass parameters by reference.
For example (using boost syntax):
```
void Increment( int& iValue )
{
iValue++;
}
int iVariable = 0;
boost::function< void () > fIncrementMyVariable = boost::bind( &Increment, boost::ref( iVariable ));
fIncrementMyVariable();
```
[This Dr. Dobbs article](http://www.ddj.com/cpp/184401949) has some info.
Hope this is right, and helpful. :)
|
193,707 |
<p>What is a preferred way to store recurring time windows? <br />
For example. If I have a calendar system where I need to be able to accommodate daily, weekly or monthly recurring events, what sort of time management system is best? <br /><br />
How is this best represented in a database? </p>
<p><strong>More Details</strong> <br />
The Specific goal of this is to provide sets of open time windows. Once we have these time windows, the code needs to test if a message that arrives to the system falls within one of the time windows.</p>
|
[
{
"answer_id": 193752,
"author": "Nick",
"author_id": 26240,
"author_profile": "https://Stackoverflow.com/users/26240",
"pm_score": 5,
"selected": true,
"text": "<p>It's like boost::ref, as far as I know. Basically, a reference which can be copied. Very useful when binding to functions where you need to pass parameters by reference.</p>\n\n<p>For example (using boost syntax):</p>\n\n<pre><code>void Increment( int& iValue )\n{\n iValue++;\n}\n\nint iVariable = 0;\nboost::function< void () > fIncrementMyVariable = boost::bind( &Increment, boost::ref( iVariable ));\n\nfIncrementMyVariable();\n</code></pre>\n\n<p><a href=\"http://www.ddj.com/cpp/184401949\" rel=\"noreferrer\">This Dr. Dobbs article</a> has some info.</p>\n\n<p>Hope this is right, and helpful. :)</p>\n"
},
{
"answer_id": 1011382,
"author": "amit kumar",
"author_id": 19501,
"author_profile": "https://Stackoverflow.com/users/19501",
"pm_score": 4,
"selected": false,
"text": "<p><code>reference_wrapper<T></code> is an immensely useful and simple library. Internally the <code>reference_wrapper<T></code> stores a pointer to T. But the interface it exposes does not contain any pointer notation. </p>\n\n<ul>\n<li>It allows the reference to behave like other simple objects - a <code>reference_wrapper<T></code> can be stored in a STL container.</li>\n<li>It helps avoid the dreadful pointer notation - the cause of so many segmentation faults. Replace a pointer to T with a <code>reference_wrapper<T></code>, pointers by references and <code>T->f()</code> by <code>T.f()</code> wherever possible (ofcourse pointers need to be stored for deleting a heap-allocated objects, but for memory management Boost Pointer Containers are quite useful).</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>class A\n{\n //...\n};\n\nclass B\n{\n public:\n void setA(A& a) \n {\n a_ = boost::ref(a); // use boost::cref if using/storing const A&\n }\n A& getA()\n {\n return a_;\n }\n B(A& a): a_(a) {}\nprivate:\n boost::reference_wrapper<A> a_; \n};\n\nint main()\n{\n A a1;\n B b(a1);\n A a2;\n b.setA(a2);\n return 0;\n}\n</code></pre>\n\n<p>Here I have used the boost implementation of reference wrapper, but C++0x standard is going to have it too. See also <a href=\"http://aszt.inf.elte.hu/~gsd/halado_cpp/ch11.html#Bind-ref\" rel=\"noreferrer\">http://aszt.inf.elte.hu/~gsd/halado_cpp/ch11.html#Bind-ref</a></p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8880/"
] |
What is a preferred way to store recurring time windows?
For example. If I have a calendar system where I need to be able to accommodate daily, weekly or monthly recurring events, what sort of time management system is best?
How is this best represented in a database?
**More Details**
The Specific goal of this is to provide sets of open time windows. Once we have these time windows, the code needs to test if a message that arrives to the system falls within one of the time windows.
|
It's like boost::ref, as far as I know. Basically, a reference which can be copied. Very useful when binding to functions where you need to pass parameters by reference.
For example (using boost syntax):
```
void Increment( int& iValue )
{
iValue++;
}
int iVariable = 0;
boost::function< void () > fIncrementMyVariable = boost::bind( &Increment, boost::ref( iVariable ));
fIncrementMyVariable();
```
[This Dr. Dobbs article](http://www.ddj.com/cpp/184401949) has some info.
Hope this is right, and helpful. :)
|
193,715 |
<p>atoi() is giving me this error:</p>
<pre><code>
error C2664: 'atoi' : cannot convert parameter 1 from 'char' to 'const char *'
Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
</code></pre>
<p>from this line:
int pid = atoi( token.at(0) );
where token is a vector</p>
<p>how can i go around this?</p>
|
[
{
"answer_id": 193717,
"author": "Jason Etheridge",
"author_id": 2193,
"author_profile": "https://Stackoverflow.com/users/2193",
"pm_score": 2,
"selected": false,
"text": "<p>You'll have to create a string:</p>\n\n<pre><code>int pid = atoi(std::string(1, token.at(0)).c_str());\n</code></pre>\n\n<p>... assuming that token is a std::vector of char, and using std::string's constructor that accepts a single character (and the number of that character that the string will contain, one in this case).</p>\n"
},
{
"answer_id": 193722,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 4,
"selected": false,
"text": "<p>token.at(0) is returning a single char, but atoi() is expecting a string (a pointer to a char.) Either convert the single character to a string, or to convert a single digit char into the number it represents you can usually<sup>*</sup> just do this:</p>\n\n<pre><code>int pid = token.at(0) - '0';\n</code></pre>\n\n<p><sup>* The exception is when the charset doesn't encode digits 0-9 in order which is extremely rare.</sup></p>\n"
},
{
"answer_id": 193749,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 1,
"selected": false,
"text": "<pre><code>stringstream ss;\nss << token.at(0);\nint pid = -1;\nss >> pid;\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>#include <iostream>\n#include <sstream>\n#include <vector>\n\nint main()\n{\n using namespace std;\n\n vector<char> token(1, '8');\n\n stringstream ss;\n ss << token.at(0);\n int pid = -1;\n ss >> pid;\n if(!ss) {\n cerr << \"error: can't convert to int '\" << token.at(0) << \"'\" << endl; \n }\n\n cout << pid << endl;\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 194221,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 2,
"selected": false,
"text": "<p>Your example is incomplete, as you don't say the exact type of the vector. I assume it is std::vector<char> (that, perhaps, you filled with each char from a C string).</p>\n\n<p>My solution would be to convert it again on char *, which would give the following code:</p>\n\n<pre><code>void doSomething(const std::vector & token)\n{\n char c[2] = {token.at(0), 0} ;\n int pid = std::atoi(c) ;\n}\n</code></pre>\n\n<p>Note that this is a C-like solution (i.e., quite ugly in C++ code), but it remains efficient.</p>\n"
},
{
"answer_id": 9362937,
"author": "jyotirmoy",
"author_id": 1221308,
"author_profile": "https://Stackoverflow.com/users/1221308",
"pm_score": 2,
"selected": false,
"text": "<pre><code>const char tempChar = token.at(0);\nint tempVal = atoi(&tempChar);\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
atoi() is giving me this error:
```
error C2664: 'atoi' : cannot convert parameter 1 from 'char' to 'const char *'
Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
```
from this line:
int pid = atoi( token.at(0) );
where token is a vector
how can i go around this?
|
token.at(0) is returning a single char, but atoi() is expecting a string (a pointer to a char.) Either convert the single character to a string, or to convert a single digit char into the number it represents you can usually\* just do this:
```
int pid = token.at(0) - '0';
```
\* The exception is when the charset doesn't encode digits 0-9 in order which is extremely rare.
|
193,728 |
<p>Is there a free XML formatting (indent) tool available where I can past an XML string and have it formatted so I can read the XML document correctly?</p>
<p>Thanks</p>
<p>Edit ~ I am using XML Notepad on Windows XP.</p>
|
[
{
"answer_id": 193745,
"author": "zoul",
"author_id": 17279,
"author_profile": "https://Stackoverflow.com/users/17279",
"pm_score": 6,
"selected": false,
"text": "<p>Use the following:</p>\n\n<blockquote>\n <p><a href=\"http://xmlsoft.org/xmllint.html\" rel=\"noreferrer\"><code>xmllint</code></a> <code>--format</code></p>\n</blockquote>\n"
},
{
"answer_id": 193753,
"author": "Guy",
"author_id": 1463,
"author_profile": "https://Stackoverflow.com/users/1463",
"pm_score": 9,
"selected": true,
"text": "<p>I believe that <a href=\"http://notepad-plus.sourceforge.net/\" rel=\"noreferrer\">Notepad++</a> has this feature.</p>\n\n<p><strong>Edit (for newer versions)</strong><br>\nInstall the \"XML Tools\" plugin (Menu Plugins, Plugin Manager)<br>\nThen run: Menu Plugins, Xml Tools, Pretty Print (XML only - with line breaks)</p>\n\n<p><strong>Original answer (for older versions of Notepad++)</strong> </p>\n\n<p>Notepad++ menu: TextFX -> HTML Tidy -> Tidy: Reindent XML</p>\n\n<p>This feature however wraps XMLs and that makes it look 'unclean'.\nTo have no wrap, </p>\n\n<ul>\n<li>open <code>C:\\Program Files\\Notepad++\\plugins\\Config\\tidy\\TIDYCFG.INI</code>, </li>\n<li>find the entry <code>[Tidy: Reindent XML]</code> and add <code>wrap:0</code> so that it looks like this: </li>\n</ul>\n\n<pre>\n[Tidy: Reindent XML] \ninput-xml: yes \nindent:yes \nwrap:0 \n</pre>\n"
},
{
"answer_id": 193767,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://www.firstobject.com/dn_editor.htm\" rel=\"noreferrer\">Firstobject's free XML editor for Windows is called foxe</a> is a great tool. </p>\n\n<p>Open or paste your XML into it and press F8 to indent (you may need to set the number of indent spaces as it may default to 0).</p>\n\n<p>It looks simple, however it contains a custom written XML parser written in C++ that allows it to work efficiently with <strong>very large XML files</strong> easily (unlike some expensive \"espionage\" related tools I've used).</p>\n\n<p><em>From the product page:</em></p>\n\n<blockquote>\n <p>The full Visual C++ source code for this firstobject XML editor\n (including the CDataEdit gigabyte edit control MFC component) is\n available as part of the Advanced CMarkup Developer License. It allows\n developers to implement custom XML handling functions such as\n validation, transformation, beautify, and reporting for their own\n purposes.</p>\n</blockquote>\n"
},
{
"answer_id": 193996,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 5,
"selected": false,
"text": "<p>You can open the XML file in any Visual Studio Express product and the press <kbd>Ctrl</kbd>+<kbd>A</kbd>, <kbd>Ctrl</kbd>+<kbd>K</kbd>, <kbd>Ctrl</kbd>+<kbd>F</kbd> to get it nicely formatted.</p>\n\n<p>Hey, it's free and it's a tool, so it fits the question. :-)</p>\n"
},
{
"answer_id": 198511,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>If you use Notepad++, I would suggest installing the <a href=\"http://sourceforge.net/project/showfiles.php?group_id=189927&package_id=264094\" rel=\"nofollow noreferrer\">XML Tools</a> plugin. You can beautify any XML content (indentation and line breaks) or linarize it. Also you can (auto-)validate your file and apply XSL transformation to it.</p>\n\n<p>Download the latest zip and copy the extracted DLL to the plugins directory of your Notepad++ installation. Also, download the External libs and copy them to your %SystemRoot%\\system32\\ directory.</p>\n"
},
{
"answer_id": 198538,
"author": "Mihai Limbășan",
"author_id": 14444,
"author_profile": "https://Stackoverflow.com/users/14444",
"pm_score": 1,
"selected": false,
"text": "<p>Not directly an answer, but good to know nevertheless: After indenting, please make sure that the parser(s) and application(s) which will subsequently process the formatted XML will not yield different results. <a href=\"http://xml.silmaril.ie/whitespace.html\" rel=\"nofollow noreferrer\">White space is often significant in XML</a> and most conforming parsers bubble it up to the application.</p>\n"
},
{
"answer_id": 216661,
"author": "JohnnySoftware",
"author_id": 29380,
"author_profile": "https://Stackoverflow.com/users/29380",
"pm_score": 1,
"selected": false,
"text": "<p>If you are a programmer, many XML parsing programming libraries will let you parse XML, then output it - and generating pretty printed, indented output <strong>is</strong> an output option.</p>\n"
},
{
"answer_id": 4720544,
"author": "Maksym Kozlenko",
"author_id": 171847,
"author_profile": "https://Stackoverflow.com/users/171847",
"pm_score": 4,
"selected": false,
"text": "<p>Another method to reindent XML in Notepad++:</p>\n\n<p>From menu select Plugins -> XML Tools -> Pretty print (XML only – with line breaks)<br>\nor press <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Shift</kbd>+<kbd>B</kbd>.</p>\n"
},
{
"answer_id": 4785158,
"author": "ykatchou",
"author_id": 452723,
"author_profile": "https://Stackoverflow.com/users/452723",
"pm_score": 1,
"selected": false,
"text": "<p>Notepad++ dit it well only if you're in ANSI.\nIf you do it in something like \"ANSI AS UTF8\", tidy dirty the doc :/.</p>\n"
},
{
"answer_id": 4914005,
"author": "austincheney",
"author_id": 605348,
"author_profile": "https://Stackoverflow.com/users/605348",
"pm_score": 1,
"selected": false,
"text": "<p>Try <a href=\"http://prettydiff.com/\" rel=\"nofollow\">http://prettydiff.com/</a> The algorithm is similar to HTML Tidy, but is more complete. The program is written entirely in JavaScript, so you don't have to install anything.</p>\n"
},
{
"answer_id": 6725786,
"author": "Ole Bille",
"author_id": 834354,
"author_profile": "https://Stackoverflow.com/users/834354",
"pm_score": 3,
"selected": false,
"text": "<p>You could also try <a href=\"http://xmltoolbox.appspot.com/\" rel=\"noreferrer\">http://xmltoolbox.appspot.com/</a> it is an online xml formatter. You just paste your xml into a large text area field and press \"format xml\" then it pretty prints the xml in the text area so its easy to read or copy.</p>\n\n<p>There is also a nice little filter feature that allows you to see all of a certain element.</p>\n\n<p>Hope you will enjoy the tool</p>\n"
},
{
"answer_id": 7336726,
"author": "pgfearo",
"author_id": 63965,
"author_profile": "https://Stackoverflow.com/users/63965",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Advanced Conventional Formatting</strong> [Update]</p>\n\n<p><a href=\"https://github.com/pgfearo/xmlspectrum\" rel=\"nofollow noreferrer\">XMLSpectrum</a> is an open source syntax-highlighter. Supporting XML - but with special features for XSLT 2.0, XSD 1.1 and XPath 2.0. I'm mentioning this here because it also has special formatting capabilities for XML: it vertically aligns attributes and their contents as well as elements - to enhance XML readability.</p>\n\n<p>The output HTML is suitable for reviewing in a browser or if the XML needs further editing it can be copied and pasted into an XML editor of your choice</p>\n\n<p>Because <em>xmlspectrum.xsl</em> uses its own XML text parser, all content such as entity references and CDATA sections are preserved - as in an editor.</p>\n\n<p><img src=\"https://i.stack.imgur.com/LBiFy.png\" alt=\"enter image description here\"></p>\n\n<p><em>Note on usage: this is just an XSLT 2.0 stylesheet so you would need to enclose the required command-line (samples provided) in a small script so you could automatically transform the XML source.</em> </p>\n\n<p><strong>Virtual Formatting</strong></p>\n\n<p><a href=\"http://qutoric.com/xmlquire\" rel=\"nofollow noreferrer\">XMLQuire</a> is a free XML editor that has special formatting capabilities - it formats XML properly, including multi-line attributes, attribute-values, word-wrap indentation and even XML comments.</p>\n\n<p>All XML indentation is done without inserting tabs or spaces, ensuring the integrity of the XML is maintained. For versions of Windows later than XP, no installation is needed, its just a 3MB .exe file.</p>\n\n<p>If you need to print out the formatted XML there are special options within the print-preview, such as line-numbering that follows the indentation. If you need to copy the formatted XML to a word processor as rich text, that's available too.</p>\n\n<p>[Disclosure: I maintain both XMLQuire and XMLSpectrum as 'home projects']</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23667/"
] |
Is there a free XML formatting (indent) tool available where I can past an XML string and have it formatted so I can read the XML document correctly?
Thanks
Edit ~ I am using XML Notepad on Windows XP.
|
I believe that [Notepad++](http://notepad-plus.sourceforge.net/) has this feature.
**Edit (for newer versions)**
Install the "XML Tools" plugin (Menu Plugins, Plugin Manager)
Then run: Menu Plugins, Xml Tools, Pretty Print (XML only - with line breaks)
**Original answer (for older versions of Notepad++)**
Notepad++ menu: TextFX -> HTML Tidy -> Tidy: Reindent XML
This feature however wraps XMLs and that makes it look 'unclean'.
To have no wrap,
* open `C:\Program Files\Notepad++\plugins\Config\tidy\TIDYCFG.INI`,
* find the entry `[Tidy: Reindent XML]` and add `wrap:0` so that it looks like this:
```
[Tidy: Reindent XML]
input-xml: yes
indent:yes
wrap:0
```
|
193,773 |
<p>You often see, on sites like <a href="http://en.wikipedia.org/wiki/The_Daily_WTF" rel="nofollow noreferrer">The Daily WTF</a>, examples of overengineered code that should have just been a call to a built-in method within the .NET framework.</p>
<p>What namespaces/classes should be considered essential knowledge for a developer starting his/her first .NET job?</p>
<p><em>As per Joel Spolsky's instruction for these types of questions, please limit your answers to individual items for voting purposes.</em></p>
|
[
{
"answer_id": 193783,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>System.String</p>\n\n<p>and learn how to use regular expressions that are exposed via the System.Text.RegularExpressions namespace.</p>\n\n<p>This will save you a huge amount of time if you end up re-writing text parsers or other string related tasks that have built in functions for them already.</p>\n\n<p><a href=\"http://www.regular-expressions.info/dotnet.html\" rel=\"nofollow noreferrer\">http://www.regular-expressions.info/dotnet.html</a></p>\n\n<p>And the daily WTF is awesome :D</p>\n"
},
{
"answer_id": 193790,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>using System;</p>\n\n<p>System is probably the most important namespace as it contains the core features such as Object and Array as well as the GC (Garbage Collector).</p>\n"
},
{
"answer_id": 193793,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 0,
"selected": false,
"text": "<p>System.Data, particularly Datatable, </p>\n"
},
{
"answer_id": 193796,
"author": "Inisheer",
"author_id": 2982,
"author_profile": "https://Stackoverflow.com/users/2982",
"pm_score": 5,
"selected": true,
"text": "<pre><code>System;\nSystem.Collections;\nSystem.Collections.Generic;\n</code></pre>\n"
},
{
"answer_id": 193800,
"author": "James Newton-King",
"author_id": 11829,
"author_profile": "https://Stackoverflow.com/users/11829",
"pm_score": 3,
"selected": false,
"text": "<p>System.IO is very important.</p>\n\n<p>Understanding how Streams and the various implementations work (FileStream, MemoryStream, CompressionStream) when combined with binary data or text from a TextReader/TextWriter instance is an essential skill.</p>\n"
},
{
"answer_id": 193801,
"author": "410",
"author_id": 24522,
"author_profile": "https://Stackoverflow.com/users/24522",
"pm_score": 0,
"selected": false,
"text": "<p>You should thoroughly look over this application. It contains many patterns and best practices that you should follow.</p>\n\n<p><a href=\"http://www.codeplex.com/guidanceExplorer\" rel=\"nofollow noreferrer\">patterns & practices Guidance Explorer</a></p>\n"
},
{
"answer_id": 193813,
"author": "Steve Hiner",
"author_id": 10221,
"author_profile": "https://Stackoverflow.com/users/10221",
"pm_score": 2,
"selected": false,
"text": "<p>If you're working in VB.NET I'd say the My namespace is very important. It contains shortcuts to a lot of areas of the framework that used to be spread all over the place in the framework. It's also quite intuitive. You can write things like:<br />\nFor Each Printer in My.Computer.Printers<br />\nor<br />\nMy.Computer.FileSystem.OpenFile(Filename)<br />\nMy.Computer.Info.AvailablePhysicalMemory<br />\nMy.Computer.Screen.PrimaryScreen.WorkingArea</p>\n"
},
{
"answer_id": 193815,
"author": "James Newton-King",
"author_id": 11829,
"author_profile": "https://Stackoverflow.com/users/11829",
"pm_score": 3,
"selected": false,
"text": "<pre><code>System.IDisposable\n</code></pre>\n\n<p>Not properly disposing objects that implement it (streams, database connections, sockets, etc) leads to locked file errors, open database connections and a whole lot of other unpleasant and hard to find bugs in your software.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/idispose.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/idispose.aspx</a></p>\n"
},
{
"answer_id": 193985,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 0,
"selected": false,
"text": "<ul>\n<li>System.IO for file operations</li>\n<li>System.Collections & System.Collections.Generic - learn how to manipulate / use Lists, Dictionary, etc.</li>\n</ul>\n"
},
{
"answer_id": 203003,
"author": "JB King",
"author_id": 8745,
"author_profile": "https://Stackoverflow.com/users/8745",
"pm_score": 0,
"selected": false,
"text": "<p>There should be some line to be drawn between a Windows Developer and a Web Developer, where either can be using the .NET Framework. System.Web is very useful if you are doing Web Development as well as knowing how .NET interacts with <a href=\"http://en.wikipedia.org/wiki/Internet_Information_Services\" rel=\"nofollow noreferrer\">IIS</a>, while this may be irrelevant for a Developer who does Windows and Console Applications. </p>\n\n<p>These are starting to blur at times so a developer should try to see where they want to be in the stack, e.g. do they want to do it all like in a small business environment or focus mainly on development like bigger shops can do.</p>\n"
},
{
"answer_id": 203017,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 3,
"selected": false,
"text": "<p>System.Brains and System.CommonSense</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1588/"
] |
You often see, on sites like [The Daily WTF](http://en.wikipedia.org/wiki/The_Daily_WTF), examples of overengineered code that should have just been a call to a built-in method within the .NET framework.
What namespaces/classes should be considered essential knowledge for a developer starting his/her first .NET job?
*As per Joel Spolsky's instruction for these types of questions, please limit your answers to individual items for voting purposes.*
|
```
System;
System.Collections;
System.Collections.Generic;
```
|
193,780 |
<p>I have 2-3 different column names that I want to look up in the entire database and list out all tables which have those columns. Is there any easy script?</p>
|
[
{
"answer_id": 193788,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 8,
"selected": false,
"text": "<pre><code>SELECT TABLE_NAME, COLUMN_NAME\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE COLUMN_NAME LIKE '%wild%';\n</code></pre>\n"
},
{
"answer_id": 193860,
"author": "Ken",
"author_id": 20074,
"author_profile": "https://Stackoverflow.com/users/20074",
"pm_score": 12,
"selected": true,
"text": "<p>To get all tables with columns <code>columnA</code> or <code>ColumnB</code> in the database <code>YourDatabase</code>:</p>\n\n<pre><code>SELECT DISTINCT TABLE_NAME \n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE COLUMN_NAME IN ('columnA','ColumnB')\n AND TABLE_SCHEMA='YourDatabase';\n</code></pre>\n"
},
{
"answer_id": 4415053,
"author": "baycaysoi",
"author_id": 538621,
"author_profile": "https://Stackoverflow.com/users/538621",
"pm_score": 5,
"selected": false,
"text": "<pre><code>SELECT DISTINCT TABLE_NAME, COLUMN_NAME \nFROM INFORMATION_SCHEMA.COLUMNS \nWHERE column_name LIKE 'employee%' \nAND TABLE_SCHEMA='YourDatabase'\n</code></pre>\n"
},
{
"answer_id": 11952827,
"author": "Radu Maris",
"author_id": 207603,
"author_profile": "https://Stackoverflow.com/users/207603",
"pm_score": 4,
"selected": false,
"text": "<p>In older MySQL versions or some MySQL NDB Cluster versions that do not have <code>information_schema</code>, you can dump the table structure and search the column manually.</p>\n<pre><code>mysqldump -h$host -u$user -p$pass --compact --no-data --all-databases > some_file.sql\n</code></pre>\n<p>Now search the column name in <code>some_file.sql</code> using your preferred text editor, or use some nifty <a href=\"https://en.wikipedia.org/wiki/AWK\" rel=\"nofollow noreferrer\">AWK</a> scripts.</p>\n<hr />\n<p>And a simple <a href=\"https://en.wikipedia.org/wiki/Sed\" rel=\"nofollow noreferrer\">sed</a> script to find the column. Just replace <em>COLUMN_NAME</em> with yours:</p>\n<pre><code>sed -n '/^USE/{h};/^CREATE/{H;x;s/\\nCREATE.*\\n/\\n/;x};/COLUMN_NAME/{x;p};' <some_file.sql\nUSE `DATABASE_NAME`;\nCREATE TABLE `TABLE_NAME` (\n `COLUMN_NAME` varchar(10) NOT NULL,\n</code></pre>\n<p>You can pipe the dump directly in sed, but that's trivial.</p>\n"
},
{
"answer_id": 12798381,
"author": "Xman Classical",
"author_id": 1465704,
"author_profile": "https://Stackoverflow.com/users/1465704",
"pm_score": 6,
"selected": false,
"text": "<p>More simply done in one line of SQL:</p>\n\n<pre><code>SELECT * FROM information_schema.columns WHERE column_name = 'column_name';\n</code></pre>\n"
},
{
"answer_id": 32115340,
"author": "oucil",
"author_id": 1058733,
"author_profile": "https://Stackoverflow.com/users/1058733",
"pm_score": 4,
"selected": false,
"text": "<p>For those searching for the inverse of this, i.e. looking for tables that do not contain a certain column name, here is the query...</p>\n\n<pre><code>SELECT DISTINCT TABLE_NAME FROM information_schema.columns WHERE \nTABLE_SCHEMA = 'your_db_name' AND TABLE_NAME NOT IN (SELECT DISTINCT \nTABLE_NAME FROM information_schema.columns WHERE column_name = \n'column_name' AND TABLE_SCHEMA = 'your_db_name');\n</code></pre>\n\n<p>This came in really handy when we began to slowly implement use of InnoDB's special <code>ai_col</code> column and needed to figure out which of our 200 tables had yet to be upgraded.</p>\n"
},
{
"answer_id": 34223872,
"author": "Shivendra Prakash Shukla",
"author_id": 3281806,
"author_profile": "https://Stackoverflow.com/users/3281806",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to "get all tables only", then use this query:</p>\n<pre><code>SELECT TABLE_NAME\nFROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_NAME like '%'\nand TABLE_SCHEMA = 'tresbu_lk'\n</code></pre>\n<p>If you want "to get all tables with columns", then use this query:</p>\n<pre><code>SELECT DISTINCT TABLE_NAME, COLUMN_NAME\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE column_name LIKE '%'\nAND TABLE_SCHEMA='tresbu_lk'\n</code></pre>\n"
},
{
"answer_id": 46304671,
"author": "António Delgado",
"author_id": 8634731,
"author_profile": "https://Stackoverflow.com/users/8634731",
"pm_score": 4,
"selected": false,
"text": "<p>Use this one line query. Replace <em>desired_column_name</em> by your column name.</p>\n<pre><code>SELECT TABLE_NAME FROM information_schema.columns WHERE column_name = 'desired_column_name';\n</code></pre>\n"
},
{
"answer_id": 50384182,
"author": "nageen nayak",
"author_id": 3996624,
"author_profile": "https://Stackoverflow.com/users/3996624",
"pm_score": 3,
"selected": false,
"text": "<pre><code>SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME LIKE '%city_id%' AND TABLE_SCHEMA='database'\n</code></pre>\n"
},
{
"answer_id": 54826287,
"author": "user2587656",
"author_id": 2587656,
"author_profile": "https://Stackoverflow.com/users/2587656",
"pm_score": 2,
"selected": false,
"text": "<p>The problem with information_schema is that it can be terribly slow. It is faster to use the SHOW commands.</p>\n\n<p>After you select the database you first send the query SHOW TABLES. And then you do SHOW COLUMNS for each of the tables.</p>\n\n<p>In PHP that would look something like</p>\n\n<pre>\n\n $res = mysqli_query(\"SHOW TABLES\");\n while($row = mysqli_fetch_array($res))\n { $rs2 = mysqli_query(\"SHOW COLUMNS FROM \".$row[0]);\n while($rw2 = mysqli_fetch_array($rs2))\n { if($rw2[0] == $target)\n ....\n }\n }\n\n</pre>\n"
},
{
"answer_id": 59382822,
"author": "love2code",
"author_id": 426759,
"author_profile": "https://Stackoverflow.com/users/426759",
"pm_score": 3,
"selected": false,
"text": "<pre><code>select distinct table_name \nfrom information_schema.columns \nwhere column_name in ('ColumnA') \n and table_schema='YourDatabase';\n and table_name in \n (\n select distinct table_name \n from information_schema.columns \n where column_name in ('ColumnB')\n and table_schema='YourDatabase';\n );\n</code></pre>\n<p>That ^^ will get the tables with ColumnA <em>and</em> ColumnB instead of ColumnA <em>or</em> ColumnB like the accepted answer</p>\n"
},
{
"answer_id": 73928849,
"author": "MiraTech",
"author_id": 2114983,
"author_profile": "https://Stackoverflow.com/users/2114983",
"pm_score": 2,
"selected": false,
"text": "<p>A simple way to do:</p>\n<pre><code>SELECT *\nFROM information_schema.columns\nWHERE column_name = 'column_name';\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8091/"
] |
I have 2-3 different column names that I want to look up in the entire database and list out all tables which have those columns. Is there any easy script?
|
To get all tables with columns `columnA` or `ColumnB` in the database `YourDatabase`:
```
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('columnA','ColumnB')
AND TABLE_SCHEMA='YourDatabase';
```
|
193,794 |
<p>How can I change a file's extension using PHP?</p>
<p>Ex: photo.jpg to photo.exe</p>
|
[
{
"answer_id": 193795,
"author": "Galen",
"author_id": 7894,
"author_profile": "https://Stackoverflow.com/users/7894",
"pm_score": 3,
"selected": false,
"text": "<p>You may use the <a href=\"http://www.php.net/rename\" rel=\"nofollow noreferrer\"><code>rename(string $from, string $to, ?resource $context = null)</code></a> function.</p>\n"
},
{
"answer_id": 193798,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": "<p>Once you have the filename in a string, first use regex to replace the extension with an extension of your choice. Here's a small function that'll do that:</p>\n\n<pre><code>function replace_extension($filename, $new_extension) {\n return preg_replace('/\\..+$/', '.' . $new_extension, $filename);\n}\n</code></pre>\n\n<p>Then use the <a href=\"http://php.net/rename\" rel=\"noreferrer\">rename()</a> function to rename the file with the new filename.</p>\n"
},
{
"answer_id": 207153,
"author": "PHLAK",
"author_id": 27025,
"author_profile": "https://Stackoverflow.com/users/27025",
"pm_score": -1,
"selected": false,
"text": "<p>I needed this to change all images extensions withing a gallery to lowercase. I ended up doing the following:</p>\n\n<pre><code>// Converts image file extensions to all lowercase\n$currentdir = opendir($gallerydir);\nwhile(false !== ($file = readdir($currentdir))) {\n if(strpos($file,'.JPG',1) || strpos($file,'.GIF',1) || strpos($file,'.PNG',1)) {\n $srcfile = \"$gallerydir/$file\";\n $filearray = explode(\".\",$file);\n $count = count($filearray);\n $pos = $count - 1;\n $filearray[$pos] = strtolower($filearray[$pos]);\n $file = implode(\".\",$filearray);\n $dstfile = \"$gallerydir/$file\";\n rename($srcfile,$dstfile);\n }\n}\n</code></pre>\n\n<p>This worked for my purposes.</p>\n"
},
{
"answer_id": 4963491,
"author": "Matt ",
"author_id": 277250,
"author_profile": "https://Stackoverflow.com/users/277250",
"pm_score": 5,
"selected": false,
"text": "<pre><code>substr_replace($file , 'png', strrpos($file , '.') +1)\n</code></pre>\n\n<p>Will change any extension to what you want. Replace png with what ever your desired extension would be.</p>\n"
},
{
"answer_id": 7296238,
"author": "Tony Maro",
"author_id": 534088,
"author_profile": "https://Stackoverflow.com/users/534088",
"pm_score": 7,
"selected": true,
"text": "<p>In modern operating systems, filenames very well might contain periods long before the file extension, for instance:</p>\n\n<pre><code>my.file.name.jpg\n</code></pre>\n\n<p>PHP provides a way to find the filename without the extension that takes this into account, then just add the new extension:</p>\n\n<pre><code>function replace_extension($filename, $new_extension) {\n $info = pathinfo($filename);\n return $info['filename'] . '.' . $new_extension;\n}\n</code></pre>\n"
},
{
"answer_id": 13619292,
"author": "niksmac",
"author_id": 827525,
"author_profile": "https://Stackoverflow.com/users/827525",
"pm_score": 2,
"selected": false,
"text": "<p>Just replace it with regexp:</p>\n\n<pre><code>$filename = preg_replace('\"\\.bmp$\"', '.jpg', $filename);\n</code></pre>\n\n<p>You can also extend this code to remove other image extensions, not just bmp:</p>\n\n<pre><code>$filename = preg_replace('\"\\.(bmp|gif)$\"', '.jpg', $filename);\n</code></pre>\n"
},
{
"answer_id": 14726079,
"author": "Alex",
"author_id": 288568,
"author_profile": "https://Stackoverflow.com/users/288568",
"pm_score": 4,
"selected": false,
"text": "<h2>Replace extension, keep path information</h2>\n\n<pre><code>function replace_extension($filename, $new_extension) {\n $info = pathinfo($filename);\n return ($info['dirname'] ? $info['dirname'] . DIRECTORY_SEPARATOR : '') \n . $info['filename'] \n . '.' \n . $new_extension;\n}\n</code></pre>\n"
},
{
"answer_id": 26446963,
"author": "Chris Hadi",
"author_id": 3960081,
"author_profile": "https://Stackoverflow.com/users/3960081",
"pm_score": 2,
"selected": false,
"text": "<p>For regex fans,\nmodified version of Thanh Trung's 'preg_replace' solution that will always contain the new extension (so that if you write a file conversion program, you won't accidentally overwrite the source file with the result) would be:</p>\n\n<pre><code>preg_replace('/\\.[^.]+$/', '.', $file) . $extension\n</code></pre>\n"
},
{
"answer_id": 28502488,
"author": "Enyby",
"author_id": 1504248,
"author_profile": "https://Stackoverflow.com/users/1504248",
"pm_score": 2,
"selected": false,
"text": "<p>Better way:</p>\n\n<pre><code>substr($filename, 0, -strlen(pathinfo($filename, PATHINFO_EXTENSION))).$new_extension\n</code></pre>\n\n<p>Changes made only on extension part. Leaves other info unchanged.</p>\n\n<p>It's safe.</p>\n"
},
{
"answer_id": 46738829,
"author": "mgutt",
"author_id": 318765,
"author_profile": "https://Stackoverflow.com/users/318765",
"pm_score": 1,
"selected": false,
"text": "<p>You could use <a href=\"http://php.net/manual/en/function.basename.php\" rel=\"nofollow noreferrer\">basename()</a>:</p>\n\n<pre><code>$oldname = 'path/photo.jpg';\n$newname = (dirname($oldname) ? dirname($oldname) . DIRECTORY_SEPARATOR : '') . basename($oldname, 'jpg') . 'exe';\n</code></pre>\n\n<p>Or for all extensions:</p>\n\n<pre><code>$newname = (dirname($oldname) ? dirname($oldname) . DIRECTORY_SEPARATOR : '') . basename($oldname, pathinfo($path, PATHINFO_EXTENSION)) . 'exe';\n</code></pre>\n\n<p>Finally use <a href=\"http://php.net/manual/en/function.rename.php\" rel=\"nofollow noreferrer\">rename()</a>:</p>\n\n<pre><code>rename($oldname, $newname);\n</code></pre>\n"
},
{
"answer_id": 54087565,
"author": "Moradnejad",
"author_id": 2419960,
"author_profile": "https://Stackoverflow.com/users/2419960",
"pm_score": 0,
"selected": false,
"text": "<p>Many good answers have been suggested. I thought it would be helpful to evaluate and <strong>compare their performance</strong>. Here are the results:</p>\n\n<ul>\n<li>answer by Tony Maro (<code>pathinfo</code>) took 0.000031040740966797 seconds. Note: It has the drawback for not including full path.</li>\n<li>answer by Matt (<code>substr_replace</code>) took 0.000010013580322266 seconds.</li>\n<li>answer by Jeremy Ruten (<code>preg_replace</code>) took 0.00070095062255859 seconds.</li>\n</ul>\n\n<p>Therefore, <strong>I would suggest <code>substr_replace</code>, since it's simpler and faster than others.</strong></p>\n\n<p>Just as a note, There is the following solution too which took 0.000014066696166992 seconds. Still couldn't beat <code>substr_replace</code>:</p>\n\n<pre><code>$parts = explode('.', $inpath);\n$parts[count( $parts ) - 1] = 'exe';\n$outpath = implode('.', $parts);\n</code></pre>\n"
},
{
"answer_id": 73534113,
"author": "Eaten by a Grue",
"author_id": 1767412,
"author_profile": "https://Stackoverflow.com/users/1767412",
"pm_score": 0,
"selected": false,
"text": "<p>I like the <code>strrpos()</code> approach because it is very fast and straightforward — however, you must first check to ensure that the filename has any extension at all. Here's a function that is extremely performant and will replace an existing extension <em>or add a new one if none exists</em>:</p>\n<pre><code>function replace_extension($filename, $extension) {\n if (($pos = strrpos($filename , '.')) !== false) {\n $filename = substr($filename, 0, $pos);\n }\n return $filename . '.' . $extension;\n}\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27025/"
] |
How can I change a file's extension using PHP?
Ex: photo.jpg to photo.exe
|
In modern operating systems, filenames very well might contain periods long before the file extension, for instance:
```
my.file.name.jpg
```
PHP provides a way to find the filename without the extension that takes this into account, then just add the new extension:
```
function replace_extension($filename, $new_extension) {
$info = pathinfo($filename);
return $info['filename'] . '.' . $new_extension;
}
```
|
193,835 |
<p>I'm looking to move some of my lighter weight metaprogramming from Nemerle to Boo and I'm trying to figure out how to define custom operators. For example, I can do the following in Nemerle:</p>
<pre><code>macro @<-(func, v) {
<[ $func($v) ]>
}
</code></pre>
<p>Then these two are equivalent:</p>
<pre><code>foo <- 5;
foo(5);
</code></pre>
<p>I can't find a way of doing this in Boo -- any ideas?</p>
|
[
{
"answer_id": 197738,
"author": "Stoo",
"author_id": 27425,
"author_profile": "https://Stackoverflow.com/users/27425",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure if this is exactly what you need but you can create syntactic macros in Boo. There's some information on the CodeHaus site, <a href=\"http://boo.codehaus.org/Syntactic+Macros\" rel=\"nofollow noreferrer\">http://boo.codehaus.org/Syntactic+Macros</a>, but the syntax has changed in one of the recent releases. I don't know of any tutorials on the new syntax but the source release for Boo 0.8.2 has some examples (some of the language structures are implemented as macros). If you don't want to download the full source a view of the SVN repository is available, <a href=\"https://svn.codehaus.org/boo/boo/trunk/src/Boo.Lang.Extensions/Macros/\" rel=\"nofollow noreferrer\">https://svn.codehaus.org/boo/boo/trunk/src/Boo.Lang.Extensions/Macros/</a>. The assert macro would be a good place to start.</p>\n\n<p>HTH</p>\n\n<p>Stoo</p>\n"
},
{
"answer_id": 1110562,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 4,
"selected": true,
"text": "<p>While Boo supports operator overloading by defining the appropriate static operator function (<code>op_addition</code>), and also supports syntactic macros, it does not support creating custom operators at this time.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4977/"
] |
I'm looking to move some of my lighter weight metaprogramming from Nemerle to Boo and I'm trying to figure out how to define custom operators. For example, I can do the following in Nemerle:
```
macro @<-(func, v) {
<[ $func($v) ]>
}
```
Then these two are equivalent:
```
foo <- 5;
foo(5);
```
I can't find a way of doing this in Boo -- any ideas?
|
While Boo supports operator overloading by defining the appropriate static operator function (`op_addition`), and also supports syntactic macros, it does not support creating custom operators at this time.
|
193,838 |
<p>I want to do a conditional rendering at the layout level based on the actual template has defined <code>content_for(:an__area)</code>, any idea how to get this done?</p>
|
[
{
"answer_id": 194243,
"author": "William Yeung",
"author_id": 16371,
"author_profile": "https://Stackoverflow.com/users/16371",
"pm_score": 1,
"selected": false,
"text": "<p>Ok I am going to shamelessly do a self reply as no one has answered and I have already found the answer :) \nDefine this as a helper method either in application_helper.rb or anywhere you found convenient.</p>\n\n<pre><code> def content_defined?(symbol)\n content_var_name=\"@content_for_\" + \n if symbol.kind_of? Symbol \n symbol.to_s\n elsif symbol.kind_of? String\n symbol\n else\n raise \"Parameter symbol must be string or symbol\"\n end\n\n !instance_variable_get(content_var_name).nil?\n\n end\n</code></pre>\n"
},
{
"answer_id": 636225,
"author": "Nick B",
"author_id": 37460,
"author_profile": "https://Stackoverflow.com/users/37460",
"pm_score": 2,
"selected": false,
"text": "<p>Can create a helper:</p>\n\n<pre><code>def content_defined?(var)\n content_var_name=\"@content_for_#{var}\" \n !instance_variable_get(content_var_name).nil?\nend\n</code></pre>\n\n<p>And use this in your layout:</p>\n\n<pre><code><% if content_defined?(:an__area) %>\n <h1>An area is defined: <%= yield :an__area %></h1>\n<% end %>\n</code></pre>\n"
},
{
"answer_id": 636257,
"author": "efalcao",
"author_id": 73985,
"author_profile": "https://Stackoverflow.com/users/73985",
"pm_score": 3,
"selected": false,
"text": "<p>not really necessary to create a helper method:</p>\n\n<pre><code><% if @content_for_sidebar %>\n <div id=\"sidebar\">\n <%= yield :sidebar %>\n </div>\n<% end %>\n</code></pre>\n\n<p>then of course in your view:</p>\n\n<pre><code><% content_for :sidebar do %>\n ...\n<% end %>\n</code></pre>\n\n<p>I use this all the time to conditionally go between a one column and two column layout</p>\n"
},
{
"answer_id": 1741764,
"author": "Enrico",
"author_id": 212014,
"author_profile": "https://Stackoverflow.com/users/212014",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure of the performance implications of calling yield twice, but this will do regardless of the internal implementation of yield (@content_for_xyz is deprecated) and without any extra code or helper methods:</p>\n\n<pre><code><% if yield :sidebar %>\n <div id=\"sidebar\">\n <%= yield :sidebar %>\n </div>\n<% end %>\n</code></pre>\n"
},
{
"answer_id": 2429033,
"author": "gudleik",
"author_id": 291939,
"author_profile": "https://Stackoverflow.com/users/291939",
"pm_score": 9,
"selected": true,
"text": "<p><code>@content_for_whatever</code> is deprecated.\nUse <code>content_for?</code> instead, like this:</p>\n\n<pre><code><% if content_for?(:whatever) %>\n <div><%= yield(:whatever) %></div>\n<% end %>\n</code></pre>\n"
},
{
"answer_id": 21860184,
"author": "gregwinn",
"author_id": 1011426,
"author_profile": "https://Stackoverflow.com/users/1011426",
"pm_score": 2,
"selected": false,
"text": "<pre><code><%if content_for?(:content)%>\n <%= yield(:content) %>\n<%end%>\n</code></pre>\n"
},
{
"answer_id": 72906340,
"author": "jmichaeln5",
"author_id": 8643768,
"author_profile": "https://Stackoverflow.com/users/8643768",
"pm_score": 0,
"selected": false,
"text": "<p>I use @view_flow and value of the content method before checking if the content is present in the view like this:</p>\n<pre><code>@view_flow.content[:header_left_or_whatever_the_name_of_your_block_is].present?\n</code></pre>\n<p>Recently stumbled upon it when showing all local, global and instance variables of self in the console with byebug. I’m a fan using this because it’s straight from Rails, won’t throw an error, won’t hide anything w “Rails magic”, returns a definite true or false, + only checks the content in the current context of the view being rendered.</p>\n<p>@view_flow is an instance attribute of ActionView::Context and because <a href=\"https://www.rubydoc.info/docs/rails/3.1.1/ActionView/Context\" rel=\"nofollow noreferrer\">Action View contexts are supplied to Action Controller to render a template</a> it will be available to any view that has been rendered by Rails. Although it checks for content, the content_for block will not be yielded if it isn’t there. So it’s been my perfect solution in similar situations.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16371/"
] |
I want to do a conditional rendering at the layout level based on the actual template has defined `content_for(:an__area)`, any idea how to get this done?
|
`@content_for_whatever` is deprecated.
Use `content_for?` instead, like this:
```
<% if content_for?(:whatever) %>
<div><%= yield(:whatever) %></div>
<% end %>
```
|
193,849 |
<p>Would this be right??</p>
<ol>
<li><p>Black Box</p>
<p>1.1 Functional</p>
<pre><code> 1.1.1 Equivalence
1.1.2 BVA
1.1.3 Use case
1.1.4 Regression
1.1.5 UAT
</code></pre>
<p>1.2 Non Functional</p>
<pre><code> 1.2.1 Testing the System Design
</code></pre></li>
<li><p>White box</p>
<p>2.1. Functional</p>
<pre><code> 2.1.1 Unit
2.1.2 Integration
2.1.3 System
</code></pre></li>
</ol>
<p><strong>Do the above fall under the right categories?</strong></p>
<p>The reason I ask this is because as a part of a report I was trying to come up with a good reference that categorised Test Techniques well. This is what my analysis and research from various sources gave me. And I hope this is helpful for someone else who might be doing the same research, but if its incorrect it should be updated.</p>
|
[
{
"answer_id": 193882,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "<p>You might also consider the case when several programs depending one on another are developed simultaneously. You have then to take into account the <strong><em>applicative architecture</em></strong> which groups all those applications into several <em>functional domains</em></p>\n\n<p>So, for instance, a financial application having to process a large number of data would be <em>one</em> functional domain, in which you would have to develop a:</p>\n\n<ul>\n<li>dispatcher module in order to process those data on several computers</li>\n<li>GUI in order to see what is going on</li>\n<li>launcher in order to initiate the right connections retrieve the correct data and format them</li>\n<li>and so on</li>\n</ul>\n\n<p>But that would only be <em>one</em> functional domain, as others would have to be developed in order to <em>exploit the results</em> of your programs (for instance, a \"referential domain\" would be there to store those results into various databases, and offer a communication bus for other programs to access them: that would be a second functional domain).</p>\n\n<p>So I would add to your tests the following categories:</p>\n\n<ul>\n<li><strong>Assembly testing</strong>: when you test within your own functional domain (on an assembly server when you deploy the different applications of your domain, with a set of testing data)</li>\n<li><strong>Integration testing</strong>: when you test <strong><em>all the applications from all the functional domains</em></strong>, which is also called <strong><em>front-to-end testing</em></strong>.</li>\n</ul>\n\n<p>Note: \"integration testing\" is not the same as \"continuous integration testing\", which basically can process the black and white tests you describe, for <strong><em>one</em></strong> program, on a very regular basis.</p>\n\n<p>The tests I am referring to are executed a few times a week by an:</p>\n\n<ul>\n<li>\"<em>Project Operational Architecture</em>\" team of your domain for assembly tests: usually some developers of your team which set up an assembly server, check if the data are up-to-date and deploy the various program you are in charge to develop.</li>\n<li>\"<em>Production Operational Architectural</em>\" team, in charge of setting a \"production-like\" environment and who is the only one able to really <em>test</em> the all chain of application from font to back.</li>\n</ul>\n\n<p>Note: an \"Operation Architecture\" team has the role to \"make operational an execution environment\", meaning to have:</p>\n\n<ul>\n<li>the right logistic team contacts in order to have the right servers and networks, </li>\n<li>the right application teams contacts in order to know about the various start/stop application processes and deployment procedures of <em>all</em> the application of your system!</li>\n</ul>\n\n<p>In short: your categories are for <em>one program</em>, but when you are developing an IS (Information System), you are forced to acknowledge the fact that you are not talking about \"<em>one</em> exe developed by <em>one</em> team deployed on <em>one</em> production machine\"... and then, welcome to an all new world of testing ;)</p>\n"
},
{
"answer_id": 358731,
"author": "mouviciel",
"author_id": 45249,
"author_profile": "https://Stackoverflow.com/users/45249",
"pm_score": 0,
"selected": false,
"text": "<p>I think that your categorisation is a good first step.</p>\n\n<p>Separation between black box and white box (some prefer glass box) testing focuses on whether you have access only to the specification or more (design, source code).</p>\n\n<p>I would add a second separation between functional and structural testing, which focuses on whether you want to consider what the software does (functional) or how it does it (structural).</p>\n\n<p>A third separation deals with how you generate test inputs, deterministically or statistically (with a deliberate distribution and not randomly). Either way, your focus is on what coverage you target.</p>\n\n<p>Finally a well known separation is between different levels of software cycle: unit testing, integration, system, acceptance, ...</p>\n"
},
{
"answer_id": 31808516,
"author": "Ashish Gupta",
"author_id": 5101711,
"author_profile": "https://Stackoverflow.com/users/5101711",
"pm_score": 0,
"selected": false,
"text": "<p>Following are the Testing methodologies broadly defined in the Software Testing:</p>\n\n<p><strong>1. Black Box Testing</strong> is a software testing method in which the internal structure/design/implementation of the item being tested is not known to the tester. These tests can be functional or non-functional, though usually functional. Test design techniques include: Equivalence partitioning, Boundary Value Analysis, Cause Effect Graphing.</p>\n\n<p><strong>2. White Box Testing</strong> is a software testing method in which the internal structure/design/implementation of the item being tested is known to the tester. Test design techniques include: Control flow testing, Data flow testing, Branch testing, and Path testing.</p>\n\n<p><strong>3. Gray Box Testing</strong> is a software testing method which is a combination of Black Box Testing method and White Box Testing method.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Would this be right??
1. Black Box
1.1 Functional
```
1.1.1 Equivalence
1.1.2 BVA
1.1.3 Use case
1.1.4 Regression
1.1.5 UAT
```
1.2 Non Functional
```
1.2.1 Testing the System Design
```
2. White box
2.1. Functional
```
2.1.1 Unit
2.1.2 Integration
2.1.3 System
```
**Do the above fall under the right categories?**
The reason I ask this is because as a part of a report I was trying to come up with a good reference that categorised Test Techniques well. This is what my analysis and research from various sources gave me. And I hope this is helpful for someone else who might be doing the same research, but if its incorrect it should be updated.
|
You might also consider the case when several programs depending one on another are developed simultaneously. You have then to take into account the ***applicative architecture*** which groups all those applications into several *functional domains*
So, for instance, a financial application having to process a large number of data would be *one* functional domain, in which you would have to develop a:
* dispatcher module in order to process those data on several computers
* GUI in order to see what is going on
* launcher in order to initiate the right connections retrieve the correct data and format them
* and so on
But that would only be *one* functional domain, as others would have to be developed in order to *exploit the results* of your programs (for instance, a "referential domain" would be there to store those results into various databases, and offer a communication bus for other programs to access them: that would be a second functional domain).
So I would add to your tests the following categories:
* **Assembly testing**: when you test within your own functional domain (on an assembly server when you deploy the different applications of your domain, with a set of testing data)
* **Integration testing**: when you test ***all the applications from all the functional domains***, which is also called ***front-to-end testing***.
Note: "integration testing" is not the same as "continuous integration testing", which basically can process the black and white tests you describe, for ***one*** program, on a very regular basis.
The tests I am referring to are executed a few times a week by an:
* "*Project Operational Architecture*" team of your domain for assembly tests: usually some developers of your team which set up an assembly server, check if the data are up-to-date and deploy the various program you are in charge to develop.
* "*Production Operational Architectural*" team, in charge of setting a "production-like" environment and who is the only one able to really *test* the all chain of application from font to back.
Note: an "Operation Architecture" team has the role to "make operational an execution environment", meaning to have:
* the right logistic team contacts in order to have the right servers and networks,
* the right application teams contacts in order to know about the various start/stop application processes and deployment procedures of *all* the application of your system!
In short: your categories are for *one program*, but when you are developing an IS (Information System), you are forced to acknowledge the fact that you are not talking about "*one* exe developed by *one* team deployed on *one* production machine"... and then, welcome to an all new world of testing ;)
|
193,852 |
<p>I have the following character string: </p>
<pre><code>"..1....10..20....30...40....50...80..."
</code></pre>
<p>and I need to extract all numbers from it into array. </p>
<p>What is the best way to do it in C? </p>
|
[
{
"answer_id": 193858,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "<p>Perhaps the easiest way is to use the <code>strtok()</code> function (or <code>strtok_r()</code> if reentrancy is a concern):</p>\n\n<pre><code>char str[] = \"..1...10...20\";\nchar *p = strtok(str, \".\");\nwhile (p != NULL) {\n printf(\"%d\\n\", atoi(p));\n p = strtok(NULL, \".\");\n}\n</code></pre>\n\n<p>Once you have the results of calling <code>atoi()</code>, it should be a simple matter to save those integers into an array.</p>\n"
},
{
"answer_id": 193892,
"author": "Diomidis Spinellis",
"author_id": 20520,
"author_profile": "https://Stackoverflow.com/users/20520",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a sscanf code with suppressed assignment (%*[.]) to skip over the dots (or any other character you want), and a scanned character count code %n to advance the string pointer.</p>\n\n<pre><code>const char *s = \"..1....10..20....30...40....50...80...\";\nint num, nc;\n\nwhile (sscanf(s, \"%*[.]%d%n\", &num, &nc) == 1) {\n printf(\"%d\\n\", num);\n s += nc;\n}\n</code></pre>\n"
},
{
"answer_id": 193947,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": -1,
"selected": false,
"text": "<p>I prefer the use of strtok in a for loop. Makes it feel more natural, though the syntax looks a little weird.</p>\n\n<pre><code>char str[] = \"..1....10..20....30...40....50...80...\"\nfor ( char* p = strtok( strtok, \".\" ); p != NULL; p = strtok( NULL, \".\" ) )\n{\n printf( \"%d\\n\", atoi( p ) );\n}\n</code></pre>\n"
},
{
"answer_id": 194305,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 1,
"selected": false,
"text": "<p>Here is the correct way to do it, it is a little longer than the simplest way but it doesn't suffer from undefined behavior if the value read is out of range, works properly if the first character is not a dot, etc. You didn't specify whether the numbers could be negative so I used a signed type but only allow positive values, you can easily change this by allowing the negative sign at the top of the inner while loop. This version allows any non-digit characters to delimit integers, if you only want dots to be allowed you can modify the inner loop to skip only dots and then check for a digit.</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <errno.h>\n\n#define ARRAY_SIZE 10\n\nsize_t store_numbers (const char *s, long *array, size_t elems)\n{\n /* Scan string s, returning the number of integers found, delimited by\n * non-digit characters. If array is not null, store the first elems\n * numbers into the provided array */\n\n long value;\n char *endptr;\n size_t index = 0;\n\n while (*s)\n {\n /* Skip any non-digits, add '-' to support negative numbers */\n while (!isdigit(*s) && *s != '\\0')\n s++;\n\n /* Try to read a number with strtol, set errno to 0 first as\n * we need it to detect a range error. */\n errno = 0;\n value = strtol(s, &endptr, 10);\n\n if (s == endptr) break; /* Conversion failed, end of input */\n if (errno != 0) { /* Error handling for out of range values here */ }\n\n /* Store value if array is not null and index is within array bounds */\n if (array && index < elems) array[index] = value;\n index++;\n\n /* Update s to point to the first character not processed by strtol */\n s = endptr;\n }\n\n /* Return the number of numbers found which may be more than were stored */\n return index;\n}\n\nvoid print_numbers (const long *a, size_t elems)\n{\n size_t idx;\n for (idx = 0; idx < elems; idx++) printf(\"%ld\\n\", a[idx]);\n return;\n}\n\nint main (void)\n{\n size_t found, stored;\n long numbers[ARRAY_SIZE];\n found = store_numbers(\"..1....10..20....30...40....50...80...\", numbers, ARRAY_SIZE);\n\n if (found > ARRAY_SIZE)\n stored = ARRAY_SIZE;\n else\n stored = found;\n\n printf(\"Found %zu numbers, stored %zu numbers:\\n\", found, stored);\n print_numbers(numbers, stored);\n\n return 0;\n}\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have the following character string:
```
"..1....10..20....30...40....50...80..."
```
and I need to extract all numbers from it into array.
What is the best way to do it in C?
|
Perhaps the easiest way is to use the `strtok()` function (or `strtok_r()` if reentrancy is a concern):
```
char str[] = "..1...10...20";
char *p = strtok(str, ".");
while (p != NULL) {
printf("%d\n", atoi(p));
p = strtok(NULL, ".");
}
```
Once you have the results of calling `atoi()`, it should be a simple matter to save those integers into an array.
|
193,855 |
<p>I'm having trouble with something that I thought would be easy...
I can't get my NotifyIcon to show a balloon tip. The basic code is:</p>
<pre><code>public void ShowSystrayBubble(string msg, int ms)
{
sysTrayIcon.Visible = true;
sysTrayIcon.ShowBalloonTip(20, "Title", "Text", ToolTipIcon.None);
}
</code></pre>
<p>Nothing happens when I execute this code. I read that the timeout arg may be in seconds or ms, can't tell, so I tried both and neither works.</p>
<p>I'm using WinXP, .NET 3.5.</p>
|
[
{
"answer_id": 193866,
"author": "greg7gkb",
"author_id": 10505,
"author_profile": "https://Stackoverflow.com/users/10505",
"pm_score": 4,
"selected": true,
"text": "<p>I had foiled myself... This turned out to be an issue at the OS level. I had previously disabled all balloons via the registry a few weeks ago.</p>\n\n<p>You can read the information here on how to disable balloon tips in WinXP:\n<a href=\"http://support.microsoft.com/kb/307729\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/307729</a></p>\n\n<p>To enable them, just set the registry value to 1 instead and logon again/restart.</p>\n"
},
{
"answer_id": 193885,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>You should then log the messages for users who have disabled the balloons be able to go review them in case of need. If you can get permissions to read the registry, you could check the value and act accordingly (not to modify the value, but to log or to show the balloon).</p>\n"
},
{
"answer_id": 398012,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Please see this it covers all combinations of mouse clicks with NotifyIcon as well as much more. The code is located in a template and is project setting driven so that you can implement NotifyIcon logic in all your projects with no coding effort at all.</p>\n\n<p>More Here</p>\n\n<p><a href=\"http://code.msdn.microsoft.com/TheNotifyIconExample\" rel=\"nofollow noreferrer\">http://code.msdn.microsoft.com/TheNotifyIconExample</a></p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10505/"
] |
I'm having trouble with something that I thought would be easy...
I can't get my NotifyIcon to show a balloon tip. The basic code is:
```
public void ShowSystrayBubble(string msg, int ms)
{
sysTrayIcon.Visible = true;
sysTrayIcon.ShowBalloonTip(20, "Title", "Text", ToolTipIcon.None);
}
```
Nothing happens when I execute this code. I read that the timeout arg may be in seconds or ms, can't tell, so I tried both and neither works.
I'm using WinXP, .NET 3.5.
|
I had foiled myself... This turned out to be an issue at the OS level. I had previously disabled all balloons via the registry a few weeks ago.
You can read the information here on how to disable balloon tips in WinXP:
<http://support.microsoft.com/kb/307729>
To enable them, just set the registry value to 1 instead and logon again/restart.
|
193,875 |
<p>I have some very simple code to generate an assembly and invoke a method on a contained type. The method gets called and runs correctly, however when I view the generated assembly using Reflector, I don't see the type.</p>
<p>Below is the sample code:</p>
<pre><code>namespace ConsoleApplication2
{
class Proggy
{
public static void Main(string[] args)
{
var ab = AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName() { Name = "MyAssembly" },
AssemblyBuilderAccess.RunAndSave);
var module = ab.DefineDynamicModule(ab.GetName().Name);
var typeBuilder = module.DefineType("MyType");
var ctr = typeBuilder.DefineConstructor(MethodAttributes.Public,
CallingConventions.Standard, Type.EmptyTypes);
var ilgc = ctr.GetILGenerator();
ilgc.Emit(OpCodes.Ldarg_0);
ilgc.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes));
ilgc.Emit(OpCodes.Ret);
var method = typeBuilder.DefineMethod("MyMethod", MethodAttributes.Public,
typeof(int), new[] { typeof(string) });
var ilg = method.GetILGenerator();
ilg.Emit(OpCodes.Ldarg_1);
ilg.EmitCall(OpCodes.Callvirt, typeof(string).GetProperty("Length").GetGetMethod(),
null);
ilg.Emit(OpCodes.Ret);
var type = typeBuilder.CreateType();
ab.Save("mytestasm.dll");
var inst = Activator.CreateInstance(type);
Console.WriteLine(type.InvokeMember("MyMethod", BindingFlags.InvokeMethod, null, inst,
new[] { "MyTestString" }));
Console.ReadLine();
}
}
}
</code></pre>
<p>and here is the corresponding disassembly from Reflector:</p>
<pre><code>.assembly MyAssembly
{
.ver 0:0:0:0
.hash algorithm 0x00008004
}
.module RefEmit_OnDiskManifestModule
// MVID: {0B944140-58D9-430E-A867-DE0AD0A8701F}
// Target Runtime Version: v2.0.50727
</code></pre>
<p>... and ...</p>
<pre><code>{
.class private auto ansi <Module>
{
}
}
</code></pre>
<p>Can anyone help me with getting the assembly properly saved?</p>
|
[
{
"answer_id": 193932,
"author": "alexmac",
"author_id": 23066,
"author_profile": "https://Stackoverflow.com/users/23066",
"pm_score": -1,
"selected": false,
"text": "<p>I am not sure why the type is not getting added. </p>\n\n<p>Another way of doing this however is to dynamically create code by just passing in a string which contains your class code. I think this is a bit easier than the above way of doing it as you can just build up the code using a string builder and test in studio.</p>\n\n<p>Here is the code i use to generate a dll:</p>\n\n<pre><code>print(\" Microsoft.CSharp.CSharpCodeProvider objCodeProvider = new Microsoft.CSharp.CSharpCodeProvider();\n string strCode = \"using System;\" + Environment.NewLine + \"using System.Data;\" + Environment.NewLine + \"using DC.Common;\" + Environment.NewLine + \"\" + Environment.NewLine + \"using System.Data.SqlClient;\" + Environment.NewLine + \"using System.Configuration;\" + Environment.NewLine + \"\" + Environment.NewLine + Environment.NewLine + BaseClassFile + Environment.NewLine + BaseManagerFile + Environment.NewLine;\n string strSourceModule = BuilderSettings.ExportDir + \"/\" + BuilderSettings.ProjectName + \"/\" + \"BaseFile.cs\";\n\n FileHelper.WriteAllText(strSourceModule, strCode);\n FileHelper.WriteAllText(BuilderSettings.ExportDir + \"/\" + BuilderSettings.ProjectName + \"/\" + \"test.txt\", strCode);\n\n ICodeCompiler icc = objCodeProvider.CreateCompiler();\n string OutputPath = BuilderSettings.ExportDir + \"/\" + BuilderSettings.ProjectName + \"/\" + BuilderSettings.ProjectName + \".dll\";\n CompilerParameters parameters = new CompilerParameters();\n CompilerResults results;\n\n parameters.GenerateExecutable = false;\n parameters.OutputAssembly = OutputPath;\n parameters.GenerateInMemory = false;\n parameters.IncludeDebugInformation = false;\n\n //Add required assemblies\n DynamicLinkLibraries.Clear();\n\n //User defined\n DynamicLinkLibraries.Add(@\"d:\\wwwroot\\\\DC.Common\\bin\\Debug\\DC.Common.dll\");\n\n //System\n DynamicLinkLibraries.Add(\"System.dll\");\n DynamicLinkLibraries.Add(\"System.Data.dll\");\n DynamicLinkLibraries.Add(\"mscorlib.dll\");\n DynamicLinkLibraries.Add(\"System.xml.dll\");\n DynamicLinkLibraries.Add(\"System.web.dll\");\n DynamicLinkLibraries.Add(\"System.configuration.dll\");\n\n //Any dynamic assembly adding must be done here\n foreach (string strLibrary in DynamicLinkLibraries)\n {\n parameters.ReferencedAssemblies.Add(strLibrary);\n }\n\n results = icc.CompileAssemblyFromSource(parameters, strCode);\n\n if (results.Errors.Count > 0)\n {\n //report any compilation errors\n string strErrors = \"Compilation failed:\" + Environment.NewLine;\n\n foreach (CompilerError oError in results.Errors)\n {\n strErrors = strErrors + \"Line number \" + oError.Line + \", Error Number: \" + oError.ErrorNumber + \", '\" + oError.ErrorText + \";\";\n\n }\n\n throw new Exception(\"Error in CompileSourceCode(): \" + Environment.NewLine + strErrors);\n }\n\n objCodeProvider = null;\n icc = null;\n parameters = null;\");\n</code></pre>\n"
},
{
"answer_id": 193948,
"author": "Eric Smith",
"author_id": 26054,
"author_profile": "https://Stackoverflow.com/users/26054",
"pm_score": 4,
"selected": true,
"text": "<p>The trick is to use a \"persistable module\" version of DefineDynamicModule method on the AssemblyBuilder instance. That is, instead of:</p>\n\n<pre><code>var module = ab.DefineDynamicModule(ab.GetName().Name);\n</code></pre>\n\n<p>use something like:</p>\n\n<pre><code>var module = ab.DefineDynamicModule(ab.GetName().Name, ab.GetName().Name + \".mod\");\n</code></pre>\n\n<p>Thereafter the corresponding module appears in the assembly after saving.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26054/"
] |
I have some very simple code to generate an assembly and invoke a method on a contained type. The method gets called and runs correctly, however when I view the generated assembly using Reflector, I don't see the type.
Below is the sample code:
```
namespace ConsoleApplication2
{
class Proggy
{
public static void Main(string[] args)
{
var ab = AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName() { Name = "MyAssembly" },
AssemblyBuilderAccess.RunAndSave);
var module = ab.DefineDynamicModule(ab.GetName().Name);
var typeBuilder = module.DefineType("MyType");
var ctr = typeBuilder.DefineConstructor(MethodAttributes.Public,
CallingConventions.Standard, Type.EmptyTypes);
var ilgc = ctr.GetILGenerator();
ilgc.Emit(OpCodes.Ldarg_0);
ilgc.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes));
ilgc.Emit(OpCodes.Ret);
var method = typeBuilder.DefineMethod("MyMethod", MethodAttributes.Public,
typeof(int), new[] { typeof(string) });
var ilg = method.GetILGenerator();
ilg.Emit(OpCodes.Ldarg_1);
ilg.EmitCall(OpCodes.Callvirt, typeof(string).GetProperty("Length").GetGetMethod(),
null);
ilg.Emit(OpCodes.Ret);
var type = typeBuilder.CreateType();
ab.Save("mytestasm.dll");
var inst = Activator.CreateInstance(type);
Console.WriteLine(type.InvokeMember("MyMethod", BindingFlags.InvokeMethod, null, inst,
new[] { "MyTestString" }));
Console.ReadLine();
}
}
}
```
and here is the corresponding disassembly from Reflector:
```
.assembly MyAssembly
{
.ver 0:0:0:0
.hash algorithm 0x00008004
}
.module RefEmit_OnDiskManifestModule
// MVID: {0B944140-58D9-430E-A867-DE0AD0A8701F}
// Target Runtime Version: v2.0.50727
```
... and ...
```
{
.class private auto ansi <Module>
{
}
}
```
Can anyone help me with getting the assembly properly saved?
|
The trick is to use a "persistable module" version of DefineDynamicModule method on the AssemblyBuilder instance. That is, instead of:
```
var module = ab.DefineDynamicModule(ab.GetName().Name);
```
use something like:
```
var module = ab.DefineDynamicModule(ab.GetName().Name, ab.GetName().Name + ".mod");
```
Thereafter the corresponding module appears in the assembly after saving.
|
193,918 |
<p>Given a point such as (0, 0, 0) and a vector like (x, y, z). What is the easiest way to align the negative Z-axis centered at (0, 0, 0) to point in the direction of this vector? Examples using OpenGL would be welcome, but not neccessary.</p>
|
[
{
"answer_id": 193923,
"author": "fluffels",
"author_id": 12828,
"author_profile": "https://Stackoverflow.com/users/12828",
"pm_score": 1,
"selected": false,
"text": "<p>To answer my own question, the best answer I've come up with is this:</p>\n\n<p>Divide the vector up into \"components\". The x component is the displacement along the x axis. If we turn to trigonometry, we have that cos(alpha) = x / vector_magnitude. If we compute the RHS then we can derive alpha, which is the amount by which we'd have to rotate around the y axis.</p>\n\n<p>Then the coordinate system can be aligned to the vector by a series of calls to glRotatef()</p>\n"
},
{
"answer_id": 194037,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<p>There's lots of different ways to rotate a coordinate-frame to point in a given direction; they'll all leave the z-axis pointed in the direction you want, but with variations in how the x- and y-axes are oriented.</p>\n\n<p>The following gets you the shortest rotation, which may or may not be what you want.</p>\n\n<pre><code>vec3 target_dir = normalise( vector );\nfloat rot_angle = acos( dot_product(target_dir,z_axis) );\nif( fabs(rot_angle) > a_very_small_number )\n{\n vec3 rot_axis = normalise( cross_product(target_dir,z_axis) );\n glRotatef( rot_angle, rot_axis.x, rot_axis.y, rot_axis.z );\n}\n</code></pre>\n"
},
{
"answer_id": 194502,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": 0,
"selected": false,
"text": "<p>There are lots of resources out there about rotating your coordinates (or rotating objects, which amounts to the same thing). I learnt a lot from <a href=\"http://tfpsly.free.fr/Docs/3dIca/3dica2.htm#chap23\" rel=\"nofollow noreferrer\">this site</a>, both about how to program in multiple dimensions and especially <a href=\"http://tfpsly.free.fr/Docs/3dIca/3dica1.htm\" rel=\"nofollow noreferrer\">how to manipulate vectors</a></p>\n"
},
{
"answer_id": 266437,
"author": "Glenn",
"author_id": 29771,
"author_profile": "https://Stackoverflow.com/users/29771",
"pm_score": 0,
"selected": false,
"text": "<p>The page <a href=\"http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/ArbitraryAxisRotation.html\" rel=\"nofollow noreferrer\">here</a> has a section \"Transformations for moving a vector to the z-axis\" that\nseems to be what you want, or perhaps the inverse of it.</p>\n"
},
{
"answer_id": 1087038,
"author": "bobobobo",
"author_id": 111307,
"author_profile": "https://Stackoverflow.com/users/111307",
"pm_score": 1,
"selected": false,
"text": "<p>You probably want to have a look at <a href=\"http://www.fastgraph.com/makegames/3drotation/\" rel=\"nofollow noreferrer\">Diana Gruber's</a> article</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12828/"
] |
Given a point such as (0, 0, 0) and a vector like (x, y, z). What is the easiest way to align the negative Z-axis centered at (0, 0, 0) to point in the direction of this vector? Examples using OpenGL would be welcome, but not neccessary.
|
There's lots of different ways to rotate a coordinate-frame to point in a given direction; they'll all leave the z-axis pointed in the direction you want, but with variations in how the x- and y-axes are oriented.
The following gets you the shortest rotation, which may or may not be what you want.
```
vec3 target_dir = normalise( vector );
float rot_angle = acos( dot_product(target_dir,z_axis) );
if( fabs(rot_angle) > a_very_small_number )
{
vec3 rot_axis = normalise( cross_product(target_dir,z_axis) );
glRotatef( rot_angle, rot_axis.x, rot_axis.y, rot_axis.z );
}
```
|
193,919 |
<p>I am a little confused by the multitude of ways in which you can import modules in Python. </p>
<pre><code>import X
import X as Y
from A import B
</code></pre>
<p>I have been reading up about scoping and namespaces, but I would like some practical advice on what is the best strategy, under which circumstances and why. Should imports happen at a module level or a method/function level? In the <code>__init__.py</code> or in the module code itself?</p>
<p>My question is not really answered by "<a href="https://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file">Python packages - import by class, not file</a>" although it is obviously related.</p>
|
[
{
"answer_id": 193927,
"author": "MvdD",
"author_id": 18044,
"author_profile": "https://Stackoverflow.com/users/18044",
"pm_score": 4,
"selected": false,
"text": "<p>I would normally use <code>import X</code> on module level. If you only need a single object from a module, use <code>from X import Y</code>. </p>\n\n<p>Only use <code>import X as Y</code> in case you're otherwise confronted with a name clash.</p>\n\n<p>I only use imports on function level to import stuff I need when the module is used as the main module, like:</p>\n\n<pre><code>def main():\n import sys\n if len(sys.argv) > 1:\n pass\n</code></pre>\n\n<p>HTH</p>\n"
},
{
"answer_id": 193931,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 7,
"selected": true,
"text": "<p>In production code in our company, we try to follow the following rules.</p>\n\n<p>We place imports at the beginning of the file, right after the main file's docstring, e.g.:</p>\n\n<pre><code>\"\"\"\nRegistry related functionality.\n\"\"\"\nimport wx\n# ...\n</code></pre>\n\n<p>Now, if we import a class that is one of few in the imported module, we import the name directly, so that in the code we only have to use the last part, e.g.:</p>\n\n<pre><code>from RegistryController import RegistryController\nfrom ui.windows.lists import ListCtrl, DynamicListCtrl\n</code></pre>\n\n<p>There are modules, however, that contain dozens of classes, e.g. list of all possible exceptions. Then we import the module itself and reference to it in the code:</p>\n\n<pre><code>from main.core import Exceptions\n# ...\nraise Exceptions.FileNotFound()\n</code></pre>\n\n<p>We use the <code>import X as Y</code> as rarely as possible, because it makes searching for usage of a particular module or class difficult. Sometimes, however, you have to use it if you wish to import two classes that have the same name, but exist in different modules, e.g.:</p>\n\n<pre><code>from Queue import Queue\nfrom main.core.MessageQueue import Queue as MessageQueue\n</code></pre>\n\n<p>As a general rule, we don't do imports inside methods -- they simply make code slower and less readable. Some may find this a good way to easily resolve cyclic imports problem, but a better solution is code reorganization.</p>\n"
},
{
"answer_id": 193937,
"author": "olt",
"author_id": 19759,
"author_profile": "https://Stackoverflow.com/users/19759",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>import X as Y</code> is useful if you have different implementations of the same module/class.</p>\n\n<p>With some nested <code>try..import..except ImportError..import</code>s you can hide the implementation from your code. See <a href=\"http://codespeak.net/lxml/tutorial.html\" rel=\"nofollow noreferrer\">lxml etree import example</a>:</p>\n\n<pre><code>try:\n from lxml import etree\n print(\"running with lxml.etree\")\nexcept ImportError:\n try:\n # Python 2.5\n import xml.etree.cElementTree as etree\n print(\"running with cElementTree on Python 2.5+\")\n except ImportError:\n try:\n # Python 2.5\n import xml.etree.ElementTree as etree\n print(\"running with ElementTree on Python 2.5+\")\n except ImportError:\n try:\n # normal cElementTree install\n import cElementTree as etree\n print(\"running with cElementTree\")\n except ImportError:\n try:\n # normal ElementTree install\n import elementtree.ElementTree as etree\n print(\"running with ElementTree\")\n except ImportError:\n print(\"Failed to import ElementTree from any known place\")\n</code></pre>\n"
},
{
"answer_id": 193979,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "<p>I generally try to use the regular <code>import modulename</code>, unless the module name is long, or used often..</p>\n\n<p>For example, I would do..</p>\n\n<pre><code>from BeautifulSoup import BeautifulStoneSoup as BSS\n</code></pre>\n\n<p>..so I can do <code>soup = BSS(html)</code> instead of <code>BeautifulSoup.BeautifulStoneSoup(html)</code></p>\n\n<p>Or..</p>\n\n<pre><code>from xmpp import XmppClientBase\n</code></pre>\n\n<p>..instead of importing the entire of xmpp when I only use the XmppClientBase</p>\n\n<p>Using <code>import x as y</code> is handy if you want to import either very long method names , or to prevent clobbering an existing import/variable/class/method (something you should try to avoid completely, but it's not always possible)</p>\n\n<p>Say I want to run a main() function from another script, but I already have a main() function..</p>\n\n<pre><code>from my_other_module import main as other_module_main\n</code></pre>\n\n<p>..wouldn't replace my <code>main</code> function with my_other_module's <code>main</code></p>\n\n<p>Oh, one thing - don't do <code>from x import *</code> - it makes your code very hard to understand, as you cannot easily see where a method came from (<code>from x import *; from y import *; my_func()</code> - where is my_func defined?)</p>\n\n<p>In all cases, you <em>could</em> just do <code>import modulename</code> and then do <code>modulename.subthing1.subthing2.method(\"test\")</code>...</p>\n\n<p>The <code>from x import y as z</code> stuff is purely for convenience - use it whenever it'll make your code easier to read or write!</p>\n"
},
{
"answer_id": 194085,
"author": "davidavr",
"author_id": 8247,
"author_profile": "https://Stackoverflow.com/users/8247",
"pm_score": 3,
"selected": false,
"text": "<p>Others have covered most of the ground here but I just wanted to add one case where I will use <code>import X as Y</code> (temporarily), when I'm trying out a new version of a class or module.</p>\n\n<p>So if we were migrating to a new implementation of a module, but didn't want to cut the code base over all at one time, we might write a <code>xyz_new</code> module and do this in the source files that we had migrated:</p>\n\n<pre><code>import xyz_new as xyz\n</code></pre>\n\n<p>Then, once we cut over the entire code base, we'd just replace the <code>xyz</code> module with <code>xyz_new</code> and change all of the imports back to</p>\n\n<pre><code>import xyz\n</code></pre>\n"
},
{
"answer_id": 194096,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 2,
"selected": false,
"text": "<p>DON'T do this:</p>\n\n<pre><code>from X import *\n</code></pre>\n\n<p>unless you are absolutely sure that you will use each and every thing in that module. And even then, you should probably reconsider using a different approach.</p>\n\n<p>Other than that, it's just a matter of style.</p>\n\n<pre><code>from X import Y\n</code></pre>\n\n<p>is good and saves you lots of typing. I tend to use that when I'm using something in it fairly frequently But if you're importing a lot from that module, you could end up with an import statement that looks like this:</p>\n\n<pre><code>from X import A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P\n</code></pre>\n\n<p>You get the idea. That's when imports like</p>\n\n<pre><code>import X\n</code></pre>\n\n<p>become useful. Either that or if I'm not really using anything in X very frequently.</p>\n"
},
{
"answer_id": 194422,
"author": "Bartosz Ptaszynski",
"author_id": 27098,
"author_profile": "https://Stackoverflow.com/users/27098",
"pm_score": 5,
"selected": false,
"text": "<p>Let me just paste a part of conversation on django-dev mailing list started by Guido van Rossum:</p>\n\n<blockquote>\n <p>[...]\n For example, it's part of the Google Python style guides[1] that all\n imports must import a module, not a class or function from that\n module. There are way more classes and functions than there are\n modules, so recalling where a particular thing comes from is much\n easier if it is prefixed with a module name. Often multiple modules\n happen to define things with the same name -- so a reader of the code\n doesn't have to go back to the top of the file to see from which\n module a given name is imported. </p>\n</blockquote>\n\n<p><strong>Source:</strong> <a href=\"http://groups.google.com/group/django-developers/browse_thread/thread/78975372cdfb7d1a\" rel=\"noreferrer\">http://groups.google.com/group/django-developers/browse_thread/thread/78975372cdfb7d1a</a></p>\n\n<p>1: <a href=\"http://code.google.com/p/soc/wiki/PythonStyleGuide#Module_and_package_imports\" rel=\"noreferrer\">http://code.google.com/p/soc/wiki/PythonStyleGuide#Module_and_package_imports</a></p>\n"
},
{
"answer_id": 204340,
"author": "Cheery",
"author_id": 21711,
"author_profile": "https://Stackoverflow.com/users/21711",
"pm_score": 1,
"selected": false,
"text": "<p>When you have a well-written library, which is sometimes case in python, you ought just import it and use it as it. Well-written library tends to take life and language of its own, resulting in pleasant-to-read -code, where you rarely reference the library. When a library is well-written, you ought not need renaming or anything else too often.</p>\n\n<pre><code>import gat\n\nnode = gat.Node()\nchild = node.children()\n</code></pre>\n\n<p>Sometimes it's not possible to write it this way, or then you want to lift down things from library you imported.</p>\n\n<pre><code>from gat import Node, SubNode\n\nnode = Node()\nchild = SubNode(node)\n</code></pre>\n\n<p>Sometimes you do this for lot of things, if your import string overflows 80 columns, It's good idea to do this:</p>\n\n<pre><code>from gat import (\n Node, SubNode, TopNode, SuperNode, CoolNode,\n PowerNode, UpNode\n)\n</code></pre>\n\n<p>The best strategy is to keep all of these imports on the top of the file. Preferrably ordered alphabetically, import -statements first, then from import -statements.</p>\n\n<p>Now I tell you why this is the best convention.</p>\n\n<p>Python could perfectly have had an automatic import, which'd look from the main imports for the value when it can't be found from global namespace. But this is not a good idea. I explain shortly why. Aside it being more complicated to implement than simple import, programmers wouldn't be so much thinking about the depedencies and finding out from where you imported things ought be done some other way than just looking into imports.</p>\n\n<p>Need to find out depedencies is one reason why people hate \"from ... import *\". Some bad examples where you need to do this exist though, for example opengl -wrappings.</p>\n\n<p>So the import definitions are actually valuable as defining the depedencies of the program. It is the way how you should exploit them. From them you can quickly just check where some weird function is imported from.</p>\n"
},
{
"answer_id": 2236989,
"author": "CastleDweller",
"author_id": 270293,
"author_profile": "https://Stackoverflow.com/users/270293",
"pm_score": 0,
"selected": false,
"text": "<p>I'm with Jason in the fact of not using</p>\n\n<pre><code>from X import *\n</code></pre>\n\n<p>But in my case (i'm not an expert programmer, so my code does not meet the coding style too well) I usually do in my programs a file with all the constants like program version, authors, error messages and all that stuff, so the file are just definitions, then I make the import</p>\n\n<pre><code>from const import *\n</code></pre>\n\n<p>That saves me a lot of time. But it's the only file that has that import, and it's because all inside that file are just variable declarations.</p>\n\n<p>Doing that kind of import in a file with classes and definitions might be useful, but when you have to read that code you spend lots of time locating functions and classes.</p>\n"
},
{
"answer_id": 16070330,
"author": "Robert Jacobs",
"author_id": 2066459,
"author_profile": "https://Stackoverflow.com/users/2066459",
"pm_score": 4,
"selected": false,
"text": "<p>Someone above said that</p>\n\n<pre><code>from X import A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>import X\n</code></pre>\n\n<p><code>import X</code> allows direct modifications to A-P, while <code>from X import ...</code> creates copies of A-P. For <code>from X import A..P</code> you do not get updates to variables if they are modified. If you modify them, you only modify your copy, but X does know about your modifications.</p>\n\n<p>If A-P are functions, you won't know the difference.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24039/"
] |
I am a little confused by the multitude of ways in which you can import modules in Python.
```
import X
import X as Y
from A import B
```
I have been reading up about scoping and namespaces, but I would like some practical advice on what is the best strategy, under which circumstances and why. Should imports happen at a module level or a method/function level? In the `__init__.py` or in the module code itself?
My question is not really answered by "[Python packages - import by class, not file](https://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file)" although it is obviously related.
|
In production code in our company, we try to follow the following rules.
We place imports at the beginning of the file, right after the main file's docstring, e.g.:
```
"""
Registry related functionality.
"""
import wx
# ...
```
Now, if we import a class that is one of few in the imported module, we import the name directly, so that in the code we only have to use the last part, e.g.:
```
from RegistryController import RegistryController
from ui.windows.lists import ListCtrl, DynamicListCtrl
```
There are modules, however, that contain dozens of classes, e.g. list of all possible exceptions. Then we import the module itself and reference to it in the code:
```
from main.core import Exceptions
# ...
raise Exceptions.FileNotFound()
```
We use the `import X as Y` as rarely as possible, because it makes searching for usage of a particular module or class difficult. Sometimes, however, you have to use it if you wish to import two classes that have the same name, but exist in different modules, e.g.:
```
from Queue import Queue
from main.core.MessageQueue import Queue as MessageQueue
```
As a general rule, we don't do imports inside methods -- they simply make code slower and less readable. Some may find this a good way to easily resolve cyclic imports problem, but a better solution is code reorganization.
|
193,941 |
<p>For a long time I've been trying different languages to find the feature-set I want and I've not been able to find it. I have languages that fit decently for various projects of mine, but I've come up with an intersection of these languages that will allow me to do 99.9% of my projects in a single language. I want the following:</p>
<ul>
<li>Built on top of .NET or has a .NET implementation</li>
<li>Has few dependencies on the .NET runtime both at compile-time and runtime (this is important since one of the major use cases is in embedded development where the .NET runtime is completely custom)</li>
<li>Has a compiler that is 100% .NET code with no unmanaged dependencies</li>
<li>Supports arbitrary expression nesting (see below)</li>
<li>Supports custom operator definitions</li>
<li>Supports type inference</li>
<li>Optimizes tail calls</li>
<li>Has explicit immutable/mutable definitions (nicety -- I've come to love this but can live without it)</li>
<li>Supports real macros for strong metaprogramming (absolute must-have)</li>
</ul>
<p>The primary two languages I've been working with are Boo and Nemerle, but I've also played around with F#.</p>
<p>Main complaints against Nemerle: The compiler has horrid error reporting, the implementation is buggy as hell (compiler and libraries), the macros can only be applied inside a function or as attributes, and it's fairly heavy dependency-wise (although not enough that it's a dealbreaker).<br />
Main complaints against Boo: No arbitrary expression nesting (dealbreaker), macros are difficult to write, no custom operator definition (potential dealbreaker).<br />
Main complaints against F#: Ugly syntax, hard to understand metaprogramming, non-free license (epic dealbreaker).</p>
<p>So the more I think about it, the more I think about developing my own language.</p>
<p>Pros:</p>
<ul>
<li>Get the exact syntax I want</li>
<li>Get a turnaround time that will be a good deal faster; difficult to quantify, but I wouldn't be surprised to see 1.5x developer productivity, especially due to the test infrastructures this can enable for certain projects</li>
<li>I can easily add custom functionality to the compiler to play nicely with my runtime</li>
<li>I get something that is designed and works <i>exactly</i> the way I want -- as much as this sounds like NIH, this will make my life easier</li>
</ul>
<p>Cons:</p>
<ul>
<li>Unless it can get popularity, I will be stuck with the burden of maintenance. I know I can at least get the Nemerle people over, since I think everyone wants something more professional, but it takes a village.</li>
<li>Due to the first con, I'm wary of using it in a professional setting. That said, I'm already using Nemerle and using my own custom modified compiler since they're not maintaining it well at all.</li>
<li>If it doesn't gain popularity, finding developers will be much more difficult, to an extent that <a href="http://www.paulgraham.com/pypar.html" rel="nofollow noreferrer">Paul Graham</a> might not even condone.</li>
</ul>
<p>So based on all of this, what's the general consensus -- is this a good idea or a bad idea? And perhaps more helpfully, have I missed any big pros or cons?</p>
<p>Edit: Forgot to add the nesting example -- here's a case in Nemerle:</p>
<pre><code>def foo =
if(bar == 5)
match(baz) { | "foo" => 1 | _ => 0 }
else bar;
</code></pre>
<p>Edit #2: Figured it wouldn't hurt to give an example of the type of code that will be converted to this language if it's to exist (S. Lott's answer alone may be enough to scare me away from doing it). The code makes heavy use of custom syntax (opcode, :=, quoteblock, etc), expression nesting, etc. You can check a good example out here: <a href="http://ironbabel.svn.sourceforge.net/viewvc/ironbabel/trunk/CPU/IA32/IA32StackMove.n?view=markup" rel="nofollow noreferrer">here</a>.</p>
|
[
{
"answer_id": 193953,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "<p>Writing your own language is not a easy project.. Especially one to be used in any kind of \"professional setting\"</p>\n\n<p>It is a <strong>huge</strong> amount of work, and I would doubt you could write your own language, and still write any big projects that use it - you will spend so long adding features that you need, fixing bugs, and general language-design stuff.</p>\n\n<p>I would <em>strongly</em> recommend choosing a language that is closest to what you want, and extending it to do what you need. It'll never be exactly what you want, but compared to the time you'll spend writing your own language, I would say that's a small compromise..</p>\n"
},
{
"answer_id": 193956,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 5,
"selected": true,
"text": "<p>Sadly, there's no metrics or stories around failed languages. Just successful languages. Clearly, the failures outnumber the successes.</p>\n\n<p>What do I base this on? Two common experiences.</p>\n\n<ol>\n<li><p>Once or twice a year, I have to endure a pitch for a product/language/tool/framework that will Absolutely Change Everything. My answer has been constant for the last 20 or so years. Show me someone who needs support and my company will support them. And that's that. Never hear from them again. Let's say I've heard 25 of these.</p></li>\n<li><p>Once or twice each year, I have to work with a customer who has orphaned technology. At some point in the past, some clever programming built a tool/framework/library/package that was used internally for several projects. Then that programmer left. No one else can figure that darn thing out, and they want us to replace/rewrite it. Sadly, we can't figure it out either, and our proposal is to rewrite from scratch. And they complain that their genius built the set of apps in a period of weeks, it can't take us months to rewrite them in Java/Python/VB/C#. Let's say I've written 25 or so of these kinds of proposals.</p></li>\n</ol>\n\n<p>That's just me, one consultant.</p>\n\n<p>Indeed one particularly sad situation was a company who's entire IT software portfolio was written by one clever guy with a private language and tools. He hadn't left, but he'd realized that his language and toolset had fallen way behind the times -- the state of the art had moved on, and he hadn't. </p>\n\n<p>And the move was -- of course -- in an unexpected direction. His language and tools were okay, but the world had started to adopt relational databases, and he had absolutely no way to upgrade his junk to move away from flat files. It was something he had not foreseen. Indeed, it was something he could not possibly foresee. [You won't fall into this trap, will you?]</p>\n\n<p>So, we talked. He rewrote a lot of the applications in Plain-Old VAX Fortran (yes, this is a long time ago.) And he rewrote it to use plain old relational SQL stuff (Ingres, at the time.)</p>\n\n<p>After a year of coding, they were having performance problems. They called me back to review all the great stuff they'd done in replacing the home-built language. Sadly, they'd done the worst possible relational database design. Worst possible. They'd taken their file copies, merges, sorts, and what-not, and implemented each low-level file system operation using SQL, duplicating database rows left, right and center.</p>\n\n<p>He was so mired in his private vision of the perfect language, that he couldn't adapt to a relatively common, pervasive new technology.</p>\n"
},
{
"answer_id": 193957,
"author": "Marcin",
"author_id": 21640,
"author_profile": "https://Stackoverflow.com/users/21640",
"pm_score": 2,
"selected": false,
"text": "<p>NEVER EVER develop your own language.</p>\n\n<p>Developing your own language is a fool's trap, and worse it will limit you to what your imagination can provide, as well demanding that you work out both your development environment and the actual programme you're writing.</p>\n\n<p>The cases in which this doesn't apply are pretty much if you're Larry Wall, the AWK guys, or part of a substantial group of people dedicated to testing the boundaries of programming. If you're in any of those categories, you don't need my advice, but I strongly doubt that you're targeting a niche where there is no suitable programming language for the task AND the characteristics of the people doing the task.</p>\n"
},
{
"answer_id": 193959,
"author": "sepang",
"author_id": 25930,
"author_profile": "https://Stackoverflow.com/users/25930",
"pm_score": 0,
"selected": false,
"text": "<p>It would be interesting to hear some of the things you feel you can't do in existing languages. What kind of projects are you working on that can't be done in C#?</p>\n\n<p>I'm just curios!</p>\n"
},
{
"answer_id": 193968,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>If you are as clever as you seem to be (a likely possibility), my advice is to go ahead and do the design of the language first, iterate a couple of times over it, ask some smart fellows you trust in smart programming language related communities about the concrete design you came up with and then take the decision.</p>\n\n<p>You might realize in the process of creating the design that just a quick hack on Nemerle would give it all you need, for example. Many things can happen just when thinking hard about a problem, and the final solution might not be what you actually had in mind when beginning the project.</p>\n\n<p>Worst case scenario, you're stuck with actually implementing the design, but by then you will have it proof read and mature, and you'll know with a high degree of certainty that it was a good path to take.</p>\n\n<p>A related piece of advice, start small, just define the features you absolutely need and then build on them to get the rest.</p>\n"
},
{
"answer_id": 193969,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I say go for it.</p>\n\n<ul>\n<li>It would be an awesome experience regardless of weather it makes it to production or not.</li>\n<li>If you make it compile down to IL then you do not have to worry about not being able to re-use your compiled assemblies with C#</li>\n<li>If you believe that you have valid complaints about the languages you listed above, it is likely that many will think like you. Of course, for every 1000 interested person there might be 1 willing to help you maintain it - but that is always the risk</li>\n</ul>\n\n<p>But here are a few things to be cautioned about:</p>\n\n<ul>\n<li>Get your language specification IN STONE before development. Make sure any and all language features are figured out before hand - even things that you may only want in the future. In my opinion, C# is slowly falling into the \"oh-just-one-more-language-extension\" trap that will lead to its eventual doom.</li>\n<li>Be sure to make it optimized. I dont know what you already know; but if you dont know then learn ;) Nobody will want a language that has nice syntax but runs as slow as IE's javascript implementation.</li>\n</ul>\n\n<p>Good luck :D</p>\n"
},
{
"answer_id": 194055,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 2,
"selected": false,
"text": "<p>Scala has a .NET compiler. I don't know the status of this though. It's kind of a second class citizen in the Scala world (which is more focused on the JVM). But it might be a good tradeof to adopt the .NET compiler instead of creating a new language from scratch.</p>\n\n<p>Scala is kind of weak in the meta-programming department ATM. It's possible that the need for metaprogramming is somewhat reduced by other language features. In any case I don't think anyone would be sad if you were to implement metaprogramming features for it. Also there is a compiler plug-in infrastructure on the way.</p>\n"
},
{
"answer_id": 194123,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 3,
"selected": false,
"text": "<p>When I first started my career in the early 90s, there seemed to be this craze of everyone developing their own in-house languages. My first <em>3</em> jobs were with companies that had done this. One company had even developed their own operating system!</p>\n\n<p>From experience, I'd say this is a bad idea for the following reasons:</p>\n\n<p>1) You will spend time debugging the language itself in addition to the code base on top of it<br>\n2) Any developers you hire will need to go through the learning curve of the language<br>\n3) It will be hard to attract and keep developers since working in a proprietary language is a dead-end for someone's career</p>\n\n<p>The main reason I left those three jobs was because they had proprietary languages and you'll notice that not many companies take this route any more :).</p>\n\n<p>An additional argument I'd make is that most languages have entire teams whose full time job it is to develop the language. Maybe you'd be an exception, but I'd be very surprised if you'd be able to match that level of development by only working on the language part-time.</p>\n"
},
{
"answer_id": 194136,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 1,
"selected": false,
"text": "<p>I think most languages will never fit all of the bill. </p>\n\n<p>You might want to combine your 2 favourite languages (in my case C# and <a href=\"http://codeplex.com/IronScheme\" rel=\"nofollow noreferrer\">Scheme</a>) and use them together.</p>\n\n<p>From a professional point of view, this probably not a good idea though.</p>\n"
},
{
"answer_id": 4931761,
"author": "NN_",
"author_id": 558098,
"author_profile": "https://Stackoverflow.com/users/558098",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Main complaints against Nemerle: The\n compiler has horrid error reporting,\n the implementation is buggy as hell\n (compiler and libraries), the macros\n can only be applied inside a function\n or as attributes, and it's fairly\n heavy dependency-wise (although not\n enough that it's a dealbreaker).</p>\n</blockquote>\n\n<p>I see your post has been written more than two years ago.\nI advise you trying Nemerle language today.\nThe compiler is stable. There are no blocker bugs for today.\nThe VS integration has a lot of improvements , also there is SharpDevelop integration.</p>\n\n<p>If you give it a chance, you won't be disappointed.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4977/"
] |
For a long time I've been trying different languages to find the feature-set I want and I've not been able to find it. I have languages that fit decently for various projects of mine, but I've come up with an intersection of these languages that will allow me to do 99.9% of my projects in a single language. I want the following:
* Built on top of .NET or has a .NET implementation
* Has few dependencies on the .NET runtime both at compile-time and runtime (this is important since one of the major use cases is in embedded development where the .NET runtime is completely custom)
* Has a compiler that is 100% .NET code with no unmanaged dependencies
* Supports arbitrary expression nesting (see below)
* Supports custom operator definitions
* Supports type inference
* Optimizes tail calls
* Has explicit immutable/mutable definitions (nicety -- I've come to love this but can live without it)
* Supports real macros for strong metaprogramming (absolute must-have)
The primary two languages I've been working with are Boo and Nemerle, but I've also played around with F#.
Main complaints against Nemerle: The compiler has horrid error reporting, the implementation is buggy as hell (compiler and libraries), the macros can only be applied inside a function or as attributes, and it's fairly heavy dependency-wise (although not enough that it's a dealbreaker).
Main complaints against Boo: No arbitrary expression nesting (dealbreaker), macros are difficult to write, no custom operator definition (potential dealbreaker).
Main complaints against F#: Ugly syntax, hard to understand metaprogramming, non-free license (epic dealbreaker).
So the more I think about it, the more I think about developing my own language.
Pros:
* Get the exact syntax I want
* Get a turnaround time that will be a good deal faster; difficult to quantify, but I wouldn't be surprised to see 1.5x developer productivity, especially due to the test infrastructures this can enable for certain projects
* I can easily add custom functionality to the compiler to play nicely with my runtime
* I get something that is designed and works *exactly* the way I want -- as much as this sounds like NIH, this will make my life easier
Cons:
* Unless it can get popularity, I will be stuck with the burden of maintenance. I know I can at least get the Nemerle people over, since I think everyone wants something more professional, but it takes a village.
* Due to the first con, I'm wary of using it in a professional setting. That said, I'm already using Nemerle and using my own custom modified compiler since they're not maintaining it well at all.
* If it doesn't gain popularity, finding developers will be much more difficult, to an extent that [Paul Graham](http://www.paulgraham.com/pypar.html) might not even condone.
So based on all of this, what's the general consensus -- is this a good idea or a bad idea? And perhaps more helpfully, have I missed any big pros or cons?
Edit: Forgot to add the nesting example -- here's a case in Nemerle:
```
def foo =
if(bar == 5)
match(baz) { | "foo" => 1 | _ => 0 }
else bar;
```
Edit #2: Figured it wouldn't hurt to give an example of the type of code that will be converted to this language if it's to exist (S. Lott's answer alone may be enough to scare me away from doing it). The code makes heavy use of custom syntax (opcode, :=, quoteblock, etc), expression nesting, etc. You can check a good example out here: [here](http://ironbabel.svn.sourceforge.net/viewvc/ironbabel/trunk/CPU/IA32/IA32StackMove.n?view=markup).
|
Sadly, there's no metrics or stories around failed languages. Just successful languages. Clearly, the failures outnumber the successes.
What do I base this on? Two common experiences.
1. Once or twice a year, I have to endure a pitch for a product/language/tool/framework that will Absolutely Change Everything. My answer has been constant for the last 20 or so years. Show me someone who needs support and my company will support them. And that's that. Never hear from them again. Let's say I've heard 25 of these.
2. Once or twice each year, I have to work with a customer who has orphaned technology. At some point in the past, some clever programming built a tool/framework/library/package that was used internally for several projects. Then that programmer left. No one else can figure that darn thing out, and they want us to replace/rewrite it. Sadly, we can't figure it out either, and our proposal is to rewrite from scratch. And they complain that their genius built the set of apps in a period of weeks, it can't take us months to rewrite them in Java/Python/VB/C#. Let's say I've written 25 or so of these kinds of proposals.
That's just me, one consultant.
Indeed one particularly sad situation was a company who's entire IT software portfolio was written by one clever guy with a private language and tools. He hadn't left, but he'd realized that his language and toolset had fallen way behind the times -- the state of the art had moved on, and he hadn't.
And the move was -- of course -- in an unexpected direction. His language and tools were okay, but the world had started to adopt relational databases, and he had absolutely no way to upgrade his junk to move away from flat files. It was something he had not foreseen. Indeed, it was something he could not possibly foresee. [You won't fall into this trap, will you?]
So, we talked. He rewrote a lot of the applications in Plain-Old VAX Fortran (yes, this is a long time ago.) And he rewrote it to use plain old relational SQL stuff (Ingres, at the time.)
After a year of coding, they were having performance problems. They called me back to review all the great stuff they'd done in replacing the home-built language. Sadly, they'd done the worst possible relational database design. Worst possible. They'd taken their file copies, merges, sorts, and what-not, and implemented each low-level file system operation using SQL, duplicating database rows left, right and center.
He was so mired in his private vision of the perfect language, that he couldn't adapt to a relatively common, pervasive new technology.
|
193,973 |
<p>It obviously depends on the context you are using them in but, I was wondering if there is a universally accepted way to name such variables, or at least in a mathematical context.</p>
<p>I've often seen:</p>
<pre><code>float k = someValue;
float oneMinusK = 1 - k;
</code></pre>
<p>...which seems as descriptive as much as meaningless to me. </p>
<p>Please note that I'm not asking how to name a variable, but how to do it in this very case. Examples and contexts where you used them will be much appreciated,</p>
<p>Thanks.</p>
|
[
{
"answer_id": 193975,
"author": "Scott James",
"author_id": 6715,
"author_profile": "https://Stackoverflow.com/users/6715",
"pm_score": 3,
"selected": false,
"text": "<p>You should name your variables based on what it means in terms of the domain you are working on not the algorithm you used to produce it. Thus if k represented your house number k-1 may represent your next door neighbors house number. Name it accordingly.</p>\n"
},
{
"answer_id": 193978,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": true,
"text": "<p>In probability 1-k is the probability of X not occurring, given that k is the probability of X occurring.</p>\n\n<p>So</p>\n\n<pre><code>float will_win_lottery = 0.00000000001;\nfloat will_not_win_lottery = 1 - will_win_lottery;\n</code></pre>\n"
},
{
"answer_id": 193981,
"author": "moo",
"author_id": 23107,
"author_profile": "https://Stackoverflow.com/users/23107",
"pm_score": -1,
"selected": false,
"text": "<p>Does it really matter? Use i; it's not any less descriptive than k. Things like this need to be documented/commented if you're that OCD about code descriptiveness.</p>\n"
},
{
"answer_id": 193993,
"author": "Dan Dyer",
"author_id": 5171,
"author_profile": "https://Stackoverflow.com/users/5171",
"pm_score": 3,
"selected": false,
"text": "<p>I would call it the <a href=\"http://en.wikipedia.org/wiki/Complement_(mathematics)\" rel=\"nofollow noreferrer\">Complement</a>.</p>\n"
},
{
"answer_id": 194011,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "<p>I would probably calculate that when I needed it. How much time do you think it saves to store it in a variable? Remember that premature optimization is the root of all evil.</p>\n"
},
{
"answer_id": 194023,
"author": "Ande Turner",
"author_id": 4857,
"author_profile": "https://Stackoverflow.com/users/4857",
"pm_score": 0,
"selected": false,
"text": "<p>Are these supposed to be constants ?</p>\n\n<p>If you are doing it for legibility reasons exclusively why not create a method a la Dan's suggestion.</p>\n\n<pre><code>float complement(float n) { return (1.0 - n); }\n</code></pre>\n"
},
{
"answer_id": 194092,
"author": "Turnkey",
"author_id": 13144,
"author_profile": "https://Stackoverflow.com/users/13144",
"pm_score": 0,
"selected": false,
"text": "<p>Your usage already seems descriptive enough, just go with it.</p>\n"
},
{
"answer_id": 217276,
"author": "Hannes Landeholm",
"author_id": 29442,
"author_profile": "https://Stackoverflow.com/users/29442",
"pm_score": 1,
"selected": false,
"text": "<p>There is no way to answer your question without knowing what \"k\" represents. Ironicly, the reason why that is not possible is the poor naming of the variable \"k\" in the first place, so that is what you should worry about instead. If you give \"k\" a more describing name, a good choise of naming for \"k-1\" should come naturally, like in the example of \"will_win_lottery\" and \"will_not_win_lottery\".</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7839/"
] |
It obviously depends on the context you are using them in but, I was wondering if there is a universally accepted way to name such variables, or at least in a mathematical context.
I've often seen:
```
float k = someValue;
float oneMinusK = 1 - k;
```
...which seems as descriptive as much as meaningless to me.
Please note that I'm not asking how to name a variable, but how to do it in this very case. Examples and contexts where you used them will be much appreciated,
Thanks.
|
In probability 1-k is the probability of X not occurring, given that k is the probability of X occurring.
So
```
float will_win_lottery = 0.00000000001;
float will_not_win_lottery = 1 - will_win_lottery;
```
|
193,994 |
<p>I'm writing a construct in PHP where a parser determins which function to call dynamically, kind of like this:</p>
<pre><code>// The definition of what to call
$function_call_spec = array( "prototype" => "myFunction",
"parameters" => array( "first_par" => "Hello",
"second_par" => "World"));
// Dispatch
$funcPrototype = $function_call_spec["prototype"];
$funcPrototype(); // Here we call function 'myFunction'.
</code></pre>
<p>This is all fine and dandy. But now comes the next step, passing the parameters, which I don't really know if it's possible the way I want to do it. It never stops amazing me however what script languages can do these days, so here goes:</p>
<p>One could pass the parameters to the function like this:</p>
<pre><code>// Here we call function 'myFunction' with the array of parameters.
$funcPrototype( $function_call_spec["parameters"] );
</code></pre>
<p>However, I want to declare 'myFunction' properly with clear arguments etc:</p>
<pre><code>function myFunction( $first_par, $second_par )
{
}
</code></pre>
<p>The question then follows - Is there any way to pass parameters to a function dynamically simply by looping through the parameter array?</p>
<p>To clarify, I <strong>don't</strong> want to do it like this:</p>
<pre><code>$funcPrototype( $function_call_spec["parameters"]["first_par"],
$function_call_spec["parameters"]["second_par"] );
</code></pre>
<p>Because this requires my code to statically know details about myFunction, which goes against the whole idea.</p>
<p>Instead I would want to do it in some way like this maybe:</p>
<pre><code>// Special magic PHP function which can be used for invoking functions dynamically
InvokeFunction( $funcPrototype, $function_call_spec["parameters"] );
</code></pre>
<p>Which then results in myFunction being called and all parameters in the array gets passed to each individual parameter variable in the prototype.</p>
<p>Any comments are welcome.</p>
<p>Regards.</p>
<p>/R</p>
<p>PS: None of the code in this post has been tested for typos etc.</p>
|
[
{
"answer_id": 193998,
"author": "moo",
"author_id": 23107,
"author_profile": "https://Stackoverflow.com/users/23107",
"pm_score": 3,
"selected": false,
"text": "<pre><code>call_user_func_array($funcPrototype, $function_call_spec[\"parameters\"]);\n</code></pre>\n\n<p>You might want to create a wrapper that names the function to your preference, such as:</p>\n\n<pre><code>function InvokeFunction($function, $args = array()) {\n return call_user_func_array($function, (array)$args);\n}\n</code></pre>\n\n<p>With this function you can call it in 3 different ways:</p>\n\n<pre><code>$return = InvokeFunction('doStuff');\n$return = InvokeFunction('doStuff', $single_arg);\n$return = InvokeFunction('doStuff', $multiple_args);\n</code></pre>\n"
},
{
"answer_id": 194000,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 5,
"selected": true,
"text": "<p>You should use <a href=\"http://php.net/call_user_func_array\" rel=\"noreferrer\"><code>call_user_func_array</code></a> which can call any function or method and takes parameteres from an array.</p>\n\n<p>Alternatively you can use <a href=\"http://php.net/manual/en/language.oop5.reflection.php#language.oop5.reflection.reflectionfunction\" rel=\"noreferrer\"><code>ReflectionFunction::invokeArgs</code></a>, but there's no benefit over <code>call_user_func_array</code> unless you already use this class for someting else (like checking whether function you call accepts appropriate number and types of arguments).</p>\n"
},
{
"answer_id": 194047,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p><code>call_user_func_array()</code> is the best choice if you don't need to enforce the contract, otherwise use <code>ReflectionFunction</code>.</p>\n"
},
{
"answer_id": 492937,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://us2.php.net/create_function\" rel=\"nofollow noreferrer\">http://us2.php.net/create_function</a></p>\n\n<p>When you use create_function(), your arguments are not evaluated until runtime. Pretty sweet.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/193994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7891/"
] |
I'm writing a construct in PHP where a parser determins which function to call dynamically, kind of like this:
```
// The definition of what to call
$function_call_spec = array( "prototype" => "myFunction",
"parameters" => array( "first_par" => "Hello",
"second_par" => "World"));
// Dispatch
$funcPrototype = $function_call_spec["prototype"];
$funcPrototype(); // Here we call function 'myFunction'.
```
This is all fine and dandy. But now comes the next step, passing the parameters, which I don't really know if it's possible the way I want to do it. It never stops amazing me however what script languages can do these days, so here goes:
One could pass the parameters to the function like this:
```
// Here we call function 'myFunction' with the array of parameters.
$funcPrototype( $function_call_spec["parameters"] );
```
However, I want to declare 'myFunction' properly with clear arguments etc:
```
function myFunction( $first_par, $second_par )
{
}
```
The question then follows - Is there any way to pass parameters to a function dynamically simply by looping through the parameter array?
To clarify, I **don't** want to do it like this:
```
$funcPrototype( $function_call_spec["parameters"]["first_par"],
$function_call_spec["parameters"]["second_par"] );
```
Because this requires my code to statically know details about myFunction, which goes against the whole idea.
Instead I would want to do it in some way like this maybe:
```
// Special magic PHP function which can be used for invoking functions dynamically
InvokeFunction( $funcPrototype, $function_call_spec["parameters"] );
```
Which then results in myFunction being called and all parameters in the array gets passed to each individual parameter variable in the prototype.
Any comments are welcome.
Regards.
/R
PS: None of the code in this post has been tested for typos etc.
|
You should use [`call_user_func_array`](http://php.net/call_user_func_array) which can call any function or method and takes parameteres from an array.
Alternatively you can use [`ReflectionFunction::invokeArgs`](http://php.net/manual/en/language.oop5.reflection.php#language.oop5.reflection.reflectionfunction), but there's no benefit over `call_user_func_array` unless you already use this class for someting else (like checking whether function you call accepts appropriate number and types of arguments).
|
194,077 |
<p>I've just recently setup a custom replication for my subscriber database, as described in <a href="https://stackoverflow.com/questions/161890/how-do-you-track-the-time-of-replicated-rows-for-subscribers-in-sql-server-2005">another post here</a>. Basically, when the publisher pushes a new record to the subscribers, the stored procedure will also insert a replicated time into an extra column in the table, and insert a new record to a log table.</p>
<p>My problem occurs when trying to replicate the log table back to the main publication database. This is what I did:</p>
<ol>
<li>In the database where the log table is located, I setup a new transactional replication, and set it to create a snapshot.</li>
<li>Once the publication is created, I create a new push subscription, and set it to initialize immediately.</li>
<li>Once the subscription is created, I checked the synchronization status and confirm that the snapshot is applied successfully.</li>
</ol>
<p>Now here's the weird part: if I manually add a record to the log table using the SQL Server Management Studio, the record will be replicated fine. If the record is added by the custom replication stored procedure, it will not. The status will always display "No replicated transactions are available".</p>
<p>I have no clue why the publication is behaving this way: I really don't see how it is treating the data inserted by the custom replication stored procedure differently.</p>
<p>Can someone explain what may I've done wrong?</p>
<p><strong>UPDATE:</strong> I finally have an answer for this problem a few months ago, just that I never got around to update this question. We have to log a support call to Microsoft, but we got a working solution.</p>
<p><hr>
<strong>ANSWER:</strong> To resolve the problem, when adding a subscription,
you need to run the script like below:</p>
<pre><code>sp_addsubscription @publication = 'TEST', ..., @loopback_detection = 'false'
</code></pre>
<p>The key to the solution is the last parameter shown above. By default, the generated subscription script will not have this parameter. </p>
|
[
{
"answer_id": 527961,
"author": "Timbo",
"author_id": 20992,
"author_profile": "https://Stackoverflow.com/users/20992",
"pm_score": 0,
"selected": false,
"text": "<p>I see this is a very old question now so you've probably resolved this, but anyway...</p>\n\n<p>The problem you describe certainly doesn't seem to make sense. The replication will be invoked further to any change to the source table via the replication trigger. The only thing that doesn't look right in your process description (though I may be misreading) is that you are creating a snapshot before pushing the subscription. Typically you should be setting up the replication, pushing the subscription and then creating / pushing a snapshot. Don't trust the sync status as this isn't checking anything, it's simply saying it has no transactions to copy, it doesn't know that the tables are synched.</p>\n\n<p>As to why your manual insert works but not the automated one I would check and recheck your workings, as fundamentally, if the replication is working then any change to this table will be replicated, irrespective of the source.</p>\n\n<p>If you have long since resolved this I'd be interested to hear the resolution.</p>\n\n<p>Edit:</p>\n\n<p>A late thought: when you are updating your datetime field using your custom proc that then fires triggers back into the replication database, you could be causing deadlocking problems between the replication model and your inserts. This could potentially be causing the failure to replicate back. Bit complex to figure out without running tests, but it's a possibility.</p>\n"
},
{
"answer_id": 649814,
"author": "alextansc",
"author_id": 19582,
"author_profile": "https://Stackoverflow.com/users/19582",
"pm_score": 2,
"selected": true,
"text": "<p>I finally have an answer for this problem a few months ago, just that I never got around to update this question. We have to log a support call to Microsoft, but we got a working solution.</p>\n\n<p>To resolve the problem, when adding a subscription, you need to run the script like below:</p>\n\n<pre><code>sp_addsubscription @publication = 'TEST', ..., @loopback_detection = 'false'\n</code></pre>\n\n<p>The key to the solution is the last parameter shown above: <strong>@loopback_detection = 'false'</strong>. By default, the generated subscription script will not have this parameter. </p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19582/"
] |
I've just recently setup a custom replication for my subscriber database, as described in [another post here](https://stackoverflow.com/questions/161890/how-do-you-track-the-time-of-replicated-rows-for-subscribers-in-sql-server-2005). Basically, when the publisher pushes a new record to the subscribers, the stored procedure will also insert a replicated time into an extra column in the table, and insert a new record to a log table.
My problem occurs when trying to replicate the log table back to the main publication database. This is what I did:
1. In the database where the log table is located, I setup a new transactional replication, and set it to create a snapshot.
2. Once the publication is created, I create a new push subscription, and set it to initialize immediately.
3. Once the subscription is created, I checked the synchronization status and confirm that the snapshot is applied successfully.
Now here's the weird part: if I manually add a record to the log table using the SQL Server Management Studio, the record will be replicated fine. If the record is added by the custom replication stored procedure, it will not. The status will always display "No replicated transactions are available".
I have no clue why the publication is behaving this way: I really don't see how it is treating the data inserted by the custom replication stored procedure differently.
Can someone explain what may I've done wrong?
**UPDATE:** I finally have an answer for this problem a few months ago, just that I never got around to update this question. We have to log a support call to Microsoft, but we got a working solution.
---
**ANSWER:** To resolve the problem, when adding a subscription,
you need to run the script like below:
```
sp_addsubscription @publication = 'TEST', ..., @loopback_detection = 'false'
```
The key to the solution is the last parameter shown above. By default, the generated subscription script will not have this parameter.
|
I finally have an answer for this problem a few months ago, just that I never got around to update this question. We have to log a support call to Microsoft, but we got a working solution.
To resolve the problem, when adding a subscription, you need to run the script like below:
```
sp_addsubscription @publication = 'TEST', ..., @loopback_detection = 'false'
```
The key to the solution is the last parameter shown above: **@loopback\_detection = 'false'**. By default, the generated subscription script will not have this parameter.
|
194,089 |
<p>Say I've got a string which contains a number. I want to check if this number is an integer.</p>
<h3>Examples</h3>
<pre><code>IsInteger("sss") => false
IsInteger("123") => true
IsInterger("123.45") =>false
</code></pre>
|
[
{
"answer_id": 194091,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 4,
"selected": false,
"text": "<p>You can use int.<a href=\"http://msdn.microsoft.com/en-us/library/f02979c7.aspx\" rel=\"noreferrer\">TryParse</a>. It will return a bool if it can parse the string and set your out parameter to the value</p>\n\n<pre><code> int val;\nif(int.TryParse(inputString, out val))\n{\n //dosomething\n}\n</code></pre>\n"
},
{
"answer_id": 194097,
"author": "Alex McBride",
"author_id": 27059,
"author_profile": "https://Stackoverflow.com/users/27059",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx\" rel=\"nofollow noreferrer\">System.Int32.TryParse</a> and do something like this...</p>\n\n<pre><code>string str = \"10\";\nint number = 0;\nif (int.TryParse(str, out number))\n{\n // True\n}\nelse\n{\n // False\n}\n</code></pre>\n"
},
{
"answer_id": 194105,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 3,
"selected": false,
"text": "<p>There are two immediate options that you can use.</p>\n\n<p><strong>Option 1</strong> - <em>preferred</em> - use <a href=\"http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx\" rel=\"noreferrer\">Int32.TryParse</a>.</p>\n\n<pre><code>int res;\nConsole.WriteLine(int.TryParse(\"sss\", out res));\nConsole.WriteLine(int.TryParse(\"123\", out res));\nConsole.WriteLine(int.TryParse(\"123.45\", out res));\nConsole.WriteLine(int.TryParse(\"123a\", out res));\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code>False\nTrue\nFalse\nFalse\n</code></pre>\n\n<p><strong>Option 2</strong> - use regular expressions</p>\n\n<pre><code>Regex pattern = new Regex(\"^-?[0-9]+$\", RegexOptions.Singleline);\nConsole.WriteLine(pattern.Match(\"sss\").Success);\nConsole.WriteLine(pattern.Match(\"123\").Success);\nConsole.WriteLine(pattern.Match(\"123.45\").Success);\nConsole.WriteLine(pattern.Match(\"123a\").Success);\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code>False\nTrue\nFalse\nFalse\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Say I've got a string which contains a number. I want to check if this number is an integer.
### Examples
```
IsInteger("sss") => false
IsInteger("123") => true
IsInterger("123.45") =>false
```
|
You can use int.[TryParse](http://msdn.microsoft.com/en-us/library/f02979c7.aspx). It will return a bool if it can parse the string and set your out parameter to the value
```
int val;
if(int.TryParse(inputString, out val))
{
//dosomething
}
```
|
194,101 |
<p>I'd like to track changes in inputs in a form via javascript. My intent is (but not limited) to</p>
<ul>
<li>enable "save" button only when something has changed</li>
<li>alert if the user wants to close the page and something is not saved</li>
</ul>
<p>Ideas?</p>
|
[
{
"answer_id": 194110,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 6,
"selected": true,
"text": "<p>Loop through all the input elements, and put an <code>onchange</code> handler on each. When that fires, set a flag which lets you know the form has changed. A basic version of that would be very easy to set up, but wouldn't be smart enough to recognize if someone changed an input from \"a\" to \"b\" and then back to \"a\". If it were important to catch that case, then it'd still be possible, but would take a bit more work.</p>\n\n<p>Here's a basic example in jQuery:</p>\n\n<pre><code>$(\"#myForm\")\n .on(\"input\", function() {\n // do whatever you need to do when something's changed.\n // perhaps set up an onExit function on the window\n $('#saveButton').show();\n })\n;\n</code></pre>\n"
},
{
"answer_id": 194112,
"author": "Dylan Beattie",
"author_id": 5017,
"author_profile": "https://Stackoverflow.com/users/5017",
"pm_score": 4,
"selected": false,
"text": "<p>Text form elements in JS expose a <code>.value</code> property and a <code>.defaultValue</code> property, so you can easily implement something like:</p>\n\n<pre><code>function formChanged(form) {\n for (var i = 0; i < form.elements.length; i++) {\n if(form.elements[i].value != form.elements[i].defaultValue) return(true);\n }\n return(false);\n}\n</code></pre>\n\n<p>For checkboxes and radio buttons see whether <code>element.checked != element.defaultChecked</code>, and for HTML <code><select /></code> elements you'll need to loop over the <code>select.options</code> array and check for each option whether <code>selected == defaultSelected</code>.</p>\n\n<p>You might want to look at using a framework like <a href=\"http://jquery.com/\" rel=\"noreferrer\">jQuery</a> to attach handlers to the <code>onchange</code> event of each individual form element. These handlers can call your <code>formChanged()</code> code and modify the <code>enabled</code> property of your \"save\" button, and/or attach/detach an event handler for the document body's <code>beforeunload</code> event.</p>\n"
},
{
"answer_id": 194113,
"author": "Gene T",
"author_id": 413049,
"author_profile": "https://Stackoverflow.com/users/413049",
"pm_score": 2,
"selected": false,
"text": "<p>If your using a web app framework (rails, ASP.NET, Cake, symfony), there should be packages for ajax validation, </p>\n\n<p><a href=\"http://webtecker.com/2008/03/17/list-of-ajax-form-validators/\" rel=\"nofollow noreferrer\">http://webtecker.com/2008/03/17/list-of-ajax-form-validators/</a></p>\n\n<p>and some wrapper on onbeforeunload() to warn users taht are about to close the form:</p>\n\n<p><a href=\"http://pragmatig.wordpress.com/2008/03/03/protecting-userdata-from-beeing-lost-with-jquery/\" rel=\"nofollow noreferrer\">http://pragmatig.wordpress.com/2008/03/03/protecting-userdata-from-beeing-lost-with-jquery/</a>\n<a href=\"https://stackoverflow.com/questions/155739/detecting-unsaved-changes-using-javascript\">Detecting Unsaved Changes</a></p>\n"
},
{
"answer_id": 194116,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 0,
"selected": false,
"text": "<p>Attach an event handler to each form input/select/textarea's onchange event. Setting a variable to tell you if you should enable the \"save\" button. Create an onunload hander that checks for a dirty form too, and when the form is submitted reset the variable:</p>\n\n<pre>\nwindow.onunload = checkUnsavedPage;\nvar isDirty = false;\nvar formElements = //Get a reference to all form elements\nfor(var i = 0; len = formElements.length; i++) {\n //Add onchange event to each element to call formChanged()\n}\n\nfunction formChanged(event) {\n isDirty = false;\n document.getElementById(\"savebtn\").disabled = \"\";\n}\n\nfunction checkUnsavedPage() {\n if (isDirty) {\n var isSure = confirm(\"you sure?\"); \n if (!isSure) {\n event.preventDefault();\n }\n }\n}\n</pre>\n"
},
{
"answer_id": 194119,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 1,
"selected": false,
"text": "<p>To alert the user before closing, use unbeforeunload:</p>\n\n<pre><code>window.onbeforeunload = function() {\n return \"You are about to lose your form data.\";\n};\n</code></pre>\n"
},
{
"answer_id": 194347,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 2,
"selected": false,
"text": "<p>I answered a question like this on Ars Technica, but the question was framed such that the changes needed to be detected even if the user does not blur a text field (in which case the change event never fires). I came up with a comprehensive script which:</p>\n\n<ol>\n<li>enables submit and reset buttons if field values change</li>\n<li>disables submit and reset buttons if the form is reset</li>\n<li>interrupts leaving the page if form data has changed and not been submitted</li>\n<li>supports IE 6+, Firefox 2+, Safari 3+ (and presumably Opera but I did not test)</li>\n</ol>\n\n<p>This script depends on Prototype but could be easily adapted to another library or to stand alone.</p>\n\n<pre><code>$(document).observe('dom:loaded', function(e) {\n var browser = {\n trident: !!document.all && !window.opera,\n webkit: (!(!!document.all && !window.opera) && !document.doctype) ||\n (!!window.devicePixelRatio && !!window.getMatchedCSSRules)\n };\n\n // Select form elements that won't bubble up delegated events (eg. onchange)\n var inputs = $('form_id').select('select, input[type=\"radio\"], input[type=\"checkbox\"]');\n\n $('form_id').observe('submit', function(e) {\n // Don't bother submitting if form not modified\n if(!$('form_id').hasClassName('modified')) {\n e.stop();\n return false;\n }\n $('form_id').addClassName('saving');\n });\n\n var change = function(e) {\n // Paste event fires before content has been pasted\n if(e && e.type && e.type == 'paste') {\n arguments.callee.defer();\n return false;\n }\n\n // Check if event actually results in changed data\n if(!e || e.type != 'change') {\n var modified = false;\n $('form_id').getElements().each(function(element) {\n if(element.tagName.match(/^textarea$/i)) {\n if($F(element) != element.defaultValue) {\n modified = true;\n }\n return;\n } else if(element.tagName.match(/^input$/i)) {\n if(element.type.match(/^(text|hidden)$/i) && $F(element) != element.defaultValue) {\n modified = true;\n } else if(element.type.match(/^(checkbox|radio)$/i) && element.checked != element.defaultChecked) {\n modified = true;\n }\n }\n });\n if(!modified) {\n return false;\n }\n }\n\n // Mark form as modified\n $('form_id').addClassName('modified');\n\n // Enable submit/reset buttons\n $('reset_button_id').removeAttribute('disabled');\n $('submit_button_id').removeAttribute('disabled');\n\n // Remove event handlers as they're no longer needed\n if(browser.trident) {\n $('form_id').stopObserving('keyup', change);\n $('form_id').stopObserving('paste', change);\n } else {\n $('form_id').stopObserving('input', change);\n }\n if(browser.webkit) {\n $$('#form_id textarea').invoke('stopObserving', 'keyup', change);\n $$('#form_id textarea').invoke('stopObserving', 'paste', change);\n }\n inputs.invoke('stopObserving', 'change', arguments.callee);\n };\n\n $('form_id').observe('reset', function(e) {\n // Unset form modified, restart modified check...\n $('reset_button_id').writeAttribute('disabled', true);\n $('submit_button_id').writeAttribute('disabled', true);\n $('form_id').removeClassName('modified');\n startObservers();\n });\n\n var startObservers = (function(e) {\n if(browser.trident) {\n $('form_id').observe('keyup', change);\n $('form_id').observe('paste', change);\n } else {\n $('form_id').observe('input', change);\n }\n // Webkit apparently doesn't fire oninput in textareas\n if(browser.webkit) {\n $$('#form_id textarea').invoke('observe', 'keyup', change);\n $$('#form_id textarea').invoke('observe', 'paste', change);\n }\n inputs.invoke('observe', 'change', change);\n return arguments.callee;\n })();\n\n window.onbeforeunload = function(e) {\n if($('form_id').hasClassName('modified') && !$('form_id').hasClassName('saving')) {\n return 'You have unsaved content, would you really like to leave the page? All your changes will be lost.';\n }\n };\n\n});\n</code></pre>\n"
},
{
"answer_id": 194381,
"author": "Jared",
"author_id": 1980,
"author_profile": "https://Stackoverflow.com/users/1980",
"pm_score": 1,
"selected": false,
"text": "<p>I would store each fields value in a variable when the page loads, then compare those values when the user unloads the page. If any differences are detected you will know what to save and better yet, be able to specifically tell the user what data will not be saved if they exit.</p>\n\n<pre><code>// this example uses the prototype library\n// also, it's not very efficient, I just threw it together\nvar valuesAtLoad = [];\nvar valuesOnCheck = [];\nvar isDirty = false;\nvar names = [];\nEvent.observe(window, 'load', function() {\n $$('.field').each(function(i) {\n valuesAtLoad.push($F(i));\n });\n});\n\nvar checkValues = function() {\n var changes = [];\n valuesOnCheck = [];\n $$('.field').each(function(i) {\n valuesOnCheck.push($F(i));\n });\n\n for(var i = 0; i <= valuesOnCheck.length - 1; i++ ) {\n var source = valuesOnCheck[i];\n var compare = valuesAtLoad[i];\n if( source !== compare ) {\n changes.push($$('.field')[i]);\n }\n }\n\n return changes.length > 0 ? changes : [];\n};\n\nsetInterval(function() { names = checkValues().pluck('id'); isDirty = names.length > 0; }, 100);\n\n// notify the user when they exit\nEvent.observe(window, 'beforeunload', function(e) {\n e.returnValue = isDirty ? \"you have changed the following fields: \\r\\n\" + names + \"\\r\\n these changes will be lost if you exit. Are you sure you want to continue?\" : true;\n});\n</code></pre>\n"
},
{
"answer_id": 194412,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a full implementation of <a href=\"https://stackoverflow.com/questions/194101/what-is-the-best-way-to-track-changes-in-a-form-via-javascript#194112\">Dylan Beattie's suggestion</a>:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/140460/clientjs-framework-for-unsaved-data-protection#140508\">Client/JS Framework for "Unsaved Data" Protection?</a></p>\n\n<p>You shouldn't need to store initial values to determine if the form has changed, unless you're populating it dynamically on the client side (although, even then, you could still set up the <code>default</code> properties on the form elements).</p>\n"
},
{
"answer_id": 402395,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can also check out this jQuery plugin I built at <a href=\"http://code.zhandwa.com/jquery/\" rel=\"nofollow noreferrer\">jQuery track changes in forms plugin</a></p>\n\n<p>See the demo <a href=\"http://downloads.zhandwa.com/trackchanges/demo/\" rel=\"nofollow noreferrer\">here</a> and download the JS <a href=\"http://downloads.zhandwa.com/trackchanges/demo/js/jquery.form.track.changes.js\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 15075385,
"author": "satyrFrost",
"author_id": 1530547,
"author_profile": "https://Stackoverflow.com/users/1530547",
"pm_score": 1,
"selected": false,
"text": "<p>I've used dirtyforms.js. Works well for me.</p>\n\n<p><a href=\"http://mal.co.nz/code/jquery-dirty-forms/\" rel=\"nofollow\">http://mal.co.nz/code/jquery-dirty-forms/</a></p>\n"
},
{
"answer_id": 16594921,
"author": "Justin",
"author_id": 922522,
"author_profile": "https://Stackoverflow.com/users/922522",
"pm_score": 0,
"selected": false,
"text": "<p>If you are open to using jQuery, see my answer a similar question: \n<a href=\"https://stackoverflow.com/questions/16593222/disable-submit-button-unless-original-form-data-has-changed/16594431#16594431\">Disable submit button unless original form data has changed</a>.</p>\n"
},
{
"answer_id": 17548306,
"author": "Nikita Makarov",
"author_id": 2564525,
"author_profile": "https://Stackoverflow.com/users/2564525",
"pm_score": 3,
"selected": false,
"text": "<p>Try</p>\n\n<pre><code>function isModifiedForm(form){\n var __clone = $(form).clone();\n __clone[0].reset();\n return $(form).serialize() == $(__clone).serialize();\n}\n</code></pre>\n\n<p>Hope its helps ))</p>\n"
},
{
"answer_id": 19526123,
"author": "skibulk",
"author_id": 1017480,
"author_profile": "https://Stackoverflow.com/users/1017480",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a javascript & jquery method for detecting form changes that is simple. It disables the submit button until changes are made. It detects attempts to leave the page by means other than submitting the form. It accounts for \"undos\" by the user, it is encapsulated within a function for ease of application, and it doesn't misfire on submit. Just call the function and pass the ID of your form.</p>\n\n<p>This function serializes the form once when the page is loaded, and again before the user leaves the page. If the two form states are different, the prompt is shown.</p>\n\n<p>Try it out: <a href=\"http://jsfiddle.net/skibulk/ev5rE/\" rel=\"noreferrer\">http://jsfiddle.net/skibulk/ev5rE/</a></p>\n\n<pre><code>function formUnloadPrompt(formSelector) {\n var formA = $(formSelector).serialize(), formB, formSubmit = false;\n\n // Detect Form Submit\n $(formSelector).submit( function(){\n formSubmit = true;\n });\n\n // Handle Form Unload \n window.onbeforeunload = function(){\n if (formSubmit) return;\n formB = $(formSelector).serialize();\n if (formA != formB) return \"Your changes have not been saved.\";\n };\n\n // Enable & Disable Submit Button\n var formToggleSubmit = function(){\n formB = $(formSelector).serialize();\n $(formSelector+' [type=\"submit\"]').attr( \"disabled\", formA == formB);\n };\n\n formToggleSubmit();\n $(formSelector).change(formToggleSubmit);\n $(formSelector).keyup(formToggleSubmit);\n}\n\n\n\n// Call function on DOM Ready:\n\n$(function(){\n formUnloadPrompt('form');\n});\n</code></pre>\n"
},
{
"answer_id": 20137132,
"author": "Savaratkar",
"author_id": 942301,
"author_profile": "https://Stackoverflow.com/users/942301",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same challenge and i was thinking of a common solution. The code below is not perfect, its from initial r&d. Following are the steps I used:</p>\n\n<p>1) Move the following JS to a another file (say changeFramework.js)</p>\n\n<p>2) Include it in your project by importing it</p>\n\n<p>3) In your html page, whichever control needs monitoring, add the class \"monitorChange\"</p>\n\n<p>4) The global variable 'hasChanged' will tell, if there is any change in the page you working on.</p>\n\n<pre><code><script type=\"text/javascript\" id=\"MonitorChangeFramework\">\n// MONITOR CHANGE FRAMEWORK\n// ALL ELEMENTS WITH CLASS \".monitorChange\" WILL BE REGISTERED FOR CHANGE\n// ON CHANGE IT WILL RAISE A FLAG\nvar hasChanged;\n\nfunction MonitorChange() {\n hasChanged = false;\n $(\".monitorChange\").change(function () {\n hasChanged = true;\n });\n}\n</code></pre>\n\n<p></p>\n\n<p>Following are the controls where I used this framework:</p>\n\n<pre><code><textarea class=\"monitorChange\" rows=\"5\" cols=\"10\" id=\"testArea\"></textarea></br>\n <div id=\"divDrinks\">\n <input type=\"checkbox\" class=\"chb monitorChange\" value=\"Tea\" />Tea </br>\n <input type=\"checkbox\" class=\"chb monitorChange\" value=\"Milk\" checked='checked' />Milk</br>\n <input type=\"checkbox\" class=\"chb monitorChange\" value=\"Coffee\" />Coffee </br>\n </div>\n <select id=\"comboCar\" class=\"monitorChange\">\n <option value=\"volvo\">Volvo</option>\n <option value=\"saab\">Saab</option>\n <option value=\"mercedes\">Mercedes</option>\n <option value=\"audi\">Audi</option>\n </select>\n <button id=\"testButton\">\n test</button><a onclick=\"NavigateTo()\">next >>> </a>\n</code></pre>\n\n<p>I believe there can be huge improvement in this framework. Comment/Changes/feedbacks are welcome. :)</p>\n"
},
{
"answer_id": 29946158,
"author": "Bijan",
"author_id": 306478,
"author_profile": "https://Stackoverflow.com/users/306478",
"pm_score": 1,
"selected": false,
"text": "<p>I did some Cross Browser Testing.</p>\n\n<p>On Chrome and Safari this is nice:</p>\n\n<pre><code><form onchange=\"validate()\">\n...\n</form>\n</code></pre>\n\n<p>For Firefox + Chrome/Safari I go with this:</p>\n\n<pre><code><form onkeydown=\"validate()\">\n ...\n <input type=\"checkbox\" onchange=\"validate()\">\n</form>\n</code></pre>\n\n<p>Items like checkboxes or radiobuttons need an own onchange event listener.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19224/"
] |
I'd like to track changes in inputs in a form via javascript. My intent is (but not limited) to
* enable "save" button only when something has changed
* alert if the user wants to close the page and something is not saved
Ideas?
|
Loop through all the input elements, and put an `onchange` handler on each. When that fires, set a flag which lets you know the form has changed. A basic version of that would be very easy to set up, but wouldn't be smart enough to recognize if someone changed an input from "a" to "b" and then back to "a". If it were important to catch that case, then it'd still be possible, but would take a bit more work.
Here's a basic example in jQuery:
```
$("#myForm")
.on("input", function() {
// do whatever you need to do when something's changed.
// perhaps set up an onExit function on the window
$('#saveButton').show();
})
;
```
|
194,102 |
<p>We have a web service that is deployed on 2 separate machines in different locations. Is it possible to monitor the url that a person used to call our webservice using java code? We have a 3DNS url set up and we want all clients to use this url as oppossed hitting the boxes directly with the correct port numbers in the url.</p>
<p>Thanks
Damien</p>
|
[
{
"answer_id": 196767,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 0,
"selected": false,
"text": "<p>You might look into something like OWSM (Oracle Web Services Manager)... there may be open source alternatives.</p>\n\n<p>OWSM creates a virtual endpoint that it handles and routes to the actual service hosts. This way, your service hosts can be hidden behind the firewall, with only the OWSM host visible to the world. When a user hits the virtual endpoint, OWSM can authenticate and pass them along to the balanced service host.</p>\n"
},
{
"answer_id": 231193,
"author": "Ian McLaird",
"author_id": 18796,
"author_profile": "https://Stackoverflow.com/users/18796",
"pm_score": 0,
"selected": false,
"text": "<p>An alternative might be to use servlet filters on the real endpoints. The filter could do a couple of different things. It could simply log the requested URL from the HttpServletRequest, or it could even redirect to the correct URL for you (I'm not sure what the implications of that are for a web service, though).</p>\n\n<p>All you would have to do is have the filter mapped to the same context path as the web service (axis uses /services/* for example).</p>\n"
},
{
"answer_id": 1861830,
"author": "monksy",
"author_id": 80701,
"author_profile": "https://Stackoverflow.com/users/80701",
"pm_score": 3,
"selected": true,
"text": "<p>Have you taken a look at: </p>\n\n<pre><code>@Resource\nWebServiceContext wsContext;\n</code></pre>\n\n<p>This will return the context of the current message sent to your webservice. I've been able to get the IP address of the user from that.</p>\n\n<p>This is assuming that you are using Java. </p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11612/"
] |
We have a web service that is deployed on 2 separate machines in different locations. Is it possible to monitor the url that a person used to call our webservice using java code? We have a 3DNS url set up and we want all clients to use this url as oppossed hitting the boxes directly with the correct port numbers in the url.
Thanks
Damien
|
Have you taken a look at:
```
@Resource
WebServiceContext wsContext;
```
This will return the context of the current message sent to your webservice. I've been able to get the IP address of the user from that.
This is assuming that you are using Java.
|
194,150 |
<p>How to check reliably if a SoundChannel is still playing a sound? </p>
<p>For example,</p>
<pre><code>[Embed(source="song.mp3")]
var Song: Class;
var s: Song = new Song();
var ch: SoundChannel = s.play();
// how to check if ch is playing?
</code></pre>
|
[
{
"answer_id": 194653,
"author": "James Fassett",
"author_id": 27081,
"author_profile": "https://Stackoverflow.com/users/27081",
"pm_score": 5,
"selected": true,
"text": "<p>I've done a little research and I can't find a way to query any object to determine if a sound is playing. You'll have to write a wrapper class and manage it yourself it seems.</p>\n\n<pre><code>\npackage\n{\n import flash.events.Event;\n import flash.media.Sound;\n import flash.media.SoundChannel;\n\n public class SoundPlayer\n {\n [Embed(source=\"song.mp3\")]\n private var Song:Class;\n\n private var s:Song;\n private var ch:SoundChannel;\n private var isSoundPlaying:Boolean;\n\n public function SoundPlayer()\n {\n s = new Song();\n play();\n }\n\n public function play():void\n {\n if(!isPlaying)\n {\n ch = s.play();\n ch.addEventListener(\n Event.SOUND_COMPLETE,\n handleSoundComplete);\n isSoundPlaying = true;\n }\n }\n\n public function stop():void\n {\n if(isPlaying)\n {\n ch.stop();\n isSoundPlaying = false;\n }\n }\n\n private function handleSoundComplete(ev:Event):void\n {\n isSoundPlaying = false;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 12744906,
"author": "RustyH",
"author_id": 1272209,
"author_profile": "https://Stackoverflow.com/users/1272209",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is really old but i found this link that i think is quite helpful. it explains how to monitor and play a file from a certain point.</p>\n\n<p><a href=\"http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7d21.html\" rel=\"nofollow\">http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7d21.html</a></p>\n"
},
{
"answer_id": 12762031,
"author": "Vesper",
"author_id": 1627055,
"author_profile": "https://Stackoverflow.com/users/1627055",
"pm_score": 1,
"selected": false,
"text": "<p>One of the ways to check if sound is still playing, and not using any managers, would be checking soundChannel.position in two consecutive enterFrame listener calls, if mismatched, then the sound is still playing.</p>\n\n<pre><code>private var oldPosition:Number;\nfunction onEnterFrame(e:Event):void {\n var stillPlaying:Boolean;\n var newPosition=soundChannel.position;\n if (newPosition-oldPosition>1) stillPlaying=true; else stillPlaying=false;\n oldPosition=newPosition;\n}\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11238/"
] |
How to check reliably if a SoundChannel is still playing a sound?
For example,
```
[Embed(source="song.mp3")]
var Song: Class;
var s: Song = new Song();
var ch: SoundChannel = s.play();
// how to check if ch is playing?
```
|
I've done a little research and I can't find a way to query any object to determine if a sound is playing. You'll have to write a wrapper class and manage it yourself it seems.
```
package
{
import flash.events.Event;
import flash.media.Sound;
import flash.media.SoundChannel;
public class SoundPlayer
{
[Embed(source="song.mp3")]
private var Song:Class;
private var s:Song;
private var ch:SoundChannel;
private var isSoundPlaying:Boolean;
public function SoundPlayer()
{
s = new Song();
play();
}
public function play():void
{
if(!isPlaying)
{
ch = s.play();
ch.addEventListener(
Event.SOUND_COMPLETE,
handleSoundComplete);
isSoundPlaying = true;
}
}
public function stop():void
{
if(isPlaying)
{
ch.stop();
isSoundPlaying = false;
}
}
private function handleSoundComplete(ev:Event):void
{
isSoundPlaying = false;
}
}
}
```
|
194,157 |
<p>I'm using:</p>
<pre><code>FileInfo(
System.Environment.GetFolderPath(
System.Environment.SpecialFolder.ProgramFiles)
+ @"\MyInstalledApp"
</code></pre>
<p>In order to determine if a program is detected on a users machine (it's not ideal, but the program I'm looking for is a right old kludge of a MS-DOS application, and I couldn't think of another method).</p>
<p>On Windows XP and 32-bit versions of Windows Vista this works fine. However, on x64 Windows Vista the code returns the x64 Program Files folder, whereas the application is installed in Program Files x86. Is there a way to programatically return the path to Program Files x86 without hard wiring "C:\Program Files (x86)"?</p>
|
[
{
"answer_id": 194163,
"author": "tomasr",
"author_id": 10292,
"author_profile": "https://Stackoverflow.com/users/10292",
"pm_score": 3,
"selected": false,
"text": "<p>One way would be to look for the \"ProgramFiles(x86)\" environment variable:</p>\n\n<pre><code>String x86folder = Environment.GetEnvironmentVariable(\"ProgramFiles(x86)\");\n</code></pre>\n"
},
{
"answer_id": 194191,
"author": "chadmyers",
"author_id": 10862,
"author_profile": "https://Stackoverflow.com/users/10862",
"pm_score": 4,
"selected": false,
"text": "<p>Note, however, that the <code>ProgramFiles(x86)</code> environment variable is only available if your application is running 64-bit.</p>\n\n<p>If your application is running 32-bit, you can just use the <code>ProgramFiles</code> environment variable whose value will actually be \"Program Files (x86)\".</p>\n"
},
{
"answer_id": 194223,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 9,
"selected": true,
"text": "<p>The function below will return the x86 <code>Program Files</code> directory in all of these three Windows configurations:</p>\n\n<ul>\n<li>32 bit Windows</li>\n<li>32 bit program running on 64 bit Windows</li>\n<li>64 bit program running on 64 bit windows</li>\n</ul>\n\n<p> </p>\n\n<pre><code>static string ProgramFilesx86()\n{\n if( 8 == IntPtr.Size \n || (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable(\"PROCESSOR_ARCHITEW6432\"))))\n {\n return Environment.GetEnvironmentVariable(\"ProgramFiles(x86)\");\n }\n\n return Environment.GetEnvironmentVariable(\"ProgramFiles\");\n}\n</code></pre>\n"
},
{
"answer_id": 4442467,
"author": "Carl Hörberg",
"author_id": 80589,
"author_profile": "https://Stackoverflow.com/users/80589",
"pm_score": 5,
"selected": false,
"text": "<pre><code>Environment.GetEnvironmentVariable(\"PROGRAMFILES(X86)\") ?? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)\n</code></pre>\n"
},
{
"answer_id": 4514110,
"author": "Nathan",
"author_id": 506520,
"author_profile": "https://Stackoverflow.com/users/506520",
"pm_score": 7,
"selected": false,
"text": "<p>If you're using .NET 4, there is a special folder enumeration <a href=\"http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx\" rel=\"noreferrer\">ProgramFilesX86</a>:</p>\n\n<pre><code>Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)\n</code></pre>\n"
},
{
"answer_id": 5140124,
"author": "Samir",
"author_id": 637418,
"author_profile": "https://Stackoverflow.com/users/637418",
"pm_score": 3,
"selected": false,
"text": "<p>I am writing an application which can run on both x86 and x64 platform for Windows 7 and querying the below variable just pulls the right program files folder path on any platform.</p>\n\n<pre><code>Environment.GetEnvironmentVariable(\"PROGRAMFILES\")\n</code></pre>\n"
},
{
"answer_id": 50842101,
"author": "Red John",
"author_id": 3721646,
"author_profile": "https://Stackoverflow.com/users/3721646",
"pm_score": 0,
"selected": false,
"text": "<p>One-liner using the new method in .NET. Will always return x86 Program Files folder.</p>\n\n<p><code>Environment.Is64BitOperatingSystem ? Environment.GetEnvironmentVariable(\"ProgramFiles(x86)\") : Environment.GetEnvironmentVariable(\"ProgramFiles\"))</code></p>\n"
},
{
"answer_id": 59478187,
"author": "Clint",
"author_id": 4686729,
"author_profile": "https://Stackoverflow.com/users/4686729",
"pm_score": 0,
"selected": false,
"text": "<p><strong>C# Code:</strong></p>\n<p><strong><code>Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)</code></strong></p>\n<p><strong>Output:</strong></p>\n<p><em>C:\\Program Files (x86)</em></p>\n<p><strong>Note:</strong></p>\n<p>We need to tell the compiler to not prefer a particular build platform.</p>\n<pre><code>Go to Visual Studio > Project Properties > Build > Uncheck "Prefer 32 bit"\n</code></pre>\n<p><strong>Reason:</strong></p>\n<blockquote>\n<p>By default for most .NET Projects is "Any CPU 32-bit preferred"</p>\n<p>When you uncheck 32 bit assembly will:</p>\n<p>JIT to 32-bit code on 32 bit process</p>\n<p>JIT to 32-bit code on 64 bit process</p>\n</blockquote>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1293123/"
] |
I'm using:
```
FileInfo(
System.Environment.GetFolderPath(
System.Environment.SpecialFolder.ProgramFiles)
+ @"\MyInstalledApp"
```
In order to determine if a program is detected on a users machine (it's not ideal, but the program I'm looking for is a right old kludge of a MS-DOS application, and I couldn't think of another method).
On Windows XP and 32-bit versions of Windows Vista this works fine. However, on x64 Windows Vista the code returns the x64 Program Files folder, whereas the application is installed in Program Files x86. Is there a way to programatically return the path to Program Files x86 without hard wiring "C:\Program Files (x86)"?
|
The function below will return the x86 `Program Files` directory in all of these three Windows configurations:
* 32 bit Windows
* 32 bit program running on 64 bit Windows
* 64 bit program running on 64 bit windows
```
static string ProgramFilesx86()
{
if( 8 == IntPtr.Size
|| (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
{
return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
}
return Environment.GetEnvironmentVariable("ProgramFiles");
}
```
|
194,165 |
<p>I'm using the standard <code>ConsoleHandler</code> from <code>java.util.logging</code> and by default the console output is directed to the error stream (i.e. <code>System.err</code>).</p>
<p>How do I change the console output to the output stream (i.e. <code>System.out</code>)?</p>
|
[
{
"answer_id": 194198,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>Have a look at the docs and source for <a href=\"http://java.sun.com/javase/6/docs/api/java/util/logging/ConsoleHandler.html\" rel=\"nofollow noreferrer\">ConsoleHandler</a> - I'm sure you could easily write a version which just uses System.err instead of System.out. (It's a shame that ConsoleHandler doesn't allow this to be configured, to be honest.)</p>\n\n<p>Then it's just a case of configuring the logging system to use your new StdoutHandler (or whatever you call it) in the normal way.</p>\n"
},
{
"answer_id": 194202,
"author": "Uri",
"author_id": 23072,
"author_profile": "https://Stackoverflow.com/users/23072",
"pm_score": 2,
"selected": false,
"text": "<p>If you use Java logging, you can change the default handler:</p>\n<p>For example, for files:</p>\n<pre><code>Handler fh = new FileHandler(FILENAME);\nLogger.getLogger(LOGGER_NAME).addHandler(fh);\n</code></pre>\n<p>If you want to output to a stream you can use StreamHandler, I think you can configure it with any output stream that you woud like, including the system stream.</p>\n"
},
{
"answer_id": 194851,
"author": "Obediah Stane",
"author_id": 23120,
"author_profile": "https://Stackoverflow.com/users/23120",
"pm_score": 3,
"selected": false,
"text": "<p>I figured out one way. First remove the default console handler:</p>\n<pre><code>setUseParentHandlers(false);\n</code></pre>\n<p>Then subclass ConsoleHandler and in the constructor:</p>\n<pre><code>setOutputStream(System.out);\n</code></pre>\n"
},
{
"answer_id": 379626,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>If you set setUseParentHandlers(false); only THAT class has it set. Other classes in the app will still pass it thru to stderr.</p>\n"
},
{
"answer_id": 1604066,
"author": "Hema",
"author_id": 194182,
"author_profile": "https://Stackoverflow.com/users/194182",
"pm_score": -1,
"selected": false,
"text": "<p>Simply extend StreamHandler & in the constructor call Super(System.out,). This will avoid closing System.err - Thanks </p>\n"
},
{
"answer_id": 2906222,
"author": "Jeremiah Jahn",
"author_id": 350068,
"author_profile": "https://Stackoverflow.com/users/350068",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Handler consoleHandler = new Handler(){\n @Override\n public void publish(LogRecord record)\n {\n if (getFormatter() == null)\n {\n setFormatter(new SimpleFormatter());\n }\n\n try {\n String message = getFormatter().format(record);\n if (record.getLevel().intValue() >= Level.WARNING.intValue())\n {\n System.err.write(message.getBytes()); \n }\n else\n {\n System.out.write(message.getBytes());\n }\n } catch (Exception exception) {\n reportError(null, exception, ErrorManager.FORMAT_FAILURE);\n }\n\n }\n\n @Override\n public void close() throws SecurityException {}\n @Override\n public void flush(){}\n };\n</code></pre>\n"
},
{
"answer_id": 4738963,
"author": "Frank Vlach",
"author_id": 581895,
"author_profile": "https://Stackoverflow.com/users/581895",
"pm_score": 4,
"selected": false,
"text": "<p>I've arrived at</p>\n\n<pre><code> SimpleFormatter fmt = new SimpleFormatter();\n StreamHandler sh = new StreamHandler(System.out, fmt);\n logger.addHandler(sh);\n</code></pre>\n"
},
{
"answer_id": 5357588,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 4,
"selected": false,
"text": "<p>Hmm I just got bit in the foot a few times, trying to accomplish this feat. Before googling my way here I managed to conjure the following hack. Ugly, but it seems to get the job done.</p>\n\n<pre><code>public class StdoutConsoleHandler extends ConsoleHandler {\n protected void setOutputStream(OutputStream out) throws SecurityException {\n super.setOutputStream(System.out); // kitten killed here :-(\n }\n}\n</code></pre>\n\n<p>Watch out: Calling setOutputStream() from the constructor is tempting, but it does (as Jon Skeet already pointed out) close System.err. Mad skills!</p>\n"
},
{
"answer_id": 10213202,
"author": "Kai",
"author_id": 1341872,
"author_profile": "https://Stackoverflow.com/users/1341872",
"pm_score": 2,
"selected": false,
"text": "<p>If there is still someone out there looking for a solution to this problem.\nHere's what I came up with finally: I just subclassed StreamHandler and added an additional parameter\nMaxLevel, which is checked at the beginning of publish(). If the level of the logging event is larger than MaxLevel, publish won't be executed any further.\nHere are the details:</p>\n\n<p><strong>MaxlevelStreamHandler.java</strong>\nMain Class below.</p>\n\n<pre><code>package helper;\n\n/**\n * The only difference to the standard StreamHandler is \n * that a MAXLEVEL can be defined (which then is not published)\n * \n * @author Kai Goergen\n */\n\nimport java.io.PrintStream;\nimport java.util.logging.Formatter;\nimport java.util.logging.Level;\nimport java.util.logging.LogRecord;\nimport java.util.logging.StreamHandler;\n\npublic class MaxlevelStreamHandler extends StreamHandler {\n\n private Level maxlevel = Level.SEVERE; // by default, put out everything\n\n /**\n * The only method we really change to check whether the message\n * is smaller than maxlevel.\n * We also flush here to make sure that the message is shown immediately.\n */\n @Override\n public synchronized void publish(LogRecord record) {\n if (record.getLevel().intValue() > this.maxlevel.intValue()) {\n // do nothing if the level is above maxlevel\n } else {\n // if we arrived here, do what we always do\n super.publish(record);\n super.flush();\n }\n }\n\n /**\n * getter for maxlevel\n * @return\n */\n public Level getMaxlevel() {\n return maxlevel;\n }\n\n /**\n * Setter for maxlevel. \n * If a logging event is larger than this level, it won't be displayed\n * @param maxlevel\n */\n public void setMaxlevel(Level maxlevel) {\n this.maxlevel = maxlevel;\n }\n\n /** Constructor forwarding */\n public MaxlevelStreamHandler(PrintStream out, Formatter formatter) {\n super(out, formatter);\n }\n\n /** Constructor forwarding */\n public MaxlevelStreamHandler() {\n super();\n }\n}\n</code></pre>\n\n<p><strong>Main Class</strong></p>\n\n<p>To now show some events in stdout and some in stderr, simply setup two StreamLoggers, one for critical events and one for all others, and disable the standard console logger:</p>\n\n<pre><code>// setup all logs that are smaller than WARNINGS to stdout\nMaxlevelStreamHandler outSh = new MaxlevelStreamHandler(System.out, formatter);\noutSh.setLevel(Level.ALL);\noutSh.setMaxlevel(Level.INFO);\nlogger.addHandler(outSh);\n\n// setup all warnings to stdout & warnings and higher to stderr\nStreamHandler errSh = new StreamHandler(System.err, formatter);\nerrSh.setLevel(Level.WARNING);\nlogger.addHandler(errSh);\n\n// remove default console logger\nlogger.setUseParentHandlers(false);\n\nlogger.info(\"info\");\nlogger.warning(\"warning\");\nlogger.severe(\"severe\");\n</code></pre>\n\n<p>Hope this helps!</p>\n\n<p>Update: I added super.flush() right after super.publish() to make sure that the message is shown immediately. Before, I had problems that the log-messages were always shown at the end. It's now part of the code above.</p>\n"
},
{
"answer_id": 23717493,
"author": "ocarlsen",
"author_id": 1007631,
"author_profile": "https://Stackoverflow.com/users/1007631",
"pm_score": 3,
"selected": false,
"text": "<p>I had a similar problem. I wanted to log INFO and below to <code>System.out</code>, and WARNING and above to <code>System.err</code>. Here is the solution I implemented:</p>\n\n<pre><code>public class DualConsoleHandler extends StreamHandler {\n\n private final ConsoleHandler stderrHandler = new ConsoleHandler();\n\n public DualConsoleHandler() {\n super(System.out, new SimpleFormatter());\n }\n\n @Override\n public void publish(LogRecord record) {\n if (record.getLevel().intValue() <= Level.INFO.intValue()) {\n super.publish(record);\n super.flush();\n } else {\n stderrHandler.publish(record);\n stderrHandler.flush();\n }\n }\n}\n</code></pre>\n\n<p>Of course, you could make it more flexible by factoring out the hard-coded reference to <code>Level.INFO</code>, for example. But this worked well for me to get some basic dual-stream logging. (BTW, the tips about not subclassing ConsoleHandler to avoid closing the <code>System.err</code> were very useful.)</p>\n"
},
{
"answer_id": 35919737,
"author": "jmehrens",
"author_id": 2428802,
"author_profile": "https://Stackoverflow.com/users/2428802",
"pm_score": 2,
"selected": false,
"text": "<p>The ConsoleHandler will grab a snapshot of <code>System.err</code> during construction. One option would be to swap the global error stream with the global out stream and then create the ConsoleHandler.</p>\n\n<pre><code>ConsoleHandler h = null;\nfinal PrintStream err = System.err;\nSystem.setErr(System.out);\ntry {\n h = new ConsoleHandler(); //Snapshot of System.err\n} finally {\n System.setErr(err);\n}\n</code></pre>\n\n<p>This assumes that the code has permission to modify error stream and that no other running code is accessing the error stream. In short, this is an option but there are safer alternatives.</p>\n"
},
{
"answer_id": 42458416,
"author": "Virendra Singh",
"author_id": 7622140,
"author_profile": "https://Stackoverflow.com/users/7622140",
"pm_score": 2,
"selected": false,
"text": "<p>When we create a new ConsoleHandler object, default output stream is \"system.err\". Sadly Java doesn't provide any public method for ConsoleHandler class to set output stream. So it can be set only at the time of object creation. As ConsoleHandler class extends StreamHandler, which has a protected method \"setOutputStream\" to set output stream explicitly. To set output Stream for ConsoleHandler just override this method at the time of new call for object creation. </p>\n\n<pre><code>ConsoleHandler consoleHandler = new ConsoleHandler (){\n @Override\n protected synchronized void setOutputStream(OutputStream out) throws SecurityException {\n super.setOutputStream(System.out);\n }\n };\n</code></pre>\n"
},
{
"answer_id": 62165188,
"author": "Hari Krishna",
"author_id": 3302424,
"author_profile": "https://Stackoverflow.com/users/3302424",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Step 1:</strong> Set parent handlers to false.</p>\n\n<pre><code>log.setUseParentHandlers(false);\n</code></pre>\n\n<p><strong>Step 2:</strong> Add a handler that writes to System.out</p>\n\n<pre><code>log.addHandler(new StreamHandler(System.out, new SimpleFormatter()));\n</code></pre>\n\n<p>Thats it..</p>\n\n<pre><code>import java.io.IOException;\nimport java.util.logging.Logger;\nimport java.util.logging.SimpleFormatter;\nimport java.util.logging.StreamHandler;\n\npublic class App {\n\n static final Logger log = Logger.getLogger(\"com.sample.app.App\");\n\n static void processData() {\n log.info(\"Started Processing Data\");\n log.info(\"Finished processing data\");\n }\n\n public static void main(String args[]) throws IOException {\n log.setUseParentHandlers(false);\n\n log.addHandler(new StreamHandler(System.out, new SimpleFormatter()));\n\n processData();\n }\n}\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23120/"
] |
I'm using the standard `ConsoleHandler` from `java.util.logging` and by default the console output is directed to the error stream (i.e. `System.err`).
How do I change the console output to the output stream (i.e. `System.out`)?
|
I've arrived at
```
SimpleFormatter fmt = new SimpleFormatter();
StreamHandler sh = new StreamHandler(System.out, fmt);
logger.addHandler(sh);
```
|
194,168 |
<p>I asked before about pixel-pushing, and have now managed to get far enough to get noise to show up on the screen. Here's how I init:</p>
<pre><code>CGDataProviderRef provider;
bitmap = malloc(320*480*4);
provider = CGDataProviderCreateWithData(NULL, bitmap, 320*480*4, NULL);
CGColorSpaceRef colorSpaceRef;
colorSpaceRef = CGColorSpaceCreateDeviceRGB();
ir = CGImageCreate(
320,
480,
8,
32,
4 * 320,
colorSpaceRef,
kCGImageAlphaNoneSkipLast,
provider,
NULL,
NO,
kCGRenderingIntentDefault
);
</code></pre>
<p>Here's how I render each frame:</p>
<pre><code>for (int i=0; i<320*480*4; i++) {
bitmap[i] = rand()%256;
}
CGRect rect = CGRectMake(0, 0, 320, 480);
CGContextDrawImage(context, rect, ir);
</code></pre>
<p>Problem is this is awfully awfully slow, around 5fps. I think my path to publish the buffer must be wrong. Is it even possible to do full-screen pixel-based graphics that I could update at 30fps, without using the 3D chip?</p>
|
[
{
"answer_id": 194216,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 1,
"selected": false,
"text": "<p>I suspect doing 614400 (<code>320*480*4</code>) memory writes, random number generation and making a new object each frame is slowing you down. </p>\n\n<p>Have you tried just writing a static bitmap to screen and seeing how fast that is? Have you perhaps tried profiling the code? Do you also need to make a new CGRect each time? </p>\n\n<p>If you just want to give the effect of randomness, there is probably no need to regenerate the entire bitmap each time.</p>\n"
},
{
"answer_id": 194386,
"author": "Chris Lundie",
"author_id": 20685,
"author_profile": "https://Stackoverflow.com/users/20685",
"pm_score": 1,
"selected": false,
"text": "<p>To my knowledge, OpenGL is supposed to be the fastest way to do graphics on the iPhone. This includes 2D and 3D. A UIView is backed by a core animation layer, which ends up drawing with OpenGL anyway. So why not skip the middle-man.</p>\n"
},
{
"answer_id": 195013,
"author": "Jason Harris",
"author_id": 1345109,
"author_profile": "https://Stackoverflow.com/users/1345109",
"pm_score": 3,
"selected": true,
"text": "<p>The slowness is almost certainly in the noise generation. If you run this in Instruments you'll probably see that a ton of time is spent sitting in your loop.</p>\n\n<p>Another smaller issue is your colorspace. If you use the screen's colorspace, you'll avoid a colorspace conversion which is potentially expensive. </p>\n\n<p>If you can use CoreGraphics routines for your drawing, you'd be better served by creating a CGLayer for the drawing context instead of creating a new object each time. </p>\n\n<p>The bytesPerRow component is also important for performance. It should be a factor of 32 IIRC. There's some code available <a href=\"http://www.geekspiff.com/content/view/61/\" rel=\"nofollow noreferrer\" title=\"here\">link text</a> that shows how to compute it.</p>\n\n<p>And yeah, for raw performance, OpenGL.</p>\n"
},
{
"answer_id": 1948932,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 1,
"selected": false,
"text": "<p>You can avoid the trip through <code>CGContextDrawImage</code> by assigning your <code>CGImageRef</code> to <code>-[CALayer setContents:]</code>, just be sure not to free bitmap while you're still using it.</p>\n\n<pre><code>[[view layer] setContents:(id)ir];\n</code></pre>\n\n<p><sup>Yes, I know this is old, I stumbled upon it from Google</sup></p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8005/"
] |
I asked before about pixel-pushing, and have now managed to get far enough to get noise to show up on the screen. Here's how I init:
```
CGDataProviderRef provider;
bitmap = malloc(320*480*4);
provider = CGDataProviderCreateWithData(NULL, bitmap, 320*480*4, NULL);
CGColorSpaceRef colorSpaceRef;
colorSpaceRef = CGColorSpaceCreateDeviceRGB();
ir = CGImageCreate(
320,
480,
8,
32,
4 * 320,
colorSpaceRef,
kCGImageAlphaNoneSkipLast,
provider,
NULL,
NO,
kCGRenderingIntentDefault
);
```
Here's how I render each frame:
```
for (int i=0; i<320*480*4; i++) {
bitmap[i] = rand()%256;
}
CGRect rect = CGRectMake(0, 0, 320, 480);
CGContextDrawImage(context, rect, ir);
```
Problem is this is awfully awfully slow, around 5fps. I think my path to publish the buffer must be wrong. Is it even possible to do full-screen pixel-based graphics that I could update at 30fps, without using the 3D chip?
|
The slowness is almost certainly in the noise generation. If you run this in Instruments you'll probably see that a ton of time is spent sitting in your loop.
Another smaller issue is your colorspace. If you use the screen's colorspace, you'll avoid a colorspace conversion which is potentially expensive.
If you can use CoreGraphics routines for your drawing, you'd be better served by creating a CGLayer for the drawing context instead of creating a new object each time.
The bytesPerRow component is also important for performance. It should be a factor of 32 IIRC. There's some code available [link text](http://www.geekspiff.com/content/view/61/ "here") that shows how to compute it.
And yeah, for raw performance, OpenGL.
|
194,194 |
<p>I have a large collection of data in an excel file (and csv files). The data needs to be placed into a database (mysql). However, before it goes into the database it needs to be processed..for example if columns 1 is less than column 3 add 4 to column 2. There are quite a few rules that must be followed before the information is persisted.</p>
<p>What would be a good design to follow to accomplish this task? (using java)</p>
<p><strong>Additional notes</strong></p>
<p>The process needs to be automated. In the sense that I don't have to manually go in and alter the data. We're talking about thousands of lines of data with 15 columns of information per line.</p>
<p>Currently, I have a sort of chain of responsibility design set up. One class(Java) for each rule. When one rule is done, it calls the following rule.</p>
<p><strong>More Info</strong></p>
<p>Typically there are about 5000 rows per data sheet. Speed isn't a huge concern because
this large input doesn't happen often.</p>
<p>I've considered drools, however I wasn't sure the task was complicated enough for drols. </p>
<p>Example rules:</p>
<ol>
<li><p>All currency (data in specific columns) must not contain currency symbols.</p></li>
<li><p>Category names must be uniform (e.g. book case = bookcase)</p></li>
<li><p>Entry dates can not be future dates</p></li>
<li><p>Text input can only contain [A-Z 0-9 \s]</p></li>
</ol>
<p>etc..<br>
Additionally if any column of information is invalid it needs to be reported when
processing is complete
(or maybe stop processing).</p>
<p>My current solution works. However I think there is room for improvement so I'm looking
for ideals as to how it can be improved and or how other people have handled similar
situations.</p>
<p>I've considered (very briefly) using drools but I wasn't sure the work was complicated enough to take advantage of drools.</p>
|
[
{
"answer_id": 194205,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 0,
"selected": false,
"text": "<p>A class for each rule? <em>Really?</em> Perhaps I'm not understanding the quantity or complexity of these rules, but I would (semi-pseudo-code):</p>\n\n<pre><code>public class ALine {\n private int col1;\n private int col2;\n private int coln;\n // ...\n\n public ALine(string line) {\n // read row into private variables\n // ...\n\n this.Process();\n this.Insert();\n }\n\n public void Process() {\n // do all your rules here working with the local variables\n }\n\n public void Insert() {\n // write to DB\n }\n}\n\nforeach line in csv\n new ALine(line);\n</code></pre>\n"
},
{
"answer_id": 194210,
"author": "stimms",
"author_id": 361,
"author_profile": "https://Stackoverflow.com/users/361",
"pm_score": 0,
"selected": false,
"text": "<p>Your methodology of using classes for each rule does sound a bit heavy weight but it has the advantage of being easy to modify and expand should new rules come along. </p>\n\n<p>As for loading the data bulk loading is the way to go. I have read some informaiton which suggests it may be as much as 3 orders of magnitude faster than loading using insert statements. You can find some information on it <a href=\"http://www.classes.cs.uchicago.edu/archive/2005/fall/23500-1/mysql-load.html\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 194211,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 0,
"selected": false,
"text": "<p>Bulk load the data into a temp table, then use sql to apply your rules.\nuse the temp table, as a basis for the insert into real table.\ndrop the temp table.</p>\n"
},
{
"answer_id": 194231,
"author": "extraneon",
"author_id": 24582,
"author_profile": "https://Stackoverflow.com/users/24582",
"pm_score": 1,
"selected": false,
"text": "<p>I think your method is OK. Especially if you use the same interface on every processor.</p>\n\n<p>You could also look to somethink called Drules, currently Jboss-rules. I used that some time ago for a rule-heavy part of my app and what I liked about it is that the business logic can be expressed in for instance a spreadsheet or DSL which then get's compiled to java (run-time and I think there's also a compile-time option). It makes rules a bit more succint and thus readable. It's also very easy to learn (2 days or so).</p>\n\n<p>Here's a link to the opensource <a href=\"https://www.jboss.org/community/docs/DOC-10741\" rel=\"nofollow noreferrer\">Jboss-rules</a>. At jboss.com you can undoubtedly purchase an offically maintained version if that's more to your companies taste.</p>\n"
},
{
"answer_id": 194375,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 0,
"selected": false,
"text": "<p>you can see that all the different answers are coming from their own experience and perspective.</p>\n\n<p>Since we don't know much about the complexity and number of rows in your system, we tend to give advice based on what we have done earlier.</p>\n\n<p>If you want to narrow down to a 1/2 solutions for your implementation, try giving more details.</p>\n\n<p>Good luck</p>\n"
},
{
"answer_id": 194679,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": true,
"text": "<p>If I didn't care to do this in 1 step (as Oli mentions), I'd probably use a <a href=\"http://www.eaipatterns.com/PipesAndFilters.html\" rel=\"nofollow noreferrer\">pipe and filters</a> design. Since your rules are relatively simple, I'd probably do a couple delegate based classes. For instance (C# code, but Java should be pretty similar...perhaps someone could translate?):</p>\n\n<pre><code>interface IFilter {\n public IEnumerable<string> Filter(IEnumerable<string> file) {\n }\n}\n\nclass PredicateFilter : IFilter {\n public PredicateFilter(Predicate<string> predicate) { }\n\n public IEnumerable<string> Filter(IEnumerable<string> file) {\n foreach (string s in file) {\n if (this.Predicate(s)) {\n yield return s;\n }\n }\n }\n}\n\nclass ActionFilter : IFilter {\n public ActionFilter(Action<string> action) { }\n\n public IEnumerable<string> Filter(IEnumerable<string> file) {\n foreach (string s in file) {\n this.Action(s);\n yield return s;\n }\n }\n}\n\nclass ReplaceFilter : IFilter {\n public ReplaceFilter(Func<string, string> replace) { }\n\n public IEnumerable<string> Filter(IEnumerable<string> file) {\n foreach (string s in file) {\n yield return this.Replace(s);\n }\n }\n}\n</code></pre>\n\n<p>From there, you could either use the delegate filters directly, or subclass them for the specifics. Then, register them with a Pipeline that will pass them through each filter.</p>\n"
},
{
"answer_id": 194706,
"author": "Seun Osewa",
"author_id": 6475,
"author_profile": "https://Stackoverflow.com/users/6475",
"pm_score": 1,
"selected": false,
"text": "<p>Just create a function to enforce each rule, and call every applicable function for each value. I don't see how this requires any exotic architecture.</p>\n"
},
{
"answer_id": 198113,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It may not be what you want to hear, it isn't the \"fun way\" by any means, but there is a much easier way to do this. </p>\n\n<p>So long as your data is evaluated line by line... you can setup another worksheet in your excel file and use spreadsheet style functions to do the necessary transforms, referencing the data from the raw data sheet. For more complex functions you can use the vba embedded in excel to write out custom operations.</p>\n\n<p>I've used this approach many times and it works really well; its just not very sexy.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17337/"
] |
I have a large collection of data in an excel file (and csv files). The data needs to be placed into a database (mysql). However, before it goes into the database it needs to be processed..for example if columns 1 is less than column 3 add 4 to column 2. There are quite a few rules that must be followed before the information is persisted.
What would be a good design to follow to accomplish this task? (using java)
**Additional notes**
The process needs to be automated. In the sense that I don't have to manually go in and alter the data. We're talking about thousands of lines of data with 15 columns of information per line.
Currently, I have a sort of chain of responsibility design set up. One class(Java) for each rule. When one rule is done, it calls the following rule.
**More Info**
Typically there are about 5000 rows per data sheet. Speed isn't a huge concern because
this large input doesn't happen often.
I've considered drools, however I wasn't sure the task was complicated enough for drols.
Example rules:
1. All currency (data in specific columns) must not contain currency symbols.
2. Category names must be uniform (e.g. book case = bookcase)
3. Entry dates can not be future dates
4. Text input can only contain [A-Z 0-9 \s]
etc..
Additionally if any column of information is invalid it needs to be reported when
processing is complete
(or maybe stop processing).
My current solution works. However I think there is room for improvement so I'm looking
for ideals as to how it can be improved and or how other people have handled similar
situations.
I've considered (very briefly) using drools but I wasn't sure the work was complicated enough to take advantage of drools.
|
If I didn't care to do this in 1 step (as Oli mentions), I'd probably use a [pipe and filters](http://www.eaipatterns.com/PipesAndFilters.html) design. Since your rules are relatively simple, I'd probably do a couple delegate based classes. For instance (C# code, but Java should be pretty similar...perhaps someone could translate?):
```
interface IFilter {
public IEnumerable<string> Filter(IEnumerable<string> file) {
}
}
class PredicateFilter : IFilter {
public PredicateFilter(Predicate<string> predicate) { }
public IEnumerable<string> Filter(IEnumerable<string> file) {
foreach (string s in file) {
if (this.Predicate(s)) {
yield return s;
}
}
}
}
class ActionFilter : IFilter {
public ActionFilter(Action<string> action) { }
public IEnumerable<string> Filter(IEnumerable<string> file) {
foreach (string s in file) {
this.Action(s);
yield return s;
}
}
}
class ReplaceFilter : IFilter {
public ReplaceFilter(Func<string, string> replace) { }
public IEnumerable<string> Filter(IEnumerable<string> file) {
foreach (string s in file) {
yield return this.Replace(s);
}
}
}
```
From there, you could either use the delegate filters directly, or subclass them for the specifics. Then, register them with a Pipeline that will pass them through each filter.
|
194,208 |
<p>I'm using the following code within the JCProperty class to retrieve data from a DAL: </p>
<pre><code>Dim x As JCProperty
x = JCPropertyDB.GetProperty(PropertyID)
If Not x Is Nothing Then
Me.PropertyID = x.PropertyID
Me.AddressLine1 = x.AddressLine1
Me.AddressLine2 = x.AddressLine2
Me.AddressLine3 = x.AddressLine3
Me.AddressCity = x.AddressCity
Me.AddressCounty = x.AddressCounty
Me.AddressPostcode = x.AddressPostcode
Me.TelNo = x.TelNo
Me.UpdatedOn = x.UpdatedOn
Me.CreatedOn = x.CreatedOn
Me.Description = x.Description
Me.GUID = x.GUID
End If
</code></pre>
<p>This works fine but requires that the DAL object (JCPropertyDB) is aware of the business object (JCProperty) and I effectively create and populate the same object twice (once in the DAL to return to the BL and then again within the BL object to populate itself). </p>
<p>I'm missing something here, I know there must be a better way! </p>
<p>Effectively I need to assign 'Me = x' which is not allowed. Can someone put me straight?</p>
|
[
{
"answer_id": 194250,
"author": "Erlend",
"author_id": 5746,
"author_profile": "https://Stackoverflow.com/users/5746",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure if this will answer your question, but the important point is that the domain model is independent of display and independent of storage. This is often denoted as separation of concerns. The idea is to get loose couplings and create a simple system where objects do not have several completely different responsibilities. <br>\nSo what I would do, is to allow the DAL to create business objects directly, but make sure I don't contaminate my business objects with anything related to the DAL. Similarly I don't want to contaminate them with UI-specific things like HTML.\nIn my opinion it's ok that both the business layer, DAL and UI-layer all have dependencies to the domain model, however it's not ok to have dependencies from the domain model and into these other components.<br>\nTo loosen the couplings, using something Spring or any other Dependency injection container together with interfaces and wiring can help you.<br>\nBy recreating the same object in every layer you are violating the DRY principle (Don't repeat yourself) and you are introducing boiler plate code and increasing the chance of introducing an error somewhere.</p>\n"
},
{
"answer_id": 194270,
"author": "Ron Savage",
"author_id": 12476,
"author_profile": "https://Stackoverflow.com/users/12476",
"pm_score": 2,
"selected": true,
"text": "<p>Personally, I'm lazy. I usually do something like:</p>\n\n<pre><code>class JCProperty : inherits JCPropertyDB\n {\n\n New()\n {\n MyBase.New()\n\n GetProperty(PropertyID)\n\n }\n }\n</code></pre>\n\n<p>Then you're basically done, until you have some additional functionality in the JCProperty class that needs to happen \"on top\" of the functionality already existing in JCPropertyDB. Then you override the JCPropertyDB methods to call the base method first then add your new functionality.</p>\n\n<p>Ron</p>\n"
},
{
"answer_id": 200351,
"author": "Neil Barnwell",
"author_id": 26414,
"author_profile": "https://Stackoverflow.com/users/26414",
"pm_score": 2,
"selected": false,
"text": "<p>You are on the right lines however missing one point slightly.</p>\n\n<p>Typically, your Data Access Layer (DAL) would return <a href=\"http://martinfowler.com/eaaCatalog/dataTransferObject.html\" rel=\"nofollow noreferrer\">Data Transfer Objects</a> (DTO) from your database. These are Plain Old CLR Objects (POCO) which contain no business logic, simply properties more or less mapping to the database tables.</p>\n\n<p>You would then have code which creates a <a href=\"http://martinfowler.com/eaaCatalog/domainModel.html\" rel=\"nofollow noreferrer\">Domain Model</a> from these DTOs, referred to as a <a href=\"http://martinfowler.com/eaaCatalog/dataMapper.html\" rel=\"nofollow noreferrer\">Data Mapper</a>. The classes in the Domain Model might have similar names (i.e. CustomerDTO -> Customer) but in addition to the data, they will contain validation rules and possibly other business logic.</p>\n\n<p>It is this Domain Model that you then use in your business layer, not the actual DTOs. This means that if you change the DTOs returned from the DAL (i.e. by implementing a new ORM tool), you only have to modify your Data Mapper providing the data model stays the same.</p>\n\n<p>I recommend looking at <a href=\"http://martinfowler.com/books.html#eaa\" rel=\"nofollow noreferrer\">Martin Fowler's Patterns of Enterprise Application Architecture</a> for data access patterns.</p>\n"
},
{
"answer_id": 1494858,
"author": "Icemanind",
"author_id": 98094,
"author_profile": "https://Stackoverflow.com/users/98094",
"pm_score": 0,
"selected": false,
"text": "<p>Check out: <a href=\"http://www.icemanind.com/layergen.aspx\" rel=\"nofollow noreferrer\">http://www.icemanind.com/layergen.aspx</a></p>\n"
},
{
"answer_id": 1543355,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I've been taking in BOs and sending back BOs from in the DAL via the bridge pattern and provider model. I can't see the point of DTOs unless I was fearful of heavy serialization (say a web service or JSON). My approach has been to abstract the Data-Layer and Business layer via an interface and provide an anonymous data layer fed into the business object. This means that I can plug in any data-layer, implement an interface that has universal Load and Save methods and which is then accessible via my domain layer. There is no DAL code in the BL - simply a call to a provided and abstracted data-layer. My call to the data layer is managed by a provider pattern (no direct reference) and I simply do:</p>\n\n<pre><code>public class Person : IBusinessObject<Person>\n{\n protected IDataLayer<T> dataLayer;\n\n Person Load() { this.dataLayer.Load(this); }\n\n}\n</code></pre>\n\n<p>in the data-layer I have...</p>\n\n<pre><code>public class PersonMapper : IDataLayer<Person> \n{\n Person Load(Person person) {\n ...get DB stuff...map to person...decorate object...\n return person;\n }\n}\n</code></pre>\n\n<p>I still don't know if this is good but it works quite well for me. I've managed to get lazy load in as well for nested objects using reflection.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20048/"
] |
I'm using the following code within the JCProperty class to retrieve data from a DAL:
```
Dim x As JCProperty
x = JCPropertyDB.GetProperty(PropertyID)
If Not x Is Nothing Then
Me.PropertyID = x.PropertyID
Me.AddressLine1 = x.AddressLine1
Me.AddressLine2 = x.AddressLine2
Me.AddressLine3 = x.AddressLine3
Me.AddressCity = x.AddressCity
Me.AddressCounty = x.AddressCounty
Me.AddressPostcode = x.AddressPostcode
Me.TelNo = x.TelNo
Me.UpdatedOn = x.UpdatedOn
Me.CreatedOn = x.CreatedOn
Me.Description = x.Description
Me.GUID = x.GUID
End If
```
This works fine but requires that the DAL object (JCPropertyDB) is aware of the business object (JCProperty) and I effectively create and populate the same object twice (once in the DAL to return to the BL and then again within the BL object to populate itself).
I'm missing something here, I know there must be a better way!
Effectively I need to assign 'Me = x' which is not allowed. Can someone put me straight?
|
Personally, I'm lazy. I usually do something like:
```
class JCProperty : inherits JCPropertyDB
{
New()
{
MyBase.New()
GetProperty(PropertyID)
}
}
```
Then you're basically done, until you have some additional functionality in the JCProperty class that needs to happen "on top" of the functionality already existing in JCPropertyDB. Then you override the JCPropertyDB methods to call the base method first then add your new functionality.
Ron
|
194,241 |
<p>In Visual Studio if I define a class to implement an interface e.g.</p>
<pre><code>class MyObject : ISerializable {}
</code></pre>
<p>I am able to right click on ISerializable, select "<em>Implement Interface</em>" from the context menu and see the appropriate methods appear in my class definition.</p>
<pre><code>class MyObject : ISerializable {
#region ISerializable Members
public void GetObjectData(SerializationInfo info,
StreamingContext context)
{
throw new NotImplementedException();
}
#endregion
}
</code></pre>
<p>Is there anything anything like this functionality available in Xcode on the Mac? I would like to be able to automatically implement Protocols in this way. Maybe with the optional methods generated but commented out.</p>
|
[
{
"answer_id": 194335,
"author": "David Grant",
"author_id": 26829,
"author_profile": "https://Stackoverflow.com/users/26829",
"pm_score": 4,
"selected": true,
"text": "<p>I have not seen that feature in Xcode.\nBut it seems like someone could write a new user script called \"Place Implementor Defs on Clipboard\" that sits inside of Scripts > Code.</p>\n\n<p>You did not find this useful. </p>\n"
},
{
"answer_id": 195028,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 3,
"selected": false,
"text": "<p>There is not currently such a refactoring in Xcode.</p>\n\n<p>If you'd like it, please file an <a href=\"http://bugreport.apple.com/\" rel=\"noreferrer\" title=\"Apple's Bug Reporter\">enhancement request</a>.</p>\n"
},
{
"answer_id": 2144445,
"author": "Casebash",
"author_id": 165495,
"author_profile": "https://Stackoverflow.com/users/165495",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://forums.macrumors.com/showthread.php?p=6180803#post6180803\" rel=\"nofollow noreferrer\">Macrumors</a> had a discussion on this too. There is a link to some apple scripts. I haven't actually tried these.</p>\n"
},
{
"answer_id": 3952028,
"author": "bithavoc",
"author_id": 146032,
"author_profile": "https://Stackoverflow.com/users/146032",
"pm_score": 1,
"selected": false,
"text": "<p>Xcode can help you per protocol method, lets say you have a protocol like this:</p>\n\n<pre><code>@protocol PosterousWebsitesDelegate <NSObject>\n- (void)PosterousWebsitesLoadSuccess:(PosterousWebsites*)websites;\n@end\n</code></pre>\n\n<p>in the @implementation section of your .m file you can start writing the name of the method and pressing ESC key to autocomplete the signature of the method/selector:</p>\n\n<pre><code>-(void)Poste (...press ESC...)\n</code></pre>\n\n<p>Xcode will autocomplete a full signature of the @protocol method, pres TAB to confirm the code.</p>\n\n<p>If you are really committing to learn OSX/iOS Development, I would recommend you to read \"XCode 3 Unleashed\", a book that really helped me to know Xcode as deep as I know VS :)</p>\n"
},
{
"answer_id": 5359534,
"author": "Clay",
"author_id": 16429,
"author_profile": "https://Stackoverflow.com/users/16429",
"pm_score": 5,
"selected": false,
"text": "<p>XCode currently does not support that kind of automation. But: an easy way to get your code bootstrapped with a protocol is to option-click the protocol name in your class declaration</p>\n\n<pre><code>@interface FooAppDelegate : NSObject <NSApplicationDelegate, \n NSTableViewDelegate> {\n</code></pre>\n\n<p>to quickly open the .h file defining the protocol. From there, copy and paste the methods you're interested in. Those headers tend to be well-commented, which helps in determining which methods you can safely ignore.</p>\n"
},
{
"answer_id": 11277545,
"author": "Randy Eppinger",
"author_id": 215789,
"author_profile": "https://Stackoverflow.com/users/215789",
"pm_score": 2,
"selected": false,
"text": "<p>I know this thread s a bit old, but I wondered the same thing and found this question. </p>\n\n<p>In my case, I'm defining a property in the interface (.h) and I want to synthesize it in the implementation (.m). I also need to implement methods defined in the interface. Yes, Xcode helps as others have mentioned, but modern IDEs offer these productivity enhancements for things we do frequently. It appears that this is still not a feature in Xcode 4.3.3. However, the feature is available in <a href=\"http://www.jetbrains.com/objc/index.html\" rel=\"nofollow\">JetBrains' AppCode</a>. I'm only dabbling with the trial, but it appears to only be possible one property or method at a time, not the whole interface like Visual Studio.</p>\n"
},
{
"answer_id": 37683796,
"author": "Harshit Gupta",
"author_id": 1120688,
"author_profile": "https://Stackoverflow.com/users/1120688",
"pm_score": 1,
"selected": false,
"text": "<p>check this plugin</p>\n\n<p><a href=\"https://github.com/music4kid/FastStub-Xcode\" rel=\"nofollow\">https://github.com/music4kid/FastStub-Xcode</a></p>\n\n<p>it does the thing that you are asking for and more.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1403/"
] |
In Visual Studio if I define a class to implement an interface e.g.
```
class MyObject : ISerializable {}
```
I am able to right click on ISerializable, select "*Implement Interface*" from the context menu and see the appropriate methods appear in my class definition.
```
class MyObject : ISerializable {
#region ISerializable Members
public void GetObjectData(SerializationInfo info,
StreamingContext context)
{
throw new NotImplementedException();
}
#endregion
}
```
Is there anything anything like this functionality available in Xcode on the Mac? I would like to be able to automatically implement Protocols in this way. Maybe with the optional methods generated but commented out.
|
I have not seen that feature in Xcode.
But it seems like someone could write a new user script called "Place Implementor Defs on Clipboard" that sits inside of Scripts > Code.
You did not find this useful.
|
194,247 |
<p>I have a 2 dimensional array, like so:</p>
<pre><code>char[,] str = new char[2,50];
</code></pre>
<p>Now, after I've stored contents in both str[0] and str[1], how do I store it in a </p>
<pre><code>string[] s = new string[2];
</code></pre>
<p>?</p>
<p>I tried </p>
<pre><code>s[0] = str[0].ToString();
</code></pre>
<p>but that seems to be an error: VC# expects 'two' indices within the braces, which means I can convert only a character from the array. Is there a way to convert the entire str[0] to a string? Or is changing it to a jagged array the only solution?</p>
|
[
{
"answer_id": 194252,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming the dimensions are fixed as 2x50:</p>\n\n<pre><code>char[,] str = new char[2,50];\n\n// populate str somehow\n\n// chose which of the strings we want (the 'row' index)\nint strIndex = 0;\n// create a temporary array (faster and less wasteful than using a StringBuilder)\nchar[] chars = new chars[50];\nfor (int i = 0; i < 50; i++)\n chars[i] = str[strIndex, i];\nstring s = new string[chars];\n</code></pre>\n\n<p>This would be easier and more performant if you used a jagged array:</p>\n\n<pre><code>char[][] str = new char[2][];\n</code></pre>\n\n<p>Then you could write:</p>\n\n<pre><code>string s = new string(characters[0]);\n</code></pre>\n"
},
{
"answer_id": 194259,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 3,
"selected": true,
"text": "<p>A jagged array is almost always the best solution for a variety of reasons, and this is one good example. There is so much more flexibility available with an array of arrays than with a multi-dimensional array. In this case, once you have the values in an array of chars, then a constructor on the string class can be used to create a string from it.</p>\n\n<p>Also, the jagged array would be composed of \"vectors\" (i.e., a single-dimensional arrays with a zero-lower-bound index), which are much more preferment in .Net because they are given special treatment by the CLR.</p>\n\n<p>So without knowing what the rest of your program is doing, that would be my recommendation.</p>\n\n<p>If you do attempt to construct a string manually by looping through the array indexes, instead of using a jagged array, then I recommend using the StringBuilder class to do it.</p>\n\n<p>I just banged this out, but it should be something like this:</p>\n\n<pre><code>// For the multi-dimentional array\nStringBuilder sb = new StringBuilder();\nfor (int stringIndex = 0; stringIndex < s.Length; stringIndex++)\n{\n sb.Clear();\n for (int charIndex = 0; charIndex < str.UpperBound(1); charIndex++)\n sb.Append(str[stringIndex,charIndex]);\n s[stringIndex] = sb.ToString();\n}\n\n// For the jagged array\nfor (int index = 0; index < s.Length; index++)\n s[index] = new string(str[index]);\n</code></pre>\n"
},
{
"answer_id": 194280,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 1,
"selected": false,
"text": "<p>I would agree with using a jagged array. You can use this helper method to initialize a jagged array:</p>\n\n<pre><code>static T[][] InitJaggedArray<T>(int dimension1, int dimension2)\n{\n T[][] array = new T[dimension1][];\n for (int i = 0; i < dimension1; i += 1)\n {\n array[i] = new T[dimension2];\n }\n return array;\n}\n</code></pre>\n\n<p>So</p>\n\n<pre><code>char[,] str = new char[2,50];\n</code></pre>\n\n<p>would become</p>\n\n<pre><code>char[][] str = ArrayHelper.InitJaggedArray<char>(2, 50);\n</code></pre>\n\n<p>You would then access elements in it like so</p>\n\n<pre><code>str[0, 10] = 'a';\n</code></pre>\n\n<p>And to make it a string you would do</p>\n\n<pre><code>string s = new string(str[0]);\n</code></pre>\n"
},
{
"answer_id": 11493521,
"author": "John Rayner",
"author_id": 46473,
"author_profile": "https://Stackoverflow.com/users/46473",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it with LINQ:</p>\n\n<pre><code>string[] Convert(char[,] chars)\n{\n return Enumerable.Range(0, chars.GetLength(1))\n .Select(i => Enumerable.Range(0, chars.GetLength(0))\n .Select(j => chars[j, i]))\n .Select(chars => new string(chars.ToArray());\n}\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8127/"
] |
I have a 2 dimensional array, like so:
```
char[,] str = new char[2,50];
```
Now, after I've stored contents in both str[0] and str[1], how do I store it in a
```
string[] s = new string[2];
```
?
I tried
```
s[0] = str[0].ToString();
```
but that seems to be an error: VC# expects 'two' indices within the braces, which means I can convert only a character from the array. Is there a way to convert the entire str[0] to a string? Or is changing it to a jagged array the only solution?
|
A jagged array is almost always the best solution for a variety of reasons, and this is one good example. There is so much more flexibility available with an array of arrays than with a multi-dimensional array. In this case, once you have the values in an array of chars, then a constructor on the string class can be used to create a string from it.
Also, the jagged array would be composed of "vectors" (i.e., a single-dimensional arrays with a zero-lower-bound index), which are much more preferment in .Net because they are given special treatment by the CLR.
So without knowing what the rest of your program is doing, that would be my recommendation.
If you do attempt to construct a string manually by looping through the array indexes, instead of using a jagged array, then I recommend using the StringBuilder class to do it.
I just banged this out, but it should be something like this:
```
// For the multi-dimentional array
StringBuilder sb = new StringBuilder();
for (int stringIndex = 0; stringIndex < s.Length; stringIndex++)
{
sb.Clear();
for (int charIndex = 0; charIndex < str.UpperBound(1); charIndex++)
sb.Append(str[stringIndex,charIndex]);
s[stringIndex] = sb.ToString();
}
// For the jagged array
for (int index = 0; index < s.Length; index++)
s[index] = new string(str[index]);
```
|
194,261 |
<p>I just played with Java file system API, and came down with the following function, used to copy binary files. The original source came from the Web, but I added try/catch/finally clauses to be sure that, should something wrong happen, the Buffer Streams would be closed (and thus, my OS ressources freed) before quiting the function.</p>
<p>I trimmed down the function to show the pattern:</p>
<pre><code>public static void copyFile(FileOutputStream oDStream, FileInputStream oSStream) throw etc...
{
BufferedInputStream oSBuffer = new BufferedInputStream(oSStream, 4096);
BufferedOutputStream oDBuffer = new BufferedOutputStream(oDStream, 4096);
try
{
try
{
int c;
while((c = oSBuffer.read()) != -1) // could throw a IOException
{
oDBuffer.write(c); // could throw a IOException
}
}
finally
{
oDBuffer.close(); // could throw a IOException
}
}
finally
{
oSBuffer.close(); // could throw a IOException
}
}
</code></pre>
<p>As far as I understand it, I cannot put the two <code>close()</code> in the finally clause because the first <code>close()</code> could well throw, and then, the second would not be executed.</p>
<p>I know C# has the <em>Dispose</em> pattern that would have handled this with the <code>using</code> keyword.</p>
<p>I even know better a C++ code would have been something like (using a Java-like API):</p>
<pre><code>void copyFile(FileOutputStream & oDStream, FileInputStream & oSStream)
{
BufferedInputStream oSBuffer(oSStream, 4096);
BufferedOutputStream oDBuffer(oDStream, 4096);
int c;
while((c = oSBuffer.read()) != -1) // could throw a IOException
{
oDBuffer.write(c); // could throw a IOException
}
// I don't care about resources, as RAII handle them for me
}
</code></pre>
<p>I am missing something, or do I really have to produce ugly and bloated code in Java just to handle exceptions in the <code>close()</code> method of a Buffered Stream?</p>
<p>(Please, tell me I'm wrong somewhere...)</p>
<p><strong>EDIT: Is it me, or when updating this page, I saw both the question and all the answers decreased by one point in a couple of minutes? Is someone enjoying himself too much while remaning anonymous?</strong></p>
<p>EDIT 2: <strong>McDowell</strong> offered a very interesting link I felt I had to mention here:
<a href="http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html" rel="noreferrer">http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html</a></p>
<p>EDIT 3: Following McDowell's link, I tumbled upon a proposal for Java 7 of a pattern similar to the C# using pattern: <a href="http://tech.puredanger.com/java7/#resourceblock" rel="noreferrer">http://tech.puredanger.com/java7/#resourceblock</a> . My problem is explicitly described. Apparently, even with the Java 7 <code>do</code>, the problems remain.</p>
|
[
{
"answer_id": 194281,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 2,
"selected": false,
"text": "<p>Unfortunately, this type of code tends to get a bit bloated in Java.</p>\n\n<p>By the way, if one of the calls to oSBuffer.read or oDBuffer.write throws an exception, then you probably want to let that exception permeate up the call hierarchy.</p>\n\n<p>Having an unguarded call to close() inside a finally-clause will cause the original exception to be replaced by one produced by the close()-call. In other words, a failing close()-method may hide the original exception produced by read() or write(). So, I think you want to ignore exceptions thrown by close() if <em>and only if</em> the other methods did not throw.</p>\n\n<p>I usually solve this by including an explicit close-call, inside the inner try:</p>\n\n<pre>\n try {\n while (...) {\n read...\n write...\n }\n oSBuffer.close(); // exception NOT ignored here\n oDBuffer.close(); // exception NOT ignored here\n } finally {\n silentClose(oSBuffer); // exception ignored here\n silentClose(oDBuffer); // exception ignored here\n }\n</pre>\n\n<pre>\n static void silentClose(Closeable c) {\n try {\n c.close();\n } catch (IOException ie) {\n // Ignored; caller must have this intention\n }\n }\n</pre>\n\n<p>Finally, for performance, the code should probably work with buffers (multiple bytes per read/write). Can't back that by numbers, but fewer calls should be more efficient than adding buffered streams on top.</p>\n"
},
{
"answer_id": 194288,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 5,
"selected": true,
"text": "<p>The try/finally pattern is the correct way to handle streams in most cases for Java 6 and lower.</p>\n\n<p><em>Some are advocating silently closing streams. Be careful doing this for these reasons: <a href=\"http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html\" rel=\"noreferrer\">Java: how not to make a mess of stream handling</a></em></p>\n\n<hr>\n\n<p>Java 7 introduces <em>try-with-resources</em>:</p>\n\n<pre><code>/** transcodes text file from one encoding to another */\npublic static void transcode(File source, Charset srcEncoding,\n File target, Charset tgtEncoding)\n throws IOException {\n try (InputStream in = new FileInputStream(source);\n Reader reader = new InputStreamReader(in, srcEncoding);\n OutputStream out = new FileOutputStream(target);\n Writer writer = new OutputStreamWriter(out, tgtEncoding)) {\n char[] buffer = new char[1024];\n int r;\n while ((r = reader.read(buffer)) != -1) {\n writer.write(buffer, 0, r);\n }\n }\n}\n</code></pre>\n\n<p><a href=\"http://download.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html\" rel=\"noreferrer\"><code>AutoCloseable</code></a> types will be automatically closed:</p>\n\n<pre><code>public class Foo {\n public static void main(String[] args) {\n class CloseTest implements AutoCloseable {\n public void close() {\n System.out.println(\"Close\");\n }\n }\n try (CloseTest closeable = new CloseTest()) {}\n }\n}\n</code></pre>\n"
},
{
"answer_id": 194292,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "<p>There are issues, but the code you found lying about on the web is really poor.</p>\n\n<p>Closing the buffer streams closes the stream underneath. You really don't want to do that. All you want to do is flush the output stream. Also there's no point in specifying the underlying streams are for files. Performance sucks because you are copying one byte at a time (actually if you use java.io use can use transferTo/transferFrom which is a bit faster still). While we are about it, the variable names suck to. So:</p>\n\n<pre><code>public static void copy(\n InputStream in, OutputStream out\n) throw IOException {\n byte[] buff = new byte[8192];\n for (;;) {\n int len = in.read(buff);\n if (len == -1) {\n break;\n }\n out.write(buff, 0, len);\n }\n}\n</code></pre>\n\n<p>If you find yourself using try-finally a lot, then you can factor it out with the \"execute around\" idiom.</p>\n\n<p>In my opinion: Java should have someway of closing resources at end of scope. I suggest adding <code>private</code> as a unary postfix operator to close at the end of the enclosing block.</p>\n"
},
{
"answer_id": 194309,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, that's how java works. There is control inversion - the user of the object has to know how to clean up the object instead of the object itself cleaning up after itself. This unfortunately leads to a lot of cleanup code scattered throughout your java code.</p>\n\n<p>C# has the \"using\" keyword to automatically call Dispose when an object goes out of scope. Java has no such thing.</p>\n"
},
{
"answer_id": 194334,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 2,
"selected": false,
"text": "<p>For common IO tasks such as copying a file, code such as that shown above is reinventing the wheel. Unfortunately, the JDK doesn't provide any higher level utilities, but apache commons-io does.</p>\n\n<p>For example, <a href=\"http://commons.apache.org/io/api-1.4/index.html?org/apache/commons/io/FileUtils.html\" rel=\"nofollow noreferrer\">FileUtils</a> contains various utility methods for working with files and directories (including copying). On the other hand, if you really need to use the IO support in the JDK, <a href=\"http://commons.apache.org/io/api-1.4/index.html?org/apache/commons/io/IOUtils.html\" rel=\"nofollow noreferrer\">IOUtils</a> contains a set of closeQuietly() methods that close Readers, Writers, Streams, etc. without throwing exceptions.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14089/"
] |
I just played with Java file system API, and came down with the following function, used to copy binary files. The original source came from the Web, but I added try/catch/finally clauses to be sure that, should something wrong happen, the Buffer Streams would be closed (and thus, my OS ressources freed) before quiting the function.
I trimmed down the function to show the pattern:
```
public static void copyFile(FileOutputStream oDStream, FileInputStream oSStream) throw etc...
{
BufferedInputStream oSBuffer = new BufferedInputStream(oSStream, 4096);
BufferedOutputStream oDBuffer = new BufferedOutputStream(oDStream, 4096);
try
{
try
{
int c;
while((c = oSBuffer.read()) != -1) // could throw a IOException
{
oDBuffer.write(c); // could throw a IOException
}
}
finally
{
oDBuffer.close(); // could throw a IOException
}
}
finally
{
oSBuffer.close(); // could throw a IOException
}
}
```
As far as I understand it, I cannot put the two `close()` in the finally clause because the first `close()` could well throw, and then, the second would not be executed.
I know C# has the *Dispose* pattern that would have handled this with the `using` keyword.
I even know better a C++ code would have been something like (using a Java-like API):
```
void copyFile(FileOutputStream & oDStream, FileInputStream & oSStream)
{
BufferedInputStream oSBuffer(oSStream, 4096);
BufferedOutputStream oDBuffer(oDStream, 4096);
int c;
while((c = oSBuffer.read()) != -1) // could throw a IOException
{
oDBuffer.write(c); // could throw a IOException
}
// I don't care about resources, as RAII handle them for me
}
```
I am missing something, or do I really have to produce ugly and bloated code in Java just to handle exceptions in the `close()` method of a Buffered Stream?
(Please, tell me I'm wrong somewhere...)
**EDIT: Is it me, or when updating this page, I saw both the question and all the answers decreased by one point in a couple of minutes? Is someone enjoying himself too much while remaning anonymous?**
EDIT 2: **McDowell** offered a very interesting link I felt I had to mention here:
<http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html>
EDIT 3: Following McDowell's link, I tumbled upon a proposal for Java 7 of a pattern similar to the C# using pattern: <http://tech.puredanger.com/java7/#resourceblock> . My problem is explicitly described. Apparently, even with the Java 7 `do`, the problems remain.
|
The try/finally pattern is the correct way to handle streams in most cases for Java 6 and lower.
*Some are advocating silently closing streams. Be careful doing this for these reasons: [Java: how not to make a mess of stream handling](http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html)*
---
Java 7 introduces *try-with-resources*:
```
/** transcodes text file from one encoding to another */
public static void transcode(File source, Charset srcEncoding,
File target, Charset tgtEncoding)
throws IOException {
try (InputStream in = new FileInputStream(source);
Reader reader = new InputStreamReader(in, srcEncoding);
OutputStream out = new FileOutputStream(target);
Writer writer = new OutputStreamWriter(out, tgtEncoding)) {
char[] buffer = new char[1024];
int r;
while ((r = reader.read(buffer)) != -1) {
writer.write(buffer, 0, r);
}
}
}
```
[`AutoCloseable`](http://download.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html) types will be automatically closed:
```
public class Foo {
public static void main(String[] args) {
class CloseTest implements AutoCloseable {
public void close() {
System.out.println("Close");
}
}
try (CloseTest closeable = new CloseTest()) {}
}
}
```
|
194,304 |
<p>I'm trying to think of clever, clear, and simple ways to write code that describes the sequence of integers in a given range. </p>
<p>Here's an example:</p>
<pre><code>IEnumerable<int> EnumerateIntegerRange(int from, int to)
{
for (int i = from; i <= to; i++)
{
yield return i;
}
}
</code></pre>
|
[
{
"answer_id": 194307,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "<p>This is already in the framework: <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx\" rel=\"noreferrer\">Enumerable.Range</a>.</p>\n\n<p>For other types, you might be interested in the range classes in my <a href=\"http://pobox.com/~skeet/csharp/miscutil\" rel=\"noreferrer\">MiscUtil</a> library.</p>\n"
},
{
"answer_id": 195920,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 0,
"selected": false,
"text": "<p>Here's an idea that lets a range class work with both things that are discrete and those which are not:</p>\n\n<pre><code>class Range<T> where T: IComparable<T>\n{\n public T From { get; set; }\n public T To { get; set; }\n\n public Range(T from, T to) { this.From = from; this.To = to; }\n\n public IEnumerable<T> Enumerate(Func<T, T> next)\n {\n for (T t = this.From; t.CompareTo(this.To) < 0; t = next(t))\n {\n yield return t;\n }\n }\n\n static void Example()\n {\n new Range<int> (0, 100).Enumerate(i => i+1)\n }\n}\n</code></pre>\n"
},
{
"answer_id": 195921,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 0,
"selected": false,
"text": "<p>And if you think that supplying the enumerator each time is annoying, here's a derived class:</p>\n\n<pre><code>class EnumerableRange<T> : Range<T>, IEnumerable<T>\n where T : IComparable<T>\n{\n readonly Func<T, T> _next;\n public EnumerableRange(T from, T to, Func<T, T> next)\n : base(from, to)\n {\n this._next = next;\n }\n\n public IEnumerator<T> GetEnumerator()\n {\n return Enumerate(this._next).GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return this.GetEnumerator();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 195924,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 3,
"selected": false,
"text": "<p>Alternately, a fluent interface from extension methods:</p>\n\n<pre><code>public static IEnumerable<int> To(this int start, int end)\n{\n return start.To(end, i => i + 1);\n}\n\npublic static IEnumerable<int> To(this int start, int end, Func<int, int> next)\n{\n int current = start;\n while (current < end)\n {\n yield return current;\n current = next(current);\n }\n}\n</code></pre>\n\n<p>used like:</p>\n\n<pre><code>1.To(100)\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5314/"
] |
I'm trying to think of clever, clear, and simple ways to write code that describes the sequence of integers in a given range.
Here's an example:
```
IEnumerable<int> EnumerateIntegerRange(int from, int to)
{
for (int i = from; i <= to; i++)
{
yield return i;
}
}
```
|
This is already in the framework: [Enumerable.Range](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx).
For other types, you might be interested in the range classes in my [MiscUtil](http://pobox.com/~skeet/csharp/miscutil) library.
|
194,328 |
<p>I know we can use tools like JProfiler etc.
Is there any tutorial on how to configure it to display the memory usage just by remote monitoring?</p>
<p>Any idea?</p>
|
[
{
"answer_id": 194351,
"author": "MatthieuGD",
"author_id": 3109,
"author_profile": "https://Stackoverflow.com/users/3109",
"pm_score": 3,
"selected": false,
"text": "<p>you have VisualGC, it's not very advanced but you can see the memory usage of your application (garbage,old, perm etc...)</p>\n\n<p><a href=\"http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jstatd.html\" rel=\"noreferrer\">http://java.sun.com/performance/jvmstat/visualgc.html</a></p>\n\n<p>to resume : \nyou launch a daemon monitoring on the remote machine (<a href=\"http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jstatd.html\" rel=\"noreferrer\">http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jstatd.html</a>, see the security parapraph)</p>\n\n<pre><code>JAVA_HOME/bin/jstatd -J-Djava.security.policy=jstatd.all.policy\n</code></pre>\n\n<p>with a file here called <strong>jstatd.all.policy</strong> containing :</p>\n\n<pre><code> grant codebase \"file:${java.home}/../lib/tools.jar\" { \npermission java.security.AllPermission;\n};\n</code></pre>\n\n<p>on the remote machine you got the pid of your application to debug with the jps tool :</p>\n\n<p><a href=\"http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jps.html#jps\" rel=\"noreferrer\">http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jps.html#jps</a></p>\n\n<p>finally on your local machine you launch the visualgc :</p>\n\n<pre><code>visualgc the_pid@remote_machine_address\n</code></pre>\n"
},
{
"answer_id": 229091,
"author": "Peter",
"author_id": 26483,
"author_profile": "https://Stackoverflow.com/users/26483",
"pm_score": 2,
"selected": false,
"text": "<p>You can change to VM params of your Java application to allow remote profiling\nsomething like <code>-agentlib:jprofilerti=port=25000</code></p>\n\n<p><a href=\"http://resources.ej-technologies.com/jprofiler/help/doc/\" rel=\"nofollow noreferrer\">General explanation of JProfiler</a>.</p>\n\n<p>Examples:</p>\n\n<ul>\n<li><p><a href=\"http://profiler.netbeans.org/docs/help/5.5/attach.html#direct_attach\" rel=\"nofollow noreferrer\">NetBeans</a> </p></li>\n<li><p><a href=\"http://plugins.intellij.net/plugin/?id=253\" rel=\"nofollow noreferrer\">Intellij</a></p></li>\n</ul>\n"
},
{
"answer_id": 229161,
"author": "joejag",
"author_id": 2257098,
"author_profile": "https://Stackoverflow.com/users/2257098",
"pm_score": 3,
"selected": false,
"text": "<p>I usually use YourKit which is an excellent application (license needed).</p>\n\n<p>In your webservers startup/shutdown script (catalina.sh for tomcat) put in:</p>\n\n<pre><code>JAVA_OPTS=\"-Djava.awt.headless=true -agentlib:yjpagent -Xrunyjpagent:sessionname=Tomcat\"\n</code></pre>\n\n<p>You'll need YourKit already downloaded and added to your library path (I do this in catalina.sh as well):</p>\n\n<pre><code>LD_LIBRARY_PATH=$LD_LIBRARY_PATH:~/yourkit/yjp-6.0.16/bin/linux-x86-32\n</code></pre>\n\n<p>You can then launch the YourKit client on your local desktop and remotely connect.</p>\n"
},
{
"answer_id": 8417604,
"author": "Madhu Cheepati",
"author_id": 1085899,
"author_profile": "https://Stackoverflow.com/users/1085899",
"pm_score": 1,
"selected": false,
"text": "<p>Profile your application using Jprofiler. Below are the steps to configure your Tomcat with Jprofiler. </p>\n\n<ol>\n<li><p>In Linux machine open <code>.bash_profile</code> file from <code>/root</code> directory.<br>\nEnter jprofiller location (using below command export) in </p>\n\n<pre><code>.bash_profile file\nexport LD_LIBRARY_PATH=/dsvol/jprofiler6/bin/linux-x86\n</code></pre></li>\n<li><p>Go Tomcat installation directory. Open <code>catalena.sh</code> file from <code>bin</code> folder.<br>\nEnter the below details in <code>catelana.sh</code> file (only red color information and black color you can find by default in catalena.sh file).</p>\n\n<pre><code>export JPROFILER_HOME\nJAVA_OPTS=\"-Xms768m -Xmx1024m -XX:PermSize=256m -XX:MaxPermSize=256m -Dfile.encoding=UTF8 -agentpath:/opt/Performance/jprofiler7/bin/linux-x86/libjprofilerti.so=port=8849 $CATALINA_OPTS\"\n</code></pre></li>\n<li><p>Start the server from bin folder by executing the <code>starup.sh</code> command</p></li>\n</ol>\n"
},
{
"answer_id": 12776596,
"author": "Moemars",
"author_id": 1000361,
"author_profile": "https://Stackoverflow.com/users/1000361",
"pm_score": 0,
"selected": false,
"text": "<p>I've heard good things of VisualVM and here is an article on how to it up remotely:</p>\n\n<p><a href=\"http://www.codefactorycr.com/java-visualvm-to-profile-a-remote-server.html\" rel=\"nofollow\">Java VisualVM to profile a remote server</a></p>\n\n<p><strong>EDIT</strong>:\nI wrote a blog post on how to setup remote profiling through an SSH tunnel here:</p>\n\n<p><a href=\"http://kamilmroczek.com/2012/11/16/168787859/\" rel=\"nofollow\">http://kamilmroczek.com/2012/11/16/168787859/</a></p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25368/"
] |
I know we can use tools like JProfiler etc.
Is there any tutorial on how to configure it to display the memory usage just by remote monitoring?
Any idea?
|
you have VisualGC, it's not very advanced but you can see the memory usage of your application (garbage,old, perm etc...)
[http://java.sun.com/performance/jvmstat/visualgc.html](http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jstatd.html)
to resume :
you launch a daemon monitoring on the remote machine (<http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jstatd.html>, see the security parapraph)
```
JAVA_HOME/bin/jstatd -J-Djava.security.policy=jstatd.all.policy
```
with a file here called **jstatd.all.policy** containing :
```
grant codebase "file:${java.home}/../lib/tools.jar" {
permission java.security.AllPermission;
};
```
on the remote machine you got the pid of your application to debug with the jps tool :
<http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jps.html#jps>
finally on your local machine you launch the visualgc :
```
visualgc the_pid@remote_machine_address
```
|
194,331 |
<p>I have a domain class containing a couple of fields. I can access them from my .gsps. I want to add a method to the domain class, which I can call from the .gsps (this method is a kind of virtual field; it's data is not coming directly from the database).</p>
<p>How do I add the method and how can I then call it from the .gsps?</p>
|
[
{
"answer_id": 194348,
"author": "Hates_",
"author_id": 3410,
"author_profile": "https://Stackoverflow.com/users/3410",
"pm_score": 5,
"selected": true,
"text": "<p>To add a method, just write it out like you would any other regular method. It will be available on the object when you display it in your GSP.</p>\n\n<pre><code>def someMethod() {\n return \"Hello.\"\n}\n</code></pre>\n\n<p>Then in your GSP.</p>\n\n<pre><code>${myObject.someMethod()}\n</code></pre>\n"
},
{
"answer_id": 199786,
"author": "John Flinchbaugh",
"author_id": 12591,
"author_profile": "https://Stackoverflow.com/users/12591",
"pm_score": 3,
"selected": false,
"text": "<p>If you want your method to appear to be more like a property, then make your method a getter method. A method called getFullName(), can be accessed like a property as ${person.fullName}. Note the lack of parentheses.</p>\n"
},
{
"answer_id": 18535117,
"author": "Ramesh",
"author_id": 2729165,
"author_profile": "https://Stackoverflow.com/users/2729165",
"pm_score": 2,
"selected": false,
"text": "<p>Consider class like below</p>\n\n<p>class Job {</p>\n\n<pre><code>String jobTitle\nString jobType\nString jobLocation\nString state\n\n\n\nstatic constraints = {\n\n jobTitle nullable : false,size: 0..200\n jobType nullable : false,size: 0..200\n jobLocation nullable : false,size: 0..200\n state nullable : false\n\n\n}\n\n\n\ndef jsonMap () {\n [\n 'jobTitle':\"some job title\",\n 'jobType':\"some jobType\",\n 'jobLocation':\"some location\",\n 'state':\"some state\"\n ]\n }\n</code></pre>\n\n<p>}</p>\n\n<p>You can use that jsonMap wherever you want. In gsp too like ${jobObject.jsonMap()}</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3506/"
] |
I have a domain class containing a couple of fields. I can access them from my .gsps. I want to add a method to the domain class, which I can call from the .gsps (this method is a kind of virtual field; it's data is not coming directly from the database).
How do I add the method and how can I then call it from the .gsps?
|
To add a method, just write it out like you would any other regular method. It will be available on the object when you display it in your GSP.
```
def someMethod() {
return "Hello."
}
```
Then in your GSP.
```
${myObject.someMethod()}
```
|
194,339 |
<p>I have several python projects that share common modules. Until now, I've been ... ahem ... keeping multiple copies of the common code and synchronizing by hand. But I'd clearly prefer to do something else.</p>
<p>It looks to me now, as if zc.Buildout maybe what I need. I guess that what I should be doing is putting each reusable component of my system into a separate egg, and then using buildout to assemble them into projects.</p>
<p>I'm also thinking that for any particular module, I should put the unit-tests into a separate package or egg, so that I'm not also installing copies of the component's unit-tests in every project. I only want to unit-test in a place where my library is developed, not where it's just being used.</p>
<p>So maybe I want something like this</p>
<pre><code>projects
lib1
tests
code
lib2
tests
code
app1
tests
appcode
app2
tests
appcode
</code></pre>
<p>etc.</p>
<p>Where both app1 and app2 are independent applications with their own code and tests, but are also including and using both lib1 and lib2. And lib1/test, lib1/code, lib2/test, lib2code, app1, app2 are separate eggs. Does this sound right?</p>
<p>However, I now get confused. I assume that when I develop app1, I want buildout to pull copies of lib1, lib2 and app1 into a separate working directory rather than put copies of these libraries under app1 directly. But how does this work with my SVN source-control? If the working directory is dynamically constructed with buildout, it can't be a live SVN directory from which I can check the changes back into the repository?</p>
<p>Have I misunderstood how buildout is meant to be used? Would I be better going for a completely different approach? How do you mix source-control with module-reuse between projects?</p>
<p>Update : thanks to the two people who've currently answered this question. I'm experimenting more with this.</p>
|
[
{
"answer_id": 194472,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>This is why you have the <a href=\"http://www.python.org/doc/2.5.2/lib/module-site.html\" rel=\"nofollow noreferrer\">site</a> module. It sets the internal <code>sys.path</code> to include all packages and modules from</p>\n\n<ul>\n<li><code>lib/site-packages</code> -- including directories, eggs and <code>.pth</code> files.</li>\n<li><code>PYTHONPATH</code></li>\n</ul>\n\n<p>This way there is exactly one working copy of your libraries.</p>\n\n<p>There are an unlimited ways to make use of this. Here are two.</p>\n\n<ol>\n<li><p>In each lib, write a <code>setup.py</code> that deploys your lib properly. When you make changes, you do an <code>svn up</code> to collect the changes and a <code>python setup.py install</code> to deploy the one working copy that every application shares.</p></li>\n<li><p>In each app, either depend on things being in the <code>PYTHONPATH</code> environment variable. Be sure that <code>projects/lib1</code> and <code>projects/lib2</code> are won the <code>PYTHONPATH</code>. Each app then shares the one working copy of the various libraries.</p></li>\n</ol>\n"
},
{
"answer_id": 195102,
"author": "Kozyarchuk",
"author_id": 52490,
"author_profile": "https://Stackoverflow.com/users/52490",
"pm_score": 2,
"selected": false,
"text": "<p>I've use the following structure quite effectively.\nin SVN.</p>\n\n<pre><code>Lib1/\n branches/\n tags/\n trunk/\n lib1/\n tests/\n setup.py\nLib2\n branches/\n tags/\n trunk/\n lib2/\n tests/\n setup.py\nApp1\n branches/\n tags/\n trunk/\n app1/\n tests/\n setup.py\nApp2\n branches/\n tags/\n trunk/\n app2/\n tests/\n setup.py\n</code></pre>\n\n<p>I would then create my dev workspace( I use eclipse/pydev) as follows, checking out from either trunk or a branch.</p>\n\n<pre><code>Lib1/\n lib1/\n tests/\n setup.py\nLib2/\n lib2/\n tests/\n setup.py\nApp1/\n app1/\n tests/\n setup.py\nApp2/\n app2/\n tests/\n setup.py\n</code></pre>\n\n<p>I would then use either eclipse project dependencies setup python path, which works well with eclipse code completion. setup.py also works but does not support having multiple workspaces well.</p>\n\n<p>For deployment, I use create a single zip with the following structure.</p>\n\n<pre><code>App1/\n lib1-1.1.0-py2.5.egg/\n lib2-1.1.0-py2.5.egg/\n app1/\n sitecustomize.py\n\nApp2/\n lib1-1.2.0-py2.5.egg/\n lib2-1.2.0-py2.5.egg/\n app2/\n sitecustomize.py\n</code></pre>\n\n<p>I don't use setup install because I want to support multiple versions of the app, also I have some control of the runtime environment, so I don't package python with my deployment but should be easy to add Python into the deployment package if it's needed.</p>\n"
},
{
"answer_id": 421758,
"author": "elarson",
"author_id": 5434,
"author_profile": "https://Stackoverflow.com/users/5434",
"pm_score": 1,
"selected": false,
"text": "<p>I'd consider each application and library an egg and use one of the examples already given in terms of laying it out in SVN. Really, the VCS end of things should not be an issue. </p>\n\n<p>Then, for testing each application/library or combination, I'd set up a virtualenv and install each package either via setup.py develop or via actually installing it. Virtualenvwrapper is also a helpful tool to manage these environments as you can simply do things like:</p>\n\n<pre><code>mkvirtualenv lib1-dev\n</code></pre>\n\n<p>And then later:</p>\n\n<pre><code>workon lib1-dev\n</code></pre>\n\n<p>Virtualenv uses the PYTHONPATH to gain finer control of the packages installed. Likewise, you can use create environments with:</p>\n\n<pre><code>virtualenv --no-site-packages some-env\n</code></pre>\n\n<p>And it will leave out any references to your actual system site-packages. This is helpful because not only can you test your library/application, but you can also verify you have the correct dependencies on installation. </p>\n"
},
{
"answer_id": 7620767,
"author": "Martijn Pieters",
"author_id": 100297,
"author_profile": "https://Stackoverflow.com/users/100297",
"pm_score": 3,
"selected": false,
"text": "<p>Do not separate the tests from your code, you need to keep the two closely together. It's not as if tests take up that much disk space or any memory! And tests can be extremely instructive to your library users.</p>\n\n<p>For library packages, include a <code>buildout.cfg</code> and <code>bootstrap.py</code> file with your package to make running the tests easy. See, for example, the <a href=\"https://github.com/plone/plone.reload\" rel=\"nofollow\">plone.reload package</a>; note how it uses <a href=\"http://pypi.python.org/pypi/zc.recipe.testrunner\" rel=\"nofollow\">zc.recipe.testrunner</a> parts to create a test script that'll autodiscover your tests and run them. This way you can ensure that your library packages are always tested!</p>\n\n<p>Then, your app packages only need to test the integration and application-specific code. Again, include the tests with the package itself, you want to not forget about your tests when working on the code. Use <code>zc.recipe.testrunner</code> parts in your buildout to discover and run these.</p>\n\n<p>Last but not least, use <a href=\"http://pypi.python.org/pypi/mr.developer\" rel=\"nofollow\">mr.developer</a> to manage your packages. With mr.developer, you can check out packages as your work on them, or rely on the released versions if you do not need to work on the code. A larger project will have many dependencies, many of which do not need you tweaking the code. With mr.developer you can pull in source code at will and turn these into development eggs, until such time you release that code and you can dismiss the checkout again.</p>\n\n<p>To see an actual example of such a project buildout, look no further than the <a href=\"https://github.com/plone/buildout.coredev\" rel=\"nofollow\">Plone core development buildout</a>.</p>\n\n<p>The <code>sources.cfg</code> file contains a long list of SCM locations for various packages, but normally released versions of eggs are used, until you explicitly activate the packages you plan to work on. <code>checkouts.cfg</code> lists all the packages checked out by default; these packages have changes that will be part of the next version of Plone and have not yet been released. If you work on Plone, you want these around because you cannot ignore these changes. And <code>testing.cfg</code> lists all the packages you need to test if you want to test Plone, a big list.</p>\n\n<p>Note that Plone's sources come from a wide variety of locations. Once you start using buildout and mr.developer to manage your packages, you are free to pull your source code from anywhere.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8482/"
] |
I have several python projects that share common modules. Until now, I've been ... ahem ... keeping multiple copies of the common code and synchronizing by hand. But I'd clearly prefer to do something else.
It looks to me now, as if zc.Buildout maybe what I need. I guess that what I should be doing is putting each reusable component of my system into a separate egg, and then using buildout to assemble them into projects.
I'm also thinking that for any particular module, I should put the unit-tests into a separate package or egg, so that I'm not also installing copies of the component's unit-tests in every project. I only want to unit-test in a place where my library is developed, not where it's just being used.
So maybe I want something like this
```
projects
lib1
tests
code
lib2
tests
code
app1
tests
appcode
app2
tests
appcode
```
etc.
Where both app1 and app2 are independent applications with their own code and tests, but are also including and using both lib1 and lib2. And lib1/test, lib1/code, lib2/test, lib2code, app1, app2 are separate eggs. Does this sound right?
However, I now get confused. I assume that when I develop app1, I want buildout to pull copies of lib1, lib2 and app1 into a separate working directory rather than put copies of these libraries under app1 directly. But how does this work with my SVN source-control? If the working directory is dynamically constructed with buildout, it can't be a live SVN directory from which I can check the changes back into the repository?
Have I misunderstood how buildout is meant to be used? Would I be better going for a completely different approach? How do you mix source-control with module-reuse between projects?
Update : thanks to the two people who've currently answered this question. I'm experimenting more with this.
|
Do not separate the tests from your code, you need to keep the two closely together. It's not as if tests take up that much disk space or any memory! And tests can be extremely instructive to your library users.
For library packages, include a `buildout.cfg` and `bootstrap.py` file with your package to make running the tests easy. See, for example, the [plone.reload package](https://github.com/plone/plone.reload); note how it uses [zc.recipe.testrunner](http://pypi.python.org/pypi/zc.recipe.testrunner) parts to create a test script that'll autodiscover your tests and run them. This way you can ensure that your library packages are always tested!
Then, your app packages only need to test the integration and application-specific code. Again, include the tests with the package itself, you want to not forget about your tests when working on the code. Use `zc.recipe.testrunner` parts in your buildout to discover and run these.
Last but not least, use [mr.developer](http://pypi.python.org/pypi/mr.developer) to manage your packages. With mr.developer, you can check out packages as your work on them, or rely on the released versions if you do not need to work on the code. A larger project will have many dependencies, many of which do not need you tweaking the code. With mr.developer you can pull in source code at will and turn these into development eggs, until such time you release that code and you can dismiss the checkout again.
To see an actual example of such a project buildout, look no further than the [Plone core development buildout](https://github.com/plone/buildout.coredev).
The `sources.cfg` file contains a long list of SCM locations for various packages, but normally released versions of eggs are used, until you explicitly activate the packages you plan to work on. `checkouts.cfg` lists all the packages checked out by default; these packages have changes that will be part of the next version of Plone and have not yet been released. If you work on Plone, you want these around because you cannot ignore these changes. And `testing.cfg` lists all the packages you need to test if you want to test Plone, a big list.
Note that Plone's sources come from a wide variety of locations. Once you start using buildout and mr.developer to manage your packages, you are free to pull your source code from anywhere.
|
194,346 |
<p>I have an HTML page (say welcome.html) which contains an iframe to a page I have no control over (say app.html). The user performs some actions using the app within the iframe and clicks submit. Once they do this, they are taken to a new page (say thanks.jsp), which loads within the iframe. Is there a way in which I can force thanks.jsp to load in the full frame and not the iframe once submit is clicked? Remember, I have no control over the logic behind that Submit button or app.html. I do however have control over welcome.html and thanks.jsp. If possible, I would like to stick with HTML and/or JavaScript. Thank you in advance.</p>
|
[
{
"answer_id": 194363,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 4,
"selected": true,
"text": "<p>You probably want to use a framebuster, with a base target in case it fails.</p>\n\n<p>First:</p>\n\n<p><strong>If</strong> <code>thanks.jsp</code> is requested via a post request - redirect so it you present the page as the response to a get request.</p>\n\n<p>Then:</p>\n\n<p>Include framebuster JavaScript:</p>\n\n<pre><code><script type=\"text/javascript\">\n if (self != top) { top.location.replace(location); }\n</script>\n</code></pre>\n\n<p>Finally:</p>\n\n<p>In case the user doesn't have JavaScript enabled, make sure they don't stay in the frame any longer then they have to:</p>\n\n<pre><code><base target=\"_top\"></code></pre>\n"
},
{
"answer_id": 194365,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 2,
"selected": false,
"text": "<p>On <code>thanks.jsp</code> you can put in the following JS:</p>\n\n<pre><code>// Parent window not the same as this one\nif (self !=top) \n{\n top.location.href = self.location.href;\n} \n</code></pre>\n\n<p>This will work provided that you have <code>thanks.jsp</code> on the same server as the original page containing the frame, due to the <a href=\"http://en.wikipedia.org/wiki/Same_origin_policy\" rel=\"nofollow noreferrer\">same origin policy</a>.</p>\n\n<p>The above code checks the url of the page you're on, then the one of the page it's executing on (<code>thanks.jsp</code>) - if they don't match you're sent to the <code>thanks.jsp</code> url. This method works fine when <code>thanks.jsp</code> is a static page, but won't carry postdata etc across with it.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78/"
] |
I have an HTML page (say welcome.html) which contains an iframe to a page I have no control over (say app.html). The user performs some actions using the app within the iframe and clicks submit. Once they do this, they are taken to a new page (say thanks.jsp), which loads within the iframe. Is there a way in which I can force thanks.jsp to load in the full frame and not the iframe once submit is clicked? Remember, I have no control over the logic behind that Submit button or app.html. I do however have control over welcome.html and thanks.jsp. If possible, I would like to stick with HTML and/or JavaScript. Thank you in advance.
|
You probably want to use a framebuster, with a base target in case it fails.
First:
**If** `thanks.jsp` is requested via a post request - redirect so it you present the page as the response to a get request.
Then:
Include framebuster JavaScript:
```
<script type="text/javascript">
if (self != top) { top.location.replace(location); }
</script>
```
Finally:
In case the user doesn't have JavaScript enabled, make sure they don't stay in the frame any longer then they have to:
```
<base target="_top">
```
|
194,382 |
<p>What is the difference between applying the visitor design pattern to your code and the following approach:</p>
<pre><code>interface Dointerface {
public void perform(Object o);
}
public class T {
private Dointerface d;
private String s;
public String getS() {
return s;
}
public T(String s) {
this.s = s;
}
public void setInterface(Dointerface d) {
this.d = d;
}
public void perform() {
d.perform(this);
}
public static void main(String[] args) {
T t = new T("Geonline");
t.setInterface(new Dointerface() {
public void perform(Object o) {
T a = (T)o;
System.out.println(a.getS());
}
});
t.perform();
}
}
</code></pre>
<p>I assume that by using interfaces, we're not really separating the algorithm.</p>
|
[
{
"answer_id": 194398,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "<p>The only thing that I see that is readily obvious is that by storing the interface, you make it so you have to do two operations rather than one to invoke it. I suppose that this could make sense if you are repeatedly going to perform the same action once the interface is set, but I think you could stick with the standard Visitor and accomplish the same thing.</p>\n"
},
{
"answer_id": 194438,
"author": "AdamC",
"author_id": 16476,
"author_profile": "https://Stackoverflow.com/users/16476",
"pm_score": 3,
"selected": false,
"text": "<p>There is quite a big difference. </p>\n\n<p>The visitor pattern uses interfaces, but its purpose is to be able to perform an operation to one or more classes (who implement an interface) without having to change the classes. Hence, the implementation actually \"visits\" the class and does its thing without the class being modified.</p>\n\n<p>An interface is a basic concept used to provide a common API to a potentially diverse group of classes. The typical test for an interface is that classes that share it are alike in at least that one respect (is-like-a) and in those cases can be treated as such.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Visitor_pattern#Example_in_Java\" rel=\"noreferrer\">Here is a simple example on wikipedia that shows a couple of visitors in java.</a></p>\n"
},
{
"answer_id": 194452,
"author": "Benno Richters",
"author_id": 3565,
"author_profile": "https://Stackoverflow.com/users/3565",
"pm_score": 3,
"selected": true,
"text": "<p>Two things:</p>\n\n<ul>\n<li>In your example you need two methods. The <code>perfom</code> and the <code>setInterface</code>. With a visitor pattern you would only need one method, the <code>perfom</code>, usually called <code>accept</code>. </li>\n<li>If you need more than one 'performer', you will have to set the performer -via the <code>setInterface</code> method- for each. This makes it impossible to make your class immutable.</li>\n</ul>\n"
},
{
"answer_id": 194986,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 2,
"selected": false,
"text": "<p>The most important difference in these examples is that in the visitor case you retain the compile-time concrete type of \"this\". This allows you to use double dispatch, where the method to be called is dependent on both the concrete data type and the visitor implementation. Double dispatch is just a special case of multiple dispatch where the method invoked is dependent on the receiver and the types of the parameters to the method. Java is of course single dispatch but some other languages support multiple dispatch.</p>\n\n<p>The basic driving force behind the visitor pattern is that by using interfaces on the concrete nodes, every operation that needs to be added to a composite data structure must change every node. The visitor pattern uses a generic (static) pattern on the nodes so that dynamically adding operations is easy. The downside is that modifying the data structure (by adding or removing concrete nodes) becomes more difficult as all operation visitors are affected.</p>\n\n<p>In general, this trade=off is a better match as it's more frequent to extend operations over a data structure than to change the data structure itself. Here's a lengthier writing of mine on how to use visitors and a bunch of considerations:</p>\n\n<ul>\n<li><a href=\"http://tech.puredanger.com/2007/07/16/visitor/\" rel=\"nofollow noreferrer\">http://tech.puredanger.com/2007/07/16/visitor/</a></li>\n</ul>\n\n<p>You might fairly ask if there is a pattern that allows us to do both: add operations or extend our data structures without breaking existing code. This is known as The Expression Problem as coined by Philip Wadler. You can find some links on this and more here:</p>\n\n<ul>\n<li><a href=\"http://tech.puredanger.com/presentations/design-patterns-reconsidered\" rel=\"nofollow noreferrer\">http://tech.puredanger.com/presentations/design-patterns-reconsidered</a></li>\n</ul>\n"
},
{
"answer_id": 217105,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 2,
"selected": false,
"text": "<p>A Visitor pattern is used when you have a data structure made up of many different classes and you have multiple algorithms that require a different operation for each class. In your example your DoInterface implementation only does one operation on one type. The only thing you do is print the result of getS() and because you cast o to T you can only do this to classes of type T.</p>\n\n<p>If you wanted to apply your interface to a typical visitor style class you your the class with your DoInterface.perform function would likely end up with a big if else if statement in it something like this:</p>\n\n<pre><code> public void visit(Object o) {\n if (o instanceof File)\n visitFile((File)o);\n else if (o instanceof Directory)\n visitDirectory((Directory)o);\n else if (o instanceof X)\n // ...\n }\n</code></pre>\n\n<p>Because this uses Object it will allow callers with any type which can create errors which will only show up at runtime. A Visitor gets around this by creating a “visitType” function for each type in the data structure. The classes in the data structure are then responsible for knowing which function on the visitor to call. The mapping is performed by each of the data structure’s classes implementing an accept function that then calls back on the Visitor class. If the function for the type does not exist on the visitor you get a compile error. The accept method looks like this:</p>\n\n<pre><code> @Override\n public void accept(FileSystemVisitor v) {\n v.visitFile(this);\n }\n</code></pre>\n\n<p>Part of the trouble with the Visitor pattern is that it takes quite a lot of code to really do it justice in a sample. I think this is why a lot of people don't get it as it is easy to get distracted by the other code. I have created a simple file system sample that hopefully shows how to use a visitor more clearly. It creates a composite with some files and directories in and then performs two operations on the hierarchy. In practice you would probably want more than two data classes and two operations to justify this pattern but this is only an example.</p>\n\n<pre><code>public class VisitorSample {\n //\n public abstract class FileSystemItem {\n public abstract String getName();\n public abstract int getSize();\n public abstract void accept(FileSystemVisitor v);\n }\n // \n public abstract class FileSystemItemContainer extends FileSystemItem {\n protected java.util.ArrayList<FileSystemItem> _list = new java.util.ArrayList<FileSystemItem>();\n // \n public void addItem(FileSystemItem item)\n {\n _list.add(item);\n }\n //\n public FileSystemItem getItem(int i)\n {\n return _list.get(i);\n }\n // \n public int getCount() {\n return _list.size();\n }\n // \n public abstract void accept(FileSystemVisitor v);\n public abstract String getName();\n public abstract int getSize();\n }\n // \n public class File extends FileSystemItem {\n //\n public String _name;\n public int _size;\n // \n public File(String name, int size) {\n _name = name;\n _size = size;\n }\n // \n @Override\n public void accept(FileSystemVisitor v) {\n v.visitFile(this);\n }\n //\n @Override\n public String getName() {\n return _name;\n }\n //\n @Override\n public int getSize() {\n return _size;\n }\n }\n // \n public class Directory extends FileSystemItemContainer {\n //\n private String _name;\n // \n public Directory(String name) {\n _name = name;\n }\n // \n @Override\n public void accept(FileSystemVisitor v) {\n v.visitDirectory(this);\n }\n //\n @Override\n public String getName() {\n return _name;\n }\n //\n @Override\n public int getSize() {\n int size = 0;\n for (int i = 0; i < _list.size(); i++)\n {\n size += _list.get(i).getSize();\n }\n return size;\n } \n }\n // \n public abstract class FileSystemVisitor {\n // \n public void visitFile(File f) { }\n public void visitDirectory(Directory d) { }\n //\n public void vistChildren(FileSystemItemContainer c) {\n for (int i = 0; i < c.getCount(); i++)\n {\n c.getItem(i).accept(this);\n }\n }\n }\n // \n public class ListingVisitor extends FileSystemVisitor {\n // \n private int _indent = 0;\n // \n @Override\n public void visitFile(File f) {\n for (int i = 0; i < _indent; i++)\n System.out.print(\" \");\n System.out.print(\"~\");\n System.out.print(f.getName());\n System.out.print(\":\");\n System.out.println(f.getSize());\n }\n // \n @Override\n public void visitDirectory(Directory d) {\n for (int i = 0; i < _indent; i++)\n System.out.print(\" \"); \n System.out.print(\"\\\\\");\n System.out.print(d.getName());\n System.out.println(\"\\\\\");\n // \n _indent += 3;\n vistChildren(d);\n _indent -= 3;\n }\n }\n // \n public class XmlVisitor extends FileSystemVisitor {\n // \n private int _indent = 0;\n // \n @Override\n public void visitFile(File f) {\n for (int i = 0; i < _indent; i++)\n System.out.print(\" \");\n System.out.print(\"<file name=\\\"\");\n System.out.print(f.getName());\n System.out.print(\"\\\" size=\\\"\");\n System.out.print(f.getSize());\n System.out.println(\"\\\" />\");\n }\n // \n @Override\n public void visitDirectory(Directory d) {\n for (int i = 0; i < _indent; i++)\n System.out.print(\" \");\n System.out.print(\"<directory name=\\\"\");\n System.out.print(d.getName());\n System.out.print(\"\\\" size=\\\"\");\n System.out.print(d.getSize());\n System.out.println(\"\\\">\");\n // \n _indent += 4;\n vistChildren(d);\n _indent -= 4;\n // \n for (int i = 0; i < _indent; i++)\n System.out.print(\" \");\n System.out.println(\"</directory>\");\n }\n }\n // \n public static void main(String[] args) {\n VisitorSample s = new VisitorSample();\n // \n Directory root = s.new Directory(\"root\");\n root.addItem(s.new File(\"FileA\", 163));\n root.addItem(s.new File(\"FileB\", 760));\n Directory sub = s.new Directory(\"sub\");\n root.addItem(sub);\n sub.addItem(s.new File(\"FileC\", 401));\n sub.addItem(s.new File(\"FileD\", 543));\n Directory subB = s.new Directory(\"subB\");\n root.addItem(subB);\n subB.addItem(s.new File(\"FileE\", 928));\n subB.addItem(s.new File(\"FileF\", 238));\n // \n XmlVisitor xmlVisitor = s.new XmlVisitor();\n root.accept(xmlVisitor);\n // \n ListingVisitor listing = s.new ListingVisitor();\n root.accept(listing);\n }\n }\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11234/"
] |
What is the difference between applying the visitor design pattern to your code and the following approach:
```
interface Dointerface {
public void perform(Object o);
}
public class T {
private Dointerface d;
private String s;
public String getS() {
return s;
}
public T(String s) {
this.s = s;
}
public void setInterface(Dointerface d) {
this.d = d;
}
public void perform() {
d.perform(this);
}
public static void main(String[] args) {
T t = new T("Geonline");
t.setInterface(new Dointerface() {
public void perform(Object o) {
T a = (T)o;
System.out.println(a.getS());
}
});
t.perform();
}
}
```
I assume that by using interfaces, we're not really separating the algorithm.
|
Two things:
* In your example you need two methods. The `perfom` and the `setInterface`. With a visitor pattern you would only need one method, the `perfom`, usually called `accept`.
* If you need more than one 'performer', you will have to set the performer -via the `setInterface` method- for each. This makes it impossible to make your class immutable.
|
194,443 |
<p>I want to post an xml document to an <strong>asp</strong> page from an <strong>asp.net</strong> page. If I use WebRequest with content/type text/xml the document never gets to the asp page. How can I do this ?</p>
|
[
{
"answer_id": 194467,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>It's absolutely possible. Make sure that you are writing the XML to the RequestStream.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getrequeststream.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getrequeststream.aspx</a></p>\n"
},
{
"answer_id": 197728,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I do use GetRequestStream. But if you try to send xml like <code><data id='10'>value</data></code> with content-type text/xml the document never gets to its destination</p>\n"
},
{
"answer_id": 315438,
"author": "Sunny Milenov",
"author_id": 8220,
"author_profile": "https://Stackoverflow.com/users/8220",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a sample without any error handling (do it yourself :) ):</p>\n\n<pre><code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);\nstring sendString = formParameterName + \"=\" + HttpUtility.UrlEncode(xmlData);\nbyte[] byteStream;\nbyteStream = System.Text.Encoding.UTF8.GetBytes(sendString);\n\nrequest.Method = POST;\nrequest.ContentType = \"application/x-www-form-urlencoded\";\nrequest.ContentLength = byteStream.LongLength;\n\nusing(Stream writer = request.GetRequestStream())\n{\n writer.Write(byteStream, 0, (int)request.ContentLength);\n writer.Flush();\n}\n\nHttpWebResponse resp = (HttpWebResponse)request.GetResponse();\n\n//read the response\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I want to post an xml document to an **asp** page from an **asp.net** page. If I use WebRequest with content/type text/xml the document never gets to the asp page. How can I do this ?
|
Here is a sample without any error handling (do it yourself :) ):
```
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
byte[] byteStream;
byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
request.Method = POST;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteStream.LongLength;
using(Stream writer = request.GetRequestStream())
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
//read the response
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.