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
|
---|---|---|---|---|---|---|
185,573 |
<p>I couldn't really find this in Rails documentation but it seems like <strong>'mattr_accessor'</strong> is the <strong>Module</strong> corollary for <strong>'attr_accessor'</strong> (getter & setter) in a normal Ruby <strong>class</strong>.</p>
<p>Eg. in a class</p>
<pre><code>class User
attr_accessor :name
def set_fullname
@name = "#{self.first_name} #{self.last_name}"
end
end
</code></pre>
<p>Eg. in a module</p>
<pre><code>module Authentication
mattr_accessor :current_user
def login
@current_user = session[:user_id] || nil
end
end
</code></pre>
<p>This helper method is provided by <strong>ActiveSupport</strong>.</p>
|
[
{
"answer_id": 185632,
"author": "Avdi",
"author_id": 20487,
"author_profile": "https://Stackoverflow.com/users/20487",
"pm_score": 9,
"selected": true,
"text": "<p>Rails extends Ruby with both <code>mattr_accessor</code> (Module accessor) and <code>cattr_accessor</code> (as well as _<code>reader</code>/<code>_writer</code> versions). As Ruby's <code>attr_accessor</code> generates getter/setter methods for <em>instances</em>, <code>cattr/mattr_accessor</code> provide getter/setter methods at the <em>class</em> or <em>module</em> level. Thus:</p>\n\n<pre><code>module Config\n mattr_accessor :hostname\n mattr_accessor :admin_email\nend\n</code></pre>\n\n<p>is short for:</p>\n\n<pre><code>module Config\n def self.hostname\n @hostname\n end\n def self.hostname=(hostname)\n @hostname = hostname\n end\n def self.admin_email\n @admin_email\n end\n def self.admin_email=(admin_email)\n @admin_email = admin_email\n end\nend\n</code></pre>\n\n<p>Both versions allow you to access the module-level variables like so:</p>\n\n<pre><code>>> Config.hostname = \"example.com\"\n>> Config.admin_email = \"[email protected]\"\n>> Config.hostname # => \"example.com\"\n>> Config.admin_email # => \"[email protected]\"\n</code></pre>\n"
},
{
"answer_id": 188915,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://github.com/rails/rails/tree/2-1-stable/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb\" rel=\"noreferrer\">Here's the source for <code>cattr_accessor</code></a></p>\n\n<p>And </p>\n\n<p><a href=\"http://github.com/rails/rails/tree/2-1-stable/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb\" rel=\"noreferrer\">Here's the source for <code>mattr_accessor</code></a></p>\n\n<p>As you can see, they're pretty much identical.</p>\n\n<p>As to why there are two different versions? Sometimes you want to write <code>cattr_accessor</code> in a module, so you can use it for configuration info <a href=\"https://stackoverflow.com/questions/185573/what-is-mattraccessor-in-a-rails-module#185632\">like Avdi mentions</a>.<br>\nHowever, <code>cattr_accessor</code> doesn't work in a module, so they more or less copied the code over to work for modules also. </p>\n\n<p>Additionally, sometimes you might want to write a class method in a module, such that whenever any class includes the module, it gets that class method as well as all the instance methods. <code>mattr_accessor</code> also lets you do this.</p>\n\n<p>However, in the second scenario, it's behaviour is pretty strange. Observe the following code, particularly note the <code>@@mattr_in_module</code> bits</p>\n\n<pre><code>module MyModule\n mattr_accessor :mattr_in_module\nend\n\nclass MyClass\n include MyModule\n def self.get_mattr; @@mattr_in_module; end # directly access the class variable\nend\n\nMyModule.mattr_in_module = 'foo' # set it on the module\n=> \"foo\"\n\nMyClass.get_mattr # get it out of the class\n=> \"foo\"\n\nclass SecondClass\n include MyModule\n def self.get_mattr; @@mattr_in_module; end # again directly access the class variable in a different class\nend\n\nSecondClass.get_mattr # get it out of the OTHER class\n=> \"foo\"\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6048/"
] |
I couldn't really find this in Rails documentation but it seems like **'mattr\_accessor'** is the **Module** corollary for **'attr\_accessor'** (getter & setter) in a normal Ruby **class**.
Eg. in a class
```
class User
attr_accessor :name
def set_fullname
@name = "#{self.first_name} #{self.last_name}"
end
end
```
Eg. in a module
```
module Authentication
mattr_accessor :current_user
def login
@current_user = session[:user_id] || nil
end
end
```
This helper method is provided by **ActiveSupport**.
|
Rails extends Ruby with both `mattr_accessor` (Module accessor) and `cattr_accessor` (as well as \_`reader`/`_writer` versions). As Ruby's `attr_accessor` generates getter/setter methods for *instances*, `cattr/mattr_accessor` provide getter/setter methods at the *class* or *module* level. Thus:
```
module Config
mattr_accessor :hostname
mattr_accessor :admin_email
end
```
is short for:
```
module Config
def self.hostname
@hostname
end
def self.hostname=(hostname)
@hostname = hostname
end
def self.admin_email
@admin_email
end
def self.admin_email=(admin_email)
@admin_email = admin_email
end
end
```
Both versions allow you to access the module-level variables like so:
```
>> Config.hostname = "example.com"
>> Config.admin_email = "[email protected]"
>> Config.hostname # => "example.com"
>> Config.admin_email # => "[email protected]"
```
|
185,575 |
<p>In bash the ampersand (&) can be used to run a command in the background and return interactive control to the user before the command has finished running. Is there an equivalent method of doing this in Powershell?</p>
<p>Example of usage in bash:</p>
<pre><code> sleep 30 &
</code></pre>
|
[
{
"answer_id": 186736,
"author": "Jeffery Hicks",
"author_id": 25508,
"author_profile": "https://Stackoverflow.com/users/25508",
"pm_score": 0,
"selected": false,
"text": "<p>I've used the solution described here <a href=\"http://jtruher.spaces.live.com/blog/cns!7143DA6E51A2628D!130.entry\" rel=\"nofollow noreferrer\">http://jtruher.spaces.live.com/blog/cns!7143DA6E51A2628D!130.entry</a> successfully in PowerShell v1.0. It definitely will be easier in PowerShell v2.0.</p>\n"
},
{
"answer_id": 6459716,
"author": "Dustin Getz",
"author_id": 20003,
"author_profile": "https://Stackoverflow.com/users/20003",
"pm_score": 5,
"selected": false,
"text": "<pre><code>ps2> start-job {start-sleep 20}\n</code></pre>\n\n<p>i have not yet figured out how to get stdout in realtime, start-job requires you to poll stdout with get-job</p>\n\n<p>update: i couldn't start-job to easily do what i want which is basically the bash & operator. here's my best hack so far</p>\n\n<pre><code>PS> notepad $profile #edit init script -- added these lines\nfunction beep { write-host `a }\nfunction ajp { start powershell {ant java-platform|out-null;beep} } #new window, stderr only, beep when done\nfunction acjp { start powershell {ant clean java-platform|out-null;beep} }\nPS> . $profile #re-load profile script\nPS> ajp\n</code></pre>\n"
},
{
"answer_id": 11372785,
"author": "Gian Marco",
"author_id": 66629,
"author_profile": "https://Stackoverflow.com/users/66629",
"pm_score": 5,
"selected": false,
"text": "<p>Seems that the script block passed to <code>Start-Job</code> is not executed with the same current directory as the <code>Start-Job</code> command, so make sure to specify fully qualified path if needed. </p>\n\n<p>For example:</p>\n\n<pre><code>Start-Job { C:\\absolute\\path\\to\\command.exe --afileparameter C:\\absolute\\path\\to\\file.txt }\n</code></pre>\n"
},
{
"answer_id": 13729303,
"author": "Bogdan Calmac",
"author_id": 424353,
"author_profile": "https://Stackoverflow.com/users/424353",
"pm_score": 7,
"selected": false,
"text": "<p>As long as the command is an executable or a file that has an associated executable, use <strong>Start-Process</strong> (available from v2):</p>\n\n<pre><code>Start-Process -NoNewWindow ping google.com\n</code></pre>\n\n<p>You can also add this as a function in your profile:</p>\n\n<pre><code>function bg() {Start-Process -NoNewWindow @args}\n</code></pre>\n\n<p>and then the invocation becomes:</p>\n\n<pre><code>bg ping google.com\n</code></pre>\n\n<p>In my opinion, Start-Job is an overkill for the simple use case of running a process in the background:</p>\n\n<ol>\n<li>Start-Job does not have access to your existing scope (because it runs in a separate session). You cannot do \"Start-Job {notepad $myfile}\"</li>\n<li>Start-Job does not preserve the current directory (because it runs in a separate session). You cannot do \"Start-Job {notepad myfile.txt}\" where myfile.txt is in the current directory.</li>\n<li>The output is not displayed automatically. You need to run Receive-Job with the ID of the job as parameter.</li>\n</ol>\n\n<p>NOTE: Regarding your initial example, \"bg sleep 30\" would not work because sleep is a Powershell commandlet. Start-Process only works when you actually fork a process.</p>\n"
},
{
"answer_id": 40503302,
"author": "Eric",
"author_id": 6550477,
"author_profile": "https://Stackoverflow.com/users/6550477",
"pm_score": 5,
"selected": false,
"text": "<p>You can use PowerShell job cmdlets to achieve your goals.</p>\n\n<p>There are 6 job related cmdlets available in PowerShell.</p>\n\n<ul>\n<li>Get-Job\n\n<ul>\n<li>Gets Windows PowerShell background jobs that are running in the current session</li>\n</ul></li>\n<li>Receive-Job\n\n<ul>\n<li>Gets the results of the Windows PowerShell background jobs in the current session</li>\n</ul></li>\n<li>Remove-Job\n\n<ul>\n<li>Deletes a Windows PowerShell background job</li>\n</ul></li>\n<li>Start-Job\n\n<ul>\n<li>Starts a Windows PowerShell background job</li>\n</ul></li>\n<li>Stop-Job\n\n<ul>\n<li>Stops a Windows PowerShell background job</li>\n</ul></li>\n<li>Wait-Job\n\n<ul>\n<li>Suppresses the command prompt until one or all of the Windows PowerShell background jobs running in the session are complete</li>\n</ul></li>\n</ul>\n\n<p>If interesting about it, you can download the sample <a href=\"https://gallery.technet.microsoft.com/How-to-create-background-b2a6a8ee\" rel=\"noreferrer\">How to create background job in PowerShell</a></p>\n"
},
{
"answer_id": 53892094,
"author": "Mariusz Pawelski",
"author_id": 350384,
"author_profile": "https://Stackoverflow.com/users/350384",
"pm_score": 6,
"selected": false,
"text": "<p>From PowerShell Core 6.0 you are able to write <code>&</code> at end of command and it will be equivalent to running you pipeline <strong>in background in current working directory</strong>.</p>\n\n<p>It's not equivalent to <code>&</code> in bash, it's just a nicer syntax for current PowerShell <a href=\"https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_jobs?view=powershell-6\" rel=\"noreferrer\">jobs</a> feature. It returns a job object so you can use all other command that you would use for jobs. For example <code>Receive-Job</code>:</p>\n\n<pre><code>C:\\utils> ping google.com &\n\nId Name PSJobTypeName State HasMoreData Location Command\n-- ---- ------------- ----- ----------- -------- -------\n35 Job35 BackgroundJob Running True localhost Microsoft.PowerShell.M...\n\n\nC:\\utils> Receive-Job 35\n\nPinging google.com [172.217.16.14] with 32 bytes of data:\nReply from 172.217.16.14: bytes=32 time=11ms TTL=55\nReply from 172.217.16.14: bytes=32 time=11ms TTL=55\nReply from 172.217.16.14: bytes=32 time=10ms TTL=55\nReply from 172.217.16.14: bytes=32 time=10ms TTL=55\n\nPing statistics for 172.217.16.14:\n Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),\nApproximate round trip times in milli-seconds:\n Minimum = 10ms, Maximum = 11ms, Average = 10ms\nC:\\utils>\n</code></pre>\n\n<p>If you want to execute couple of statements in background you can combine <a href=\"https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-6#call-operator-\" rel=\"noreferrer\"><code>&</code> call operator</a>, <a href=\"https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_script_blocks?view=powershell-6\" rel=\"noreferrer\"><code>{ }</code> script block</a> and this new <a href=\"https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-6#background-operator-\" rel=\"noreferrer\"><code>&</code> background operator</a> like here:</p>\n\n<pre><code>& { cd .\\SomeDir\\; .\\SomeLongRunningOperation.bat; cd ..; } &\n</code></pre>\n\n<hr>\n\n<p>Here's some more info from documentation pages:</p>\n\n<p>from <a href=\"https://learn.microsoft.com/en-us/powershell/scripting/whats-new/what-s-new-in-powershell-core-60?view=powershell-6#support-backgrounding-of-pipelines-with-ampersand--3360\" rel=\"noreferrer\"><em>What's New in PowerShell Core 6.0</em></a>:</p>\n\n<blockquote>\n <p><strong>Support backgrounding of pipelines with ampersand (&) (#3360)</strong></p>\n \n <p>Putting <code>&</code> at the end of a pipeline causes the pipeline to be run as a PowerShell job. When a pipeline is backgrounded, a job object is returned. Once the pipeline is running as a job, all of the standard <code>*-Job</code> cmdlets can be used to manage the job. Variables (ignoring process-specific variables) used in the pipeline are automatically copied to the job so <code>Copy-Item $foo $bar &</code> just works. The job is also run in the current directory instead of the user's home directory. For more information about PowerShell jobs, see <a href=\"https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_jobs?view=powershell-6\" rel=\"noreferrer\">about_Jobs</a>.</p>\n</blockquote>\n\n<p>from <a href=\"https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-6#ampersand-background-operator-\" rel=\"noreferrer\"><em>about_operators / Ampersand background operator &</em></a>:</p>\n\n<blockquote>\n <p><strong>Ampersand background operator &</strong></p>\n \n <p>Runs the pipeline before it in a PowerShell job. The ampersand background operator acts similarly to the UNIX \"ampersand operator\" which famously runs the command before it as a background process. The ampersand background operator is built on top of PowerShell jobs so it shares a lot of functionality with <code>Start-Job</code>. The following command contains basic usage of the ampersand background operator.</p>\n\n<pre><code>Get-Process -Name pwsh &\n</code></pre>\n \n <p>This is functionally equivalent to the following usage of <code>Start-Job</code>.</p>\n \n <p><code>Start-Job -ScriptBlock {Get-Process -Name pwsh}</code></p>\n \n <p>Since it's functionally equivalent to using <code>Start-Job</code>, the ampersand background operator returns a <code>Job</code> object just like <code>Start-Job does</code>. This means that you are able to use <code>Receive-Job</code> and <code>Remove-Job</code> just as you would if you had used <code>Start-Job</code> to start the job.</p>\n\n<pre><code>$job = Get-Process -Name pwsh &\nReceive-Job $job\n</code></pre>\n \n <p>Output</p>\n\n<pre><code>NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName\n------ ----- ----- ------ -- -- -----------\n 0 0.00 221.16 25.90 6988 988 pwsh\n 0 0.00 140.12 29.87 14845 845 pwsh\n 0 0.00 85.51 0.91 19639 988 pwsh\n\n\n$job = Get-Process -Name pwsh &\nRemove-Job $job\n</code></pre>\n \n <p>For more information on PowerShell jobs, see <a href=\"https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_jobs?view=powershell-6\" rel=\"noreferrer\">about_Jobs</a>.</p>\n</blockquote>\n"
},
{
"answer_id": 56963061,
"author": "js2010",
"author_id": 6654942,
"author_profile": "https://Stackoverflow.com/users/6654942",
"pm_score": 3,
"selected": false,
"text": "<p>You can do something like this. </p>\n\n<pre><code>$a = start-process -NoNewWindow powershell {timeout 10; 'done'} -PassThru\n</code></pre>\n\n<p>And if you want to wait for it:</p>\n\n<pre><code>$a | wait-process\n</code></pre>\n\n<p>Bonus osx or linux version:</p>\n\n<pre><code>$a = start-process pwsh '-c',{start-sleep 5; 'done'} -PassThru \n</code></pre>\n\n<p>Example pinger script I have. The args are passed as an array:</p>\n\n<pre><code>$1 = start -n powershell pinger,comp001 -pa\n</code></pre>\n"
},
{
"answer_id": 57808376,
"author": "bence of outer space",
"author_id": 2667819,
"author_profile": "https://Stackoverflow.com/users/2667819",
"pm_score": 3,
"selected": false,
"text": "<p>tl;dr</p>\n\n<pre><code>Start-Process powershell { sleep 30 }\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5769/"
] |
In bash the ampersand (&) can be used to run a command in the background and return interactive control to the user before the command has finished running. Is there an equivalent method of doing this in Powershell?
Example of usage in bash:
```
sleep 30 &
```
|
As long as the command is an executable or a file that has an associated executable, use **Start-Process** (available from v2):
```
Start-Process -NoNewWindow ping google.com
```
You can also add this as a function in your profile:
```
function bg() {Start-Process -NoNewWindow @args}
```
and then the invocation becomes:
```
bg ping google.com
```
In my opinion, Start-Job is an overkill for the simple use case of running a process in the background:
1. Start-Job does not have access to your existing scope (because it runs in a separate session). You cannot do "Start-Job {notepad $myfile}"
2. Start-Job does not preserve the current directory (because it runs in a separate session). You cannot do "Start-Job {notepad myfile.txt}" where myfile.txt is in the current directory.
3. The output is not displayed automatically. You need to run Receive-Job with the ID of the job as parameter.
NOTE: Regarding your initial example, "bg sleep 30" would not work because sleep is a Powershell commandlet. Start-Process only works when you actually fork a process.
|
185,591 |
<p>What is this error? </p>
<pre><code>cannot find symbol, symbol: method getstring(java.lang.String)
Location: class InternalFrameDemo
if <!windowTitleField.getText().equals(getstring("InternalFrameDemo.frame_label")))
</code></pre>
|
[
{
"answer_id": 185596,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 2,
"selected": false,
"text": "<p>it means that the class InternalFrameDemo has no getstring() method - shouldn't that be \"getString\" with an uppercase \"S\"?</p>\n"
},
{
"answer_id": 185601,
"author": "Eric Tuttleman",
"author_id": 25677,
"author_profile": "https://Stackoverflow.com/users/25677",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe it's saying that there isn't a method in InteranlFrameDemo called getstring that takes a String argument. Possibly is the method supposed to be getString(\"mystring\")?</p>\n\n<p>method names are case-sensitive in java, which is why I'm guessing this</p>\n"
},
{
"answer_id": 185602,
"author": "abarax",
"author_id": 24390,
"author_profile": "https://Stackoverflow.com/users/24390",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps getstring() should be getString()?</p>\n\n<p>Basically it is saying InternalFrameDemo has no getstring() method.</p>\n"
},
{
"answer_id": 185605,
"author": "Cristian Sanchez",
"author_id": 3659,
"author_profile": "https://Stackoverflow.com/users/3659",
"pm_score": 4,
"selected": false,
"text": "<p>Java is case-sensitive. Because \"getstring\" is not equal to \"getString\", the compiler thinks the \"getstring\" method does not exist in the InternalFrameDemo class and throws back that error.</p>\n\n<p>In Java, methods will generally have the first letter of each word after the first word capitalized (e.g. toString(), toUpperCase(), etc.), classes will use Upper <a href=\"http://en.wikipedia.org/wiki/CamelCase\" rel=\"nofollow noreferrer\">Camel Case</a> (e.g. ClassName, String, StringBuilder) and constants will be in all caps (e.g. MAX_VALUE)</p>\n"
},
{
"answer_id": 185615,
"author": "Glitch",
"author_id": 324306,
"author_profile": "https://Stackoverflow.com/users/324306",
"pm_score": 0,
"selected": false,
"text": "<p>It's just because Java is case sensitive. Try getString() instead of getstring(). Java generally uses Camel notation.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
What is this error?
```
cannot find symbol, symbol: method getstring(java.lang.String)
Location: class InternalFrameDemo
if <!windowTitleField.getText().equals(getstring("InternalFrameDemo.frame_label")))
```
|
Java is case-sensitive. Because "getstring" is not equal to "getString", the compiler thinks the "getstring" method does not exist in the InternalFrameDemo class and throws back that error.
In Java, methods will generally have the first letter of each word after the first word capitalized (e.g. toString(), toUpperCase(), etc.), classes will use Upper [Camel Case](http://en.wikipedia.org/wiki/CamelCase) (e.g. ClassName, String, StringBuilder) and constants will be in all caps (e.g. MAX\_VALUE)
|
185,594 |
<p>What data structure does the following declaration specify?</p>
<pre><code> List<ArrayList>[] myArray;
</code></pre>
<p>I think it should declare an array where each element is a <code>List</code> (e.g., a <code>LinkedList</code> or an <code>ArrayList</code>) and require that each <code>List</code> contain <code>ArrayList</code> objects.</p>
<p>My reasoning:</p>
<pre><code> List<String> someList; // A List of String objects
List<ArrayList> someList; // A List of ArrayList objects
List<ArrayList>[] someListArray; // An array of List of ArrayList objects
</code></pre>
<p>After running some tests, I determined that it accepts an array where each element is an <code>LinkedList</code> object and does not specify what the LinkedList objects contain.</p>
<p>So <code>List<ArrayList></code> specifies what the <code>List</code> must contain, but <code>List<ArrayList>[]</code> specifies how the <code>List</code> must be implemented.</p>
<p>Am I missing something?</p>
<p>Here are my tests.</p>
<pre><code>import java.util.ArrayList;
import java.util.List;
import java.util.LinkedList;
public class Generics1 {
public static void main(String[] args) {
List<ArrayList>[] someListArray;
someListArray = getArrayWhereEachElementIsAnArrayListObject();
// Why does this satisfy the declaration?
//someListArray[0] => ArrayList object holding Strings
someListArray= getArrayWhereEachElementIsAListOfArrayListObjects();
//someListArray[0] => ArrayList object holding ArrayList objects
}
public static List[] getArrayWhereEachElementIsAnArrayListObject() {
List[] arrayOfLists = new ArrayList[2];
arrayOfLists[0] = getStringList();
arrayOfLists[1] = getIntegerList();
return arrayOfLists;
}
public static List[] getArrayWhereEachElementIsAListOfArrayListObjects() {
List list1 = new ArrayList();
list1.add(getArrayList());
List list2 = new ArrayList();
list2.add(getArrayList());
List[] arrayOfListsOfArrayLists = new ArrayList[2];
arrayOfListsOfArrayLists[0] = list1;
arrayOfListsOfArrayLists[1] = list2;
return arrayOfListsOfArrayLists;
}
public static List getStringList() {
List stringList= new ArrayList();
stringList.add("one");
stringList.add("two");
return stringList;
}
public static List getIntegerList() {
List intList= new ArrayList();
intList.add(new Integer(1));
intList.add(new Integer(2));
return intList;
}
public static ArrayList getArrayList() {
ArrayList arrayList = new ArrayList() ;
return arrayList;
}
}
</code></pre>
|
[
{
"answer_id": 185619,
"author": "Mark",
"author_id": 26310,
"author_profile": "https://Stackoverflow.com/users/26310",
"pm_score": 3,
"selected": false,
"text": "<p>Mr Josh Bloch says: </p>\n\n<blockquote>\n <p>\"Prefer lists to array because arrays\n are covariant and generics are\n invariant'</p>\n</blockquote>\n\n<p>You could perhaps do:</p>\n\n<pre><code>List<List<ArrayList>> someListArray;\n</code></pre>\n\n<p>This may give some performance hit (not even noticable i bet) but you will get better type safety at compile time.</p>\n\n<p>but I think the question should be more around \"why\" you need this?</p>\n"
},
{
"answer_id": 185627,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 3,
"selected": false,
"text": "<pre><code>List<ArrayList>[] someListArray;\n</code></pre>\n\n<p>gives you an:</p>\n\n<pre><code>array of ( List of ArrayList )\n</code></pre>\n\n<p>But due to limitations in Java generics (bug <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6229728\" rel=\"nofollow noreferrer\">6229728</a>) you can only actually create:</p>\n\n<pre><code>array of List\n</code></pre>\n\n<p>and cast it:</p>\n\n<pre><code>List<ArrayList>[] someListArray = (List<ArrayList>[]) new List[5];\n</code></pre>\n"
},
{
"answer_id": 185633,
"author": "abarax",
"author_id": 24390,
"author_profile": "https://Stackoverflow.com/users/24390",
"pm_score": 0,
"selected": false,
"text": "<p>You are correct in saying: </p>\n\n<blockquote>\n <p>After running some tests, I determined the declaration means an array where each element is an ArrayList object.</p>\n</blockquote>\n\n<p>Executing this code</p>\n\n<pre><code>List<ArrayList>[] myArray = new ArrayList[2];\n\nmyArray[0] = new ArrayList<String>();\nmyArray[0].add(\"test 1\");\n\nmyArray[1] = new ArrayList<String>();\nmyArray[1].add(\"test 2\");\n\nprint myArray;\n</code></pre>\n\n<p>Produces this result:</p>\n\n<pre><code>{[\"test 1\"], [\"test 2\"]}\n</code></pre>\n\n<p>It seems to me there is no reason not to do this instead:</p>\n\n<pre><code>List<ArrayList> myArray = new ArrayList<ArrayList>();\n</code></pre>\n"
},
{
"answer_id": 185753,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 0,
"selected": false,
"text": "<p>List is a List capable of holding ArrayList objects\nList [] is an array of such Lists</p>\n\n<p>So, what you said is that An Array of (List of ArrayList object) is CORRECT.</p>\n\n<p>Can you share what your tests were. My own tests are different</p>\n\n<pre><code>import java.util.*;\n\npublic class TestList {\n public static void main(String ... args) {\n class MySpecialLinkedList extends LinkedList<ArrayList<Integer>> {\n MySpecialLinkedList() {\n\n }\n\n public void foo() {\n\n }\n\n\n public Object clone()\n {\n return super.clone();\n }\n }\n\n List<ArrayList<Integer>> [] someListArray = new MySpecialLinkedList[10];\n for (int i = 0; i < 10; ++i) {\n someListArray[i] = new LinkedList<ArrayList<Integer>>();\n for (int j = 0; j < 20; ++j) {\n someListArray[i].add(new ArrayList<Integer>());\n for (int k = 0; k < 30; ++k) {\n someListArray[i].get(j).add(j);\n }\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 185812,
"author": "user19685",
"author_id": 19685,
"author_profile": "https://Stackoverflow.com/users/19685",
"pm_score": 0,
"selected": false,
"text": "<p>After running some additional tests, I think I have my answer.</p>\n\n<p>List<ArrayList>[] does indeed specify an array where each element is a List of ArrayList objects.</p>\n\n<p>Compiling the code as shown below revealed why my first test allowed me to use an array where each element is a List of anything. Using return types of List[] and List in the methods that populate the arrays did not provide the compiler enough information to prohibit the assignments. But the compiler did issue warnings about the ambiguity.</p>\n\n<p>From the compiler's point of view, a method returning a List[] might be returning a List<ArrayList> (which satisfies the declaration) or it might not. Similarly, a method returning a List might or might not return an ArrayList.</p>\n\n<p>Here was the compiler output:</p>\n\n<p>javac Generics2.java -Xlint:unchecked</p>\n\n<pre>\nGenerics2.java:12: warning: [unchecked] unchecked conversion\nfound : java.util.List[]\nrequired: java.util.List<java.util.ArrayList>[]\n someListArray = getArrayWhereEachElementIsALinkedListObject();\n ^\nGenerics2.java:16: warning: [unchecked] unchecked conversion\nfound : java.util.List[]\nrequired: java.util.List<java.util.ArrayList>[]\n someListArray= getArrayWhereEachElementIsAListOfLinkedListObjects();\n</pre>\n\n<p>Here are my tests.</p>\n\n<pre>\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.LinkedList;\n\n\npublic class Generics2 {\n\n public static void main(String[] args) {\n\n List<ArrayList>[] someListArray;\n\n someListArray = getArrayWhereEachElementIsALinkedListObject();\n // Why does this satisfy the declaration?\n //someListArray[0] => LinkedList object holding Strings\n\n someListArray= getArrayWhereEachElementIsAListOfLinkedListObjects();\n //someListArray[0] => LinkedList object holding LinkedList objects\n\n }\n\n public static List[] getArrayWhereEachElementIsALinkedListObject() {\n List[] arrayOfLists = new LinkedList[2];\n arrayOfLists[0] = getStringLinkedListAsList();\n arrayOfLists[1] = getIntegerLinkedListAsList();\n return arrayOfLists;\n }\n\n public static List[] getArrayWhereEachElementIsAListOfLinkedListObjects() {\n\n List list1 = new LinkedList();\n list1.add(new LinkedList());\n\n List list2 = new LinkedList();\n list2.add(new LinkedList());\n\n List[] arrayOfListsOfLinkedLists = new LinkedList[2];\n arrayOfListsOfLinkedLists[0] = list1;\n arrayOfListsOfLinkedLists[1] = list2;\n return arrayOfListsOfLinkedLists;\n }\n\n public static List getStringLinkedListAsList() {\n List stringList= new LinkedList();\n stringList.add(\"one\");\n stringList.add(\"two\");\n return stringList;\n }\n\n\n public static List getIntegerLinkedListAsList() {\n List intList= new LinkedList();\n intList.add(new Integer(1));\n intList.add(new Integer(2));\n return intList;\n }\n\n}\n</pre>\n"
},
{
"answer_id": 187269,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 4,
"selected": false,
"text": "<p>The answer is that arrays can only hold reified types. And generified classes are not reified. That is, the runtime \"type\" of the List<ArrayList> is just List. Generics are erased at runtime (google \"wall of erasure\" for more). </p>\n\n<p>So this: </p>\n\n<pre><code>List<ArrayList>[] myArray\n</code></pre>\n\n<p>really means: </p>\n\n<pre><code>List[] myArray\n</code></pre>\n\n<p>There is no type-safe way to declare what you're trying to declare. Generally, I'd recommend you use a List instead of an array in this case. Some people have gone so far as to suggest that arrays should be treated as deprecated types now that we have generics. I can't say I'm willing to go that far but you should consider whether a collection is a better alternative whenever you're drawn to an array.</p>\n\n<p>The book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0596527756\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Java Generics and Collections</a> by Naftalin and Wadler is an excellent reference for questions you might have about generics. Or, of course, the <a href=\"http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html\" rel=\"noreferrer\">Generics FAQ</a> is your canonical online reference.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19685/"
] |
What data structure does the following declaration specify?
```
List<ArrayList>[] myArray;
```
I think it should declare an array where each element is a `List` (e.g., a `LinkedList` or an `ArrayList`) and require that each `List` contain `ArrayList` objects.
My reasoning:
```
List<String> someList; // A List of String objects
List<ArrayList> someList; // A List of ArrayList objects
List<ArrayList>[] someListArray; // An array of List of ArrayList objects
```
After running some tests, I determined that it accepts an array where each element is an `LinkedList` object and does not specify what the LinkedList objects contain.
So `List<ArrayList>` specifies what the `List` must contain, but `List<ArrayList>[]` specifies how the `List` must be implemented.
Am I missing something?
Here are my tests.
```
import java.util.ArrayList;
import java.util.List;
import java.util.LinkedList;
public class Generics1 {
public static void main(String[] args) {
List<ArrayList>[] someListArray;
someListArray = getArrayWhereEachElementIsAnArrayListObject();
// Why does this satisfy the declaration?
//someListArray[0] => ArrayList object holding Strings
someListArray= getArrayWhereEachElementIsAListOfArrayListObjects();
//someListArray[0] => ArrayList object holding ArrayList objects
}
public static List[] getArrayWhereEachElementIsAnArrayListObject() {
List[] arrayOfLists = new ArrayList[2];
arrayOfLists[0] = getStringList();
arrayOfLists[1] = getIntegerList();
return arrayOfLists;
}
public static List[] getArrayWhereEachElementIsAListOfArrayListObjects() {
List list1 = new ArrayList();
list1.add(getArrayList());
List list2 = new ArrayList();
list2.add(getArrayList());
List[] arrayOfListsOfArrayLists = new ArrayList[2];
arrayOfListsOfArrayLists[0] = list1;
arrayOfListsOfArrayLists[1] = list2;
return arrayOfListsOfArrayLists;
}
public static List getStringList() {
List stringList= new ArrayList();
stringList.add("one");
stringList.add("two");
return stringList;
}
public static List getIntegerList() {
List intList= new ArrayList();
intList.add(new Integer(1));
intList.add(new Integer(2));
return intList;
}
public static ArrayList getArrayList() {
ArrayList arrayList = new ArrayList() ;
return arrayList;
}
}
```
|
The answer is that arrays can only hold reified types. And generified classes are not reified. That is, the runtime "type" of the List<ArrayList> is just List. Generics are erased at runtime (google "wall of erasure" for more).
So this:
```
List<ArrayList>[] myArray
```
really means:
```
List[] myArray
```
There is no type-safe way to declare what you're trying to declare. Generally, I'd recommend you use a List instead of an array in this case. Some people have gone so far as to suggest that arrays should be treated as deprecated types now that we have generics. I can't say I'm willing to go that far but you should consider whether a collection is a better alternative whenever you're drawn to an array.
The book [Java Generics and Collections](https://rads.stackoverflow.com/amzn/click/com/0596527756) by Naftalin and Wadler is an excellent reference for questions you might have about generics. Or, of course, the [Generics FAQ](http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html) is your canonical online reference.
|
185,606 |
<p>I wonder if this would be doable ? To insert an array into one field in the database.</p>
<p>For instance I have a title, I want to have that title with only one id, but it's going to be bilingually used on the website.</p>
<p>It feels a bit unnecessary to make another table to have their global ids and then another table with the actual titles linked to the table with the global id.</p>
<p>I just want to have something like this</p>
<pre><code>ID TITLE
1 Array("english title", "nederlandse titel");
</code></pre>
<p>I'm using PHP/MSYQL, so if it would be doable could you please explain in these languages.</p>
<p>Oh yeah I figured that I could format it funky and use the split function to turn it into an array again. But I wonder if I could just store it as an array right away, I case the user might type something with the same formatting (one out of a million)</p>
|
[
{
"answer_id": 185616,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 3,
"selected": false,
"text": "<p>There's really only two reasonable choices here:</p>\n\n<p><strong>Join with another table</strong><br/>\npros: unlimited titles in unlimited languages<br/>\ncons: join overhead is more computationally expensive, SQL is marginally more complex to update/insert etc</p>\n\n<p><strong>Multiple columns</strong><br/>\neg: TITLE_EN, TITLE_NL, TITLE_DE<br/>\npros: fast to insert, select, etc<br/>\ncons: limited number of languages, adding more is an ALTER TABLE</p>\n\n<p>Given our two choices, you usually should should pick the first one. Unless you're dealing with just an obscene amount of transactions that cannot be parallelized, or you absosmurfly can ensure that you will never add languages, the extra flexibility in schema layout will save you headaches in the long run.</p>\n"
},
{
"answer_id": 185625,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 5,
"selected": true,
"text": "<p>it's doable:</p>\n\n<pre><code>$title = serialize($array);\n</code></pre>\n\n<p>and then to decode:</p>\n\n<pre><code>$title = unserialize($mysql_data);\n</code></pre>\n\n<p>but as mentioned it really lessens the benefits of a database in the first place. i'd definitely suggest looking into a multi-table or multi-column option instead, depending on the amount of languages you want to support and if that number will change in the future.</p>\n\n<p><strong>edit:</strong> a good point mentioned by <a href=\"https://stackoverflow.com/users/20265/dcousineau\">dcousineau</a> (see comments)</p>\n\n<blockquote>\n <p>Sometimes the serialized output, even after escaping, throws characters into the query that screws things up. You may want to wrap your serialize() in base64_encode() calls and then use base64_decode() before you unserialize.</p>\n</blockquote>\n\n<p>adjusted code for those situations:</p>\n\n<pre><code>$title = base64_encode(serialize($array) );\n$title = unserialize(base64_decode($mysql_data) );\n</code></pre>\n"
},
{
"answer_id": 185639,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": false,
"text": "<p>Arrays do violate normalization; in my experience with internationalization databases I've found that having a the phrases normalized is the best design,</p>\n\n<p>I allows you to easily make wholesale copies of rows - for instance 'es' to 'es-mx' or 'en' to 'en-US', 'en-GB', and my favorite: 'xx-piglatin'. In an array schema, you would either have to re-write every record or add complex parsing or use something more complex than arrays, like XML.</p>\n\n<p>It is relatively easy to use <code>LEFT JOIN</code>s for find untranslated phrases for work and also to use <code>COALESCE</code> to return a default so the program remains usable even if the phrase is not translated.</p>\n"
},
{
"answer_id": 188694,
"author": "sebthebert",
"author_id": 24820,
"author_profile": "https://Stackoverflow.com/users/24820",
"pm_score": 1,
"selected": false,
"text": "<p>Use a table with 3 columns !</p>\n\n<p>ID, TITLE_EN, TITLE_NL</p>\n\n<p>There is no good reason to serialize that, REALLY !</p>\n"
},
{
"answer_id": 69020698,
"author": "rémy",
"author_id": 419581,
"author_profile": "https://Stackoverflow.com/users/419581",
"pm_score": 0,
"selected": false,
"text": "<p>There is the JSON data-type, which will also store "arrays".</p>\n<p><a href=\"https://dev.mysql.com/doc/refman/8.0/en/json.html\" rel=\"nofollow noreferrer\">https://dev.mysql.com/doc/refman/8.0/en/json.html</a></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18671/"
] |
I wonder if this would be doable ? To insert an array into one field in the database.
For instance I have a title, I want to have that title with only one id, but it's going to be bilingually used on the website.
It feels a bit unnecessary to make another table to have their global ids and then another table with the actual titles linked to the table with the global id.
I just want to have something like this
```
ID TITLE
1 Array("english title", "nederlandse titel");
```
I'm using PHP/MSYQL, so if it would be doable could you please explain in these languages.
Oh yeah I figured that I could format it funky and use the split function to turn it into an array again. But I wonder if I could just store it as an array right away, I case the user might type something with the same formatting (one out of a million)
|
it's doable:
```
$title = serialize($array);
```
and then to decode:
```
$title = unserialize($mysql_data);
```
but as mentioned it really lessens the benefits of a database in the first place. i'd definitely suggest looking into a multi-table or multi-column option instead, depending on the amount of languages you want to support and if that number will change in the future.
**edit:** a good point mentioned by [dcousineau](https://stackoverflow.com/users/20265/dcousineau) (see comments)
>
> Sometimes the serialized output, even after escaping, throws characters into the query that screws things up. You may want to wrap your serialize() in base64\_encode() calls and then use base64\_decode() before you unserialize.
>
>
>
adjusted code for those situations:
```
$title = base64_encode(serialize($array) );
$title = unserialize(base64_decode($mysql_data) );
```
|
185,624 |
<p>I have a function that is declared and defined in a header file. This is a problem all by itself. When that function is not inlined, every translation unit that uses that header gets a copy of the function, and when they are linked together there are duplicated. I "fixed" that by making the function inline, but I'm afraid that this is a fragile solution because as far as I know, the compiler doesn't guarantee inlining, even when you specify the "inline" keyword. If this is not true, please correct me.</p>
<p>Anyways, the real question is, what happens to static variables inside this function? How many copies do I end up with?</p>
|
[
{
"answer_id": 185630,
"author": "Jason Etheridge",
"author_id": 2193,
"author_profile": "https://Stackoverflow.com/users/2193",
"pm_score": -1,
"selected": false,
"text": "<p>I believe you will end up with one per translation unit. You've effectively got many versions of that function (and its declared static variable), one for every translation unit that includes the header.</p>\n"
},
{
"answer_id": 185640,
"author": "Windows programmer",
"author_id": 23705,
"author_profile": "https://Stackoverflow.com/users/23705",
"pm_score": -1,
"selected": false,
"text": "<p>Inlining means that executable code (instructions) is inlined into the calling function's code. The compiler can choose to do that regardless of whether you've asked it to. That has no effect on the variables (data) declared in the function.</p>\n"
},
{
"answer_id": 185677,
"author": "Robert Gould",
"author_id": 15124,
"author_profile": "https://Stackoverflow.com/users/15124",
"pm_score": -1,
"selected": false,
"text": "<p>Besides any design issues this all may imply, since you're already stuck with it, you should use static in this case not inline. That way everyone shares the same variables. (Static function)</p>\n"
},
{
"answer_id": 185682,
"author": "Dirk Groeneveld",
"author_id": 13562,
"author_profile": "https://Stackoverflow.com/users/13562",
"pm_score": 2,
"selected": false,
"text": "<p>Since I wrote the question I tried it out with Visual Studio 2008. I tried to turn on all the options that make VS act in compliance with standards, but it's possible that I missed some. These are the results:</p>\n\n<p>When the function is merely \"inline\", there is only one copy of the static variable.</p>\n\n<p>When the function is \"static inline\", there are as many copies as there are translation units.</p>\n\n<p>The real question is now whether things are supposed to be this way, or if this is an ideosyncracy of the Microsoft C++ compiler.</p>\n"
},
{
"answer_id": 185723,
"author": "Raphaël Saint-Pierre",
"author_id": 22689,
"author_profile": "https://Stackoverflow.com/users/22689",
"pm_score": 3,
"selected": false,
"text": "<p>It is supposed to be this way.\n\"static\" tells the compiler you want the function to be local to the compilation unit, therefore you want one copy per compilation unit and one copy of the static variables per instance of the function.</p>\n\n<p>\"inline\" used to tell the compiler you want the function to be inlined; nowadays, it just takes it as \"it's ok if there are several copies of the code, just make sure it's the same function\". So everybody shares the static variables.</p>\n\n<p>Note: this answer was written in response to the answer the original poster posted to himself.</p>\n"
},
{
"answer_id": 185730,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 5,
"selected": false,
"text": "<p>I believe the compiler creates many copies of the variable, but the linker picks one and makes all the others reference it. I had similar results when I tried an experiment to create different versions of an inline function; if the function wasn't actually inlined (debug mode), all calls went to the same function regardless of the source file they were called from.</p>\n\n<p>Think like a compiler for a moment - how could it be otherwise? Each compilation unit (source file) is independent of the others, and can be compiled separately; each one must therefore create a copy of the variable, thinking it is the only one. The linker has the ability to reach across those boundaries and adjust the references for both variables and functions.</p>\n"
},
{
"answer_id": 189162,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 8,
"selected": true,
"text": "<p>I guess you're missing something, here.</p>\n\n<h2>static function?</h2>\n\n<p>Declaring a function static will make it \"hidden\" in its compilation unit.</p>\n\n<blockquote>\n <p>A name having namespace scope (3.3.6) has internal linkage if it is the name of</p>\n \n <p>— a variable, function or function template that is explicitly declared static;</p>\n \n <p>3.5/3 - C++14 (n3797)</p>\n \n <p>When a name has internal linkage , the entity it denotes can be referred to by names from other scopes in the same translation unit.</p>\n \n <p>3.5/2 - C++14 (n3797)</p>\n</blockquote>\n\n<p>If you declare this static function in a header, then all the compilation units including this header will have their own copy of the function.</p>\n\n<p>The thing is, if there are static variables inside that function, each compilation unit including this header will also have their own, personal version.</p>\n\n<h2>inline function?</h2>\n\n<p>Declaring it inline makes it a candidate for inlining (it does not mean a lot nowadays in C++, as the compiler will inline or not, sometimes ignoring the fact the keyword inline is present or absent):</p>\n\n<blockquote>\n <p>A function declaration (8.3.5, 9.3, 11.3) with an inline specifier declares an inline function. The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules for inline functions defined by 7.1.2 shall still be respected.</p>\n \n <p>7.1.2/2 - C++14 (n3797)</p>\n</blockquote>\n\n<p>In a header, its has an interesting side effect: The inlined function can be defined multiple times in the same module, and the linker will simply join \"them\" into one (if they were not inlined for compiler's reason).</p>\n\n<p>For static variables declared inside, the standard specifically says there one, and only one of them:</p>\n\n<blockquote>\n <p>A static local variable in an extern inline function always refers to the same object.</p>\n \n <p>7.1.2/4 - C++98/C++14 (n3797)</p>\n</blockquote>\n\n<p>(functions are by default extern, so, unless you specifically mark your function as static, this applies to that function)</p>\n\n<p>This has the advantage of \"static\" (i.e. it can be defined in a header) without its flaws (it exists at most once if it is not inlined)</p>\n\n<h2>static local variable?</h2>\n\n<p>Static local variables have no linkage (they can't be referred to by name outside their scope), but has static storage duration (i.e. it is global, but its construction and destruction obey to specific rules).</p>\n\n<h2>static + inline?</h2>\n\n<p>Mixing inline and static will then have the consequences you described (even if the function is inlined, the static variable inside won't be, and you'll end with as much static variables as you have compilation units including the definition of your static functions).</p>\n\n<h2>Answer to author's additional question</h2>\n\n<blockquote>\n <p>Since I wrote the question I tried it out with Visual Studio 2008. I tried to turn on all the options that make VS act in compliance with standards, but it's possible that I missed some. These are the results:</p>\n \n <p>When the function is merely \"inline\", there is only one copy of the static variable.</p>\n \n <p>When the function is \"static inline\", there are as many copies as there are translation units.</p>\n \n <p>The real question is now whether things are supposed to be this way, or if this is an idiosyncrasy of the Microsoft C++ compiler.</p>\n</blockquote>\n\n<p>So I suppose you have something like that:</p>\n\n<pre><code>void doSomething()\n{\n static int value ;\n}\n</code></pre>\n\n<p>You must realise that the static variable inside the function, simply put, a global variable hidden to all but the function's scope, meaning that only the function it is declared inside can reach it.</p>\n\n<p>Inlining the function won't change anything:</p>\n\n<pre><code>inline void doSomething()\n{\n static int value ;\n}\n</code></pre>\n\n<p>There will be only one hidden global variable. The fact the compiler will try to inline the code won't change the fact there is only one global hidden variable.</p>\n\n<p>Now, if your function is declared static:</p>\n\n<pre><code>static void doSomething()\n{\n static int value ;\n}\n</code></pre>\n\n<p>Then it is \"private\" for each compilation unit, meaning that every CPP file including the header where the static function is declared will have its own private copy of the function, including its own private copy of global hidden variable, thus as much variables as there are compilation units including the header.</p>\n\n<p>Adding \"inline\" to a \"static\" function with a \"static\" variable inside:</p>\n\n<pre><code>inline static void doSomething()\n{\n static int value ;\n}\n</code></pre>\n\n<p>has the same result than not adding this \"inline\" keyword, as far as the static variable inside is concerned.</p>\n\n<p><b>So the behaviour of VC++ is correct, and you are mistaking the real meaning of \"inline\" and \"static\".</b></p>\n"
},
{
"answer_id": 1350268,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Static means one copy is distributed throughout the program , but inline means it requires the same code for several time in the same program , so it is not possible to make a variable static inside the inline function.</p>\n"
},
{
"answer_id": 1384400,
"author": "Matt",
"author_id": 169116,
"author_profile": "https://Stackoverflow.com/users/169116",
"pm_score": 4,
"selected": false,
"text": "<p>I found Mark Ransom's answer helpful - that the compiler creates many copies of the static variable, but the linker chooses one and enforces it across all translation units. </p>\n\n<p>Elsewhere I found this:</p>\n\n<p><strong>See [dcl.fct.spec]/4</strong></p>\n\n<blockquote>\n <p>[..] An inline function with external linkage shall have the same \n address in all translation units. A static local variable in an extern \n inline function always refers to the same object. A string literal in an \n extern inline function is the same object in different translation units. </p>\n</blockquote>\n\n<p>I don't have a copy of the standard to check, but it matches with my experience examining the assembly in VS Express 2008</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13562/"
] |
I have a function that is declared and defined in a header file. This is a problem all by itself. When that function is not inlined, every translation unit that uses that header gets a copy of the function, and when they are linked together there are duplicated. I "fixed" that by making the function inline, but I'm afraid that this is a fragile solution because as far as I know, the compiler doesn't guarantee inlining, even when you specify the "inline" keyword. If this is not true, please correct me.
Anyways, the real question is, what happens to static variables inside this function? How many copies do I end up with?
|
I guess you're missing something, here.
static function?
----------------
Declaring a function static will make it "hidden" in its compilation unit.
>
> A name having namespace scope (3.3.6) has internal linkage if it is the name of
>
>
> — a variable, function or function template that is explicitly declared static;
>
>
> 3.5/3 - C++14 (n3797)
>
>
> When a name has internal linkage , the entity it denotes can be referred to by names from other scopes in the same translation unit.
>
>
> 3.5/2 - C++14 (n3797)
>
>
>
If you declare this static function in a header, then all the compilation units including this header will have their own copy of the function.
The thing is, if there are static variables inside that function, each compilation unit including this header will also have their own, personal version.
inline function?
----------------
Declaring it inline makes it a candidate for inlining (it does not mean a lot nowadays in C++, as the compiler will inline or not, sometimes ignoring the fact the keyword inline is present or absent):
>
> A function declaration (8.3.5, 9.3, 11.3) with an inline specifier declares an inline function. The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules for inline functions defined by 7.1.2 shall still be respected.
>
>
> 7.1.2/2 - C++14 (n3797)
>
>
>
In a header, its has an interesting side effect: The inlined function can be defined multiple times in the same module, and the linker will simply join "them" into one (if they were not inlined for compiler's reason).
For static variables declared inside, the standard specifically says there one, and only one of them:
>
> A static local variable in an extern inline function always refers to the same object.
>
>
> 7.1.2/4 - C++98/C++14 (n3797)
>
>
>
(functions are by default extern, so, unless you specifically mark your function as static, this applies to that function)
This has the advantage of "static" (i.e. it can be defined in a header) without its flaws (it exists at most once if it is not inlined)
static local variable?
----------------------
Static local variables have no linkage (they can't be referred to by name outside their scope), but has static storage duration (i.e. it is global, but its construction and destruction obey to specific rules).
static + inline?
----------------
Mixing inline and static will then have the consequences you described (even if the function is inlined, the static variable inside won't be, and you'll end with as much static variables as you have compilation units including the definition of your static functions).
Answer to author's additional question
--------------------------------------
>
> Since I wrote the question I tried it out with Visual Studio 2008. I tried to turn on all the options that make VS act in compliance with standards, but it's possible that I missed some. These are the results:
>
>
> When the function is merely "inline", there is only one copy of the static variable.
>
>
> When the function is "static inline", there are as many copies as there are translation units.
>
>
> The real question is now whether things are supposed to be this way, or if this is an idiosyncrasy of the Microsoft C++ compiler.
>
>
>
So I suppose you have something like that:
```
void doSomething()
{
static int value ;
}
```
You must realise that the static variable inside the function, simply put, a global variable hidden to all but the function's scope, meaning that only the function it is declared inside can reach it.
Inlining the function won't change anything:
```
inline void doSomething()
{
static int value ;
}
```
There will be only one hidden global variable. The fact the compiler will try to inline the code won't change the fact there is only one global hidden variable.
Now, if your function is declared static:
```
static void doSomething()
{
static int value ;
}
```
Then it is "private" for each compilation unit, meaning that every CPP file including the header where the static function is declared will have its own private copy of the function, including its own private copy of global hidden variable, thus as much variables as there are compilation units including the header.
Adding "inline" to a "static" function with a "static" variable inside:
```
inline static void doSomething()
{
static int value ;
}
```
has the same result than not adding this "inline" keyword, as far as the static variable inside is concerned.
**So the behaviour of VC++ is correct, and you are mistaking the real meaning of "inline" and "static".**
|
185,648 |
<p>I have a ListBox with a bunch of images in it (done through a datatemplate). The images are created by setting the items source:</p>
<pre><code><Image x:Name="ItemImage" Source="{Binding ImageUrl}"/>
</code></pre>
<p>and then they are cleared by using the listbox's Items.Clear() method. New Images are added by using the Items.Add method of the listbox. </p>
<p>However, memory usage just starts moving up and up and up. It is the same 300 or so small images that are getting displayed, but the memory never seems to get freed. The App starts using about 40Megs, and quickly climbs up to 700Megs. How do I free up the memory that all these images are using?</p>
<p><strong>EDIT</strong>: One thing I forgot to mention, the images (which are about 4-5k each in size) are being loaded over the network. Is caching somehow responsible for this? Displaying 12 Images chews up about 10 Megs of memory, which is about 100X filesize.</p>
|
[
{
"answer_id": 185655,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 4,
"selected": true,
"text": "<p>Monitoring of the system health using statspack (9i) or AWR (10g+) would be the best method of identifying bottlenecks.</p>\n\n<p>In particular:</p>\n\n<ul>\n<li>lookout for redo waits. The redo log is critical in maintaining a high write rate</li>\n<li>Use bind variables</li>\n<li>Use bulk operations wherever possible.</li>\n<li>Watch for index contention where multiple processes insert records into a single table having an index on a sequence-derived column</li>\n</ul>\n"
},
{
"answer_id": 185658,
"author": "Nick Stinemates",
"author_id": 4960,
"author_profile": "https://Stackoverflow.com/users/4960",
"pm_score": 1,
"selected": false,
"text": "<p>I could not recommend the <a href=\"http://download.oracle.com/docs/cd/B19306_01/server.102/b14196/em_manage002.htm\" rel=\"nofollow noreferrer\">Oracle Enterprise Management Console</a> (built in to Oracle) enough. It will let you know exactly what you're doing wrong and <strong>how to fix it!</strong></p>\n\n<p>You may want to consider getting rid of any extra index's (indices?) you may have. This may have cause a slight overhead on start up, but adding data to an indexed table may slow it down considerably.</p>\n"
},
{
"answer_id": 187600,
"author": "Andrew not the Saint",
"author_id": 23670,
"author_profile": "https://Stackoverflow.com/users/23670",
"pm_score": 2,
"selected": false,
"text": "<p>Along with David's answer:</p>\n\n<ul>\n<li>Monitor row migration and row chaining activity and change table storage parameters if necessary</li>\n<li>Check your redo log file system: disable FS caching (i.e. use Direct I/O), disable last access time, change block size to 512B. Or even better, migrate to ASM.</li>\n<li>Read about index-organized tables and see if you can apply them anywhere.</li>\n<li>Verify that asynch I/O is used.</li>\n<li>For large SGA sizes, enable large pages and LOCK_SGA (platform specific)</li>\n<li>Experiment with different DBWR settings (e.g. <em>fast_start_mttr_target</em>, <em>dbwr_processes</em>)</li>\n<li>At the hardware level, make sure you got a decent RAID-10 controller with write-caching enabled! Get lots of 15K RPM hard drives.</li>\n</ul>\n\n<p>Last but not the least: <strong>define repeatable and realistic performance test cases before you do any modifications. There's a lot of hit and miss in this kind of tuning - for each test execution do only one change at a time.</strong></p>\n"
},
{
"answer_id": 189689,
"author": "Rob Williams",
"author_id": 26682,
"author_profile": "https://Stackoverflow.com/users/26682",
"pm_score": 0,
"selected": false,
"text": "<p>Depending on the characteristics of your application and your data, consider a bulk data load using an Oracle external table. Have the application write the data to a text file, then use an INSERT INTO your target table from a SELECT on the external table = very fast.</p>\n\n<p>There are some constraints, and it may not fit your circumstances, but it gives massive performance when you can use it.</p>\n\n<p>I used this for loading near-real-time text data files at the rate of 40,000 files per day, upto about 2 MB per file, into an 8 TB (yes, TeraBytes) Oracle 10g database instance.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] |
I have a ListBox with a bunch of images in it (done through a datatemplate). The images are created by setting the items source:
```
<Image x:Name="ItemImage" Source="{Binding ImageUrl}"/>
```
and then they are cleared by using the listbox's Items.Clear() method. New Images are added by using the Items.Add method of the listbox.
However, memory usage just starts moving up and up and up. It is the same 300 or so small images that are getting displayed, but the memory never seems to get freed. The App starts using about 40Megs, and quickly climbs up to 700Megs. How do I free up the memory that all these images are using?
**EDIT**: One thing I forgot to mention, the images (which are about 4-5k each in size) are being loaded over the network. Is caching somehow responsible for this? Displaying 12 Images chews up about 10 Megs of memory, which is about 100X filesize.
|
Monitoring of the system health using statspack (9i) or AWR (10g+) would be the best method of identifying bottlenecks.
In particular:
* lookout for redo waits. The redo log is critical in maintaining a high write rate
* Use bind variables
* Use bulk operations wherever possible.
* Watch for index contention where multiple processes insert records into a single table having an index on a sequence-derived column
|
185,652 |
<p>I have a UIImageView and the objective is to scale it down proportionally by giving it either a height or width. </p>
<pre><code>UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
//Add image view
[self.view addSubview:imageView];
//set contentMode to scale aspect to fit
imageView.contentMode = UIViewContentModeScaleAspectFit;
//change width of frame
CGRect frame = imageView.frame;
frame.size.width = 100;
imageView.frame = frame;
</code></pre>
<p>The image did get resized but the position is not at the top left. What is the best approach to scaling image/imageView and how do I correct the position?</p>
|
[
{
"answer_id": 185788,
"author": "user26359",
"author_id": 26359,
"author_profile": "https://Stackoverflow.com/users/26359",
"pm_score": 0,
"selected": false,
"text": "<p>I think you can do something like</p>\n\n<pre><code>image.center = [[imageView window] center];\n</code></pre>\n"
},
{
"answer_id": 185911,
"author": "Chris Lundie",
"author_id": 20685,
"author_profile": "https://Stackoverflow.com/users/20685",
"pm_score": 5,
"selected": false,
"text": "<p>You could try making the <code>imageView</code> size match the <code>image</code>. The following code is not tested.</p>\n\n<pre><code>CGSize kMaxImageViewSize = {.width = 100, .height = 100};\nCGSize imageSize = image.size;\nCGFloat aspectRatio = imageSize.width / imageSize.height;\nCGRect frame = imageView.frame;\nif (kMaxImageViewSize.width / aspectRatio <= kMaxImageViewSize.height) \n{\n frame.size.width = kMaxImageViewSize.width;\n frame.size.height = frame.size.width / aspectRatio;\n} \nelse \n{\n frame.size.height = kMaxImageViewSize.height;\n frame.size.width = frame.size.height * aspectRatio;\n}\nimageView.frame = frame;\n</code></pre>\n"
},
{
"answer_id": 193219,
"author": "kdbdallas",
"author_id": 26728,
"author_profile": "https://Stackoverflow.com/users/26728",
"pm_score": -1,
"selected": false,
"text": "<p>Here is how you can scale it easily.</p>\n\n<p>This works in 2.x with the Simulator and the iPhone.</p>\n\n<pre><code>UIImage *thumbnail = [originalImage _imageScaledToSize:CGSizeMake(40.0, 40.0) interpolationQuality:1];\n</code></pre>\n"
},
{
"answer_id": 537697,
"author": "Jane Sales",
"author_id": 63994,
"author_profile": "https://Stackoverflow.com/users/63994",
"pm_score": 6,
"selected": false,
"text": "<p>I just tried this, and UIImage does not support _imageScaledToSize.</p>\n\n<p>I ended up adding a method to UIImage using a category - a suggestion I found on the Apple Dev forums.</p>\n\n<p>In a project-wide .h -</p>\n\n<pre><code>@interface UIImage (Extras)\n- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;\n@end;\n</code></pre>\n\n<p>Implementation:</p>\n\n<pre><code>@implementation UIImage (Extras)\n\n- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {\n\n UIImage *sourceImage = self;\n UIImage *newImage = nil;\n\n CGSize imageSize = sourceImage.size;\n CGFloat width = imageSize.width;\n CGFloat height = imageSize.height;\n\n CGFloat targetWidth = targetSize.width;\n CGFloat targetHeight = targetSize.height;\n\n CGFloat scaleFactor = 0.0;\n CGFloat scaledWidth = targetWidth;\n CGFloat scaledHeight = targetHeight;\n\n CGPoint thumbnailPoint = CGPointMake(0.0,0.0);\n\n if (CGSizeEqualToSize(imageSize, targetSize) == NO) {\n\n CGFloat widthFactor = targetWidth / width;\n CGFloat heightFactor = targetHeight / height;\n\n if (widthFactor < heightFactor) \n scaleFactor = widthFactor;\n else\n scaleFactor = heightFactor;\n\n scaledWidth = width * scaleFactor;\n scaledHeight = height * scaleFactor;\n\n // center the image\n\n if (widthFactor < heightFactor) {\n thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; \n } else if (widthFactor > heightFactor) {\n thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;\n }\n }\n\n\n // this is actually the interesting part:\n\n UIGraphicsBeginImageContext(targetSize);\n\n CGRect thumbnailRect = CGRectZero;\n thumbnailRect.origin = thumbnailPoint;\n thumbnailRect.size.width = scaledWidth;\n thumbnailRect.size.height = scaledHeight;\n\n [sourceImage drawInRect:thumbnailRect];\n\n newImage = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n\n if(newImage == nil) NSLog(@\"could not scale image\");\n\n\n return newImage ;\n}\n\n@end;\n</code></pre>\n"
},
{
"answer_id": 2300540,
"author": "Ken Abrams",
"author_id": 277445,
"author_profile": "https://Stackoverflow.com/users/277445",
"pm_score": 9,
"selected": false,
"text": "<p>Fixed easily, once I found the documentation!</p>\n<pre><code> imageView.contentMode = .scaleAspectFit\n</code></pre>\n"
},
{
"answer_id": 6126467,
"author": "neoneye",
"author_id": 78336,
"author_profile": "https://Stackoverflow.com/users/78336",
"pm_score": 4,
"selected": false,
"text": "<p>one can resize an UIImage this way</p>\n\n<pre><code>image = [UIImage imageWithCGImage:[image CGImage] scale:2.0 orientation:UIImageOrientationUp];\n</code></pre>\n"
},
{
"answer_id": 6362277,
"author": "Nate Flink",
"author_id": 396429,
"author_profile": "https://Stackoverflow.com/users/396429",
"pm_score": 4,
"selected": false,
"text": "<pre><code>UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@\"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg\"]]];\nUIImageView *imageView = [[UIImageView alloc] initWithImage:image]; \n\n\n//set contentMode to scale aspect to fit\nimageView.contentMode = UIViewContentModeScaleAspectFit;\n\n//change width of frame\n//CGRect frame = imageView.frame;\n//frame.size.width = 100;\n//imageView.frame = frame;\n\n//original lines that deal with frame commented out, yo.\nimageView.frame = CGRectMake(10, 20, 60, 60);\n\n...\n\n//Add image view\n[myView addSubview:imageView]; \n</code></pre>\n\n<p>The original code posted at the top worked well for me in iOS 4.2. </p>\n\n<p>I found that creating a CGRect and specifying all the top, left, width, and height values was the easiest way to adjust the position in my case, which was using a UIImageView inside a table cell. (Still need to add code to release objects)</p>\n"
},
{
"answer_id": 13815388,
"author": "Li-chih Wu",
"author_id": 1716918,
"author_profile": "https://Stackoverflow.com/users/1716918",
"pm_score": 5,
"selected": false,
"text": "<pre><code>imageView.contentMode = UIViewContentModeScaleAspectFill;\nimageView.clipsToBounds = YES;\n</code></pre>\n"
},
{
"answer_id": 14220605,
"author": "Jacksonkr",
"author_id": 332578,
"author_profile": "https://Stackoverflow.com/users/332578",
"pm_score": 9,
"selected": false,
"text": "<p>I've seen a bit of conversation about scale types so I decided to put together an <a href=\"http://jacksonkr.com/content/uiimageview-scaling-explained-visually\" rel=\"noreferrer\">article regarding some of the most popular content mode scaling types</a>.</p>\n\n<p>The associated image is here:</p>\n\n<p><img src=\"https://i.stack.imgur.com/JHiqw.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 20101282,
"author": "Peter Kreinz",
"author_id": 3013992,
"author_profile": "https://Stackoverflow.com/users/3013992",
"pm_score": 3,
"selected": false,
"text": "<p>UIImageView+Scale.h:</p>\n\n<pre><code>#import <Foundation/Foundation.h>\n\n@interface UIImageView (Scale)\n\n-(void) scaleAspectFit:(CGFloat) scaleFactor;\n\n@end\n</code></pre>\n\n<p>UIImageView+Scale.m:</p>\n\n<pre><code>#import \"UIImageView+Scale.h\"\n\n@implementation UIImageView (Scale)\n\n\n-(void) scaleAspectFit:(CGFloat) scaleFactor{\n\n self.contentScaleFactor = scaleFactor;\n self.transform = CGAffineTransformMakeScale(scaleFactor, scaleFactor);\n\n CGRect newRect = self.frame;\n newRect.origin.x = 0;\n newRect.origin.y = 0;\n self.frame = newRect;\n}\n\n@end\n</code></pre>\n"
},
{
"answer_id": 29425814,
"author": "Jeffrey Neo",
"author_id": 1856717,
"author_profile": "https://Stackoverflow.com/users/1856717",
"pm_score": 4,
"selected": false,
"text": "<p>Set your ImageView by selecting Mode to <code>Aspect Fill</code> and check the <code>Clip Subviews</code> box.</p>\n\n<p><img src=\"https://i.stack.imgur.com/WjMz3.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 32626996,
"author": "Somir Saikia",
"author_id": 2181124,
"author_profile": "https://Stackoverflow.com/users/2181124",
"pm_score": 3,
"selected": false,
"text": "<p>For Swift :</p>\n\n<pre><code>self.imageViews.contentMode = UIViewContentMode.ScaleToFill\n</code></pre>\n"
},
{
"answer_id": 35621618,
"author": "Avijit Nagare",
"author_id": 4767429,
"author_profile": "https://Stackoverflow.com/users/4767429",
"pm_score": 2,
"selected": false,
"text": "<p>I used following code.where imageCoverView is UIView holds UIImageView</p>\n\n<pre><code>if (image.size.height<self.imageCoverView.bounds.size.height && image.size.width<self.imageCoverView.bounds.size.width)\n{\n [self.profileImageView sizeToFit];\n self.profileImageView.contentMode =UIViewContentModeCenter\n}\nelse\n{\n self.profileImageView.contentMode =UIViewContentModeScaleAspectFit;\n}\n</code></pre>\n"
},
{
"answer_id": 35621788,
"author": "Alessandro Ornano",
"author_id": 1894067,
"author_profile": "https://Stackoverflow.com/users/1894067",
"pm_score": 1,
"selected": false,
"text": "<p>Usually I use this method for my apps (<strong>Swift 2.x</strong> compatible):</p>\n\n<pre><code>// Resize UIImage\nfunc resizeImage(image:UIImage, scaleX:CGFloat,scaleY:CGFloat) ->UIImage {\n let size = CGSizeApplyAffineTransform(image.size, CGAffineTransformMakeScale(scaleX, scaleY))\n let hasAlpha = true\n let scale: CGFloat = 0.0 // Automatically use scale factor of main screen\n\n UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)\n image.drawInRect(CGRect(origin: CGPointZero, size: size))\n\n let scaledImage = UIGraphicsGetImageFromCurrentImageContext()\n UIGraphicsEndImageContext()\n return scaledImage\n}\n</code></pre>\n"
},
{
"answer_id": 39921707,
"author": "vvamondes",
"author_id": 1662751,
"author_profile": "https://Stackoverflow.com/users/1662751",
"pm_score": 4,
"selected": false,
"text": "<p>This works fine for me Swift 2.x:</p>\n\n<pre><code>imageView.contentMode = .ScaleAspectFill\nimageView.clipsToBounds = true;\n</code></pre>\n"
},
{
"answer_id": 41181245,
"author": "P.J.Radadiya",
"author_id": 5722289,
"author_profile": "https://Stackoverflow.com/users/5722289",
"pm_score": 4,
"selected": false,
"text": "<p>Set your <code>UIimageview</code> by scale.........</p>\n\n<p><a href=\"https://i.stack.imgur.com/JEhNI.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/JEhNI.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 41475740,
"author": "Lane Rettig",
"author_id": 2397068,
"author_profile": "https://Stackoverflow.com/users/2397068",
"pm_score": 2,
"selected": false,
"text": "<p>If the solutions proposed here aren't working for you, and your image asset is actually a PDF, note that XCode actually treats PDFs differently than image files. In particular, it doesn't seem able to scale to fill properly with a PDF: it ends up tiled instead. This drove me crazy until I figured out that the issue was the PDF format. Convert to JPG and you should be good to go.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987/"
] |
I have a UIImageView and the objective is to scale it down proportionally by giving it either a height or width.
```
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
//Add image view
[self.view addSubview:imageView];
//set contentMode to scale aspect to fit
imageView.contentMode = UIViewContentModeScaleAspectFit;
//change width of frame
CGRect frame = imageView.frame;
frame.size.width = 100;
imageView.frame = frame;
```
The image did get resized but the position is not at the top left. What is the best approach to scaling image/imageView and how do I correct the position?
|
Fixed easily, once I found the documentation!
```
imageView.contentMode = .scaleAspectFit
```
|
185,661 |
<p>I'd like to know if Flash/AS3 has any nice way to convert an AS3 'Date' object to/from rfc-850 timestamp format (as used by HTTP date and last-modified).</p>
<p>This question is very similar to <a href="https://stackoverflow.com/questions/17017/how-do-i-parse-and-convert-datetimes-to-the-rfc-3339-date-time-format">this question about rfc 3339</a>, except it's specific to AS3 and rfc-850.</p>
<p>RFC-850 is like: <code>Thu, 09 Oct 2008 01:09:43 GMT</code></p>
|
[
{
"answer_id": 185858,
"author": "Raleigh Buckner",
"author_id": 1153,
"author_profile": "https://Stackoverflow.com/users/1153",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://as3corelib.googlecode.com\" rel=\"nofollow noreferrer\">as3corelib</a> libraries have DateUtil.toRFC822() and DateUtil.parseRFC822() methods (among others). Don't know if these are exactly what you are looking for. </p>\n\n<p>The specific docs for the DateUtil class is here: <a href=\"http://as3corelib.googlecode.com/svn/trunk/docs/com/adobe/utils/DateUtil.html\" rel=\"nofollow noreferrer\">http://as3corelib.googlecode.com/svn/trunk/docs/com/adobe/utils/DateUtil.html</a></p>\n"
},
{
"answer_id": 186080,
"author": "aaaidan",
"author_id": 26331,
"author_profile": "https://Stackoverflow.com/users/26331",
"pm_score": 3,
"selected": true,
"text": "<p>Alright, so here's a couple of functions to do RFC-802/<code>Date</code> conversion in Flash.</p>\n\n<p>I learned that the <code>Date</code> object doesn't really have any notion of a timezone, and assumes that it is in the local timezone. If you pass an RFC-802 date to the <code>Date()</code> constructor, it parses it everything except the \"GMT\" timezone token at the end, resulting in the correct time but possibly in the wrong timezone. </p>\n\n<p>Subtracting the current timezone from the parsed Date compensates for this, so a timestamp can do a round-trip with these functions without becoming completely wrong.</p>\n\n<p>(Wouldn't it have been <em>great</em> if <em>somebody</em> had included a <code>timezone</code> property when they were designing the <code>Date</code> class?)</p>\n\n<pre><code>/**\n * Converts an RFC string to a Date object.\n */\nfunction fromRFC802(date:String):Date {\n // Passing in an RFC802 date to the Date constructor causes flash\n // to conveniently ignore the \"GMT\" timezone at the end, and assumes\n // that it's in the Local timezone.\n // If we additionally convert it back to GMT, then we're sweet.\n\n var outputDate:Date = new Date(date);\n outputDate = new Date(outputDate.time - outputDate.getTimezoneOffset()*1000*60);\n return outputDate;\n}\n\n/** \n * Converts a Date object to an RFC802-formatted string (GMT/UTC).\n */\nfunction toRFC802 (date:Date):String {\n // example: Thu, 09 Oct 2008 01:09:43 GMT\n\n // Convert to GMT\n\n var output:String = \"\";\n\n // Day\n switch (date.dayUTC) {\n case 0: output += \"Sun\"; break;\n case 1: output += \"Mon\"; break;\n case 2: output += \"Tue\"; break;\n case 3: output += \"Wed\"; break;\n case 4: output += \"Thu\"; break;\n case 5: output += \"Fri\"; break;\n case 6: output += \"Sat\"; break;\n }\n\n output += \", \";\n\n // Date\n if (date.dateUTC < 10) {\n output += \"0\"; // leading zero\n }\n output += date.dateUTC + \" \";\n\n // Month\n switch(date.month) {\n case 0: output += \"Jan\"; break;\n case 1: output += \"Feb\"; break;\n case 2: output += \"Mar\"; break;\n case 3: output += \"Apr\"; break;\n case 4: output += \"May\"; break;\n case 5: output += \"Jun\"; break;\n case 6: output += \"Jul\"; break;\n case 7: output += \"Aug\"; break;\n case 8: output += \"Sep\"; break;\n case 9: output += \"Oct\"; break;\n case 10: output += \"Nov\"; break;\n case 11: output += \"Dec\"; break;\n }\n\n output += \" \";\n\n // Year\n output += date.fullYearUTC + \" \";\n\n // Hours\n if (date.hoursUTC < 10) {\n output += \"0\"; // leading zero\n }\n output += date.hoursUTC + \":\";\n\n // Minutes\n if (date.minutesUTC < 10) {\n output += \"0\"; // leading zero\n }\n output += date.minutesUTC + \":\";\n\n // Seconds\n if (date.seconds < 10) {\n output += \"0\"; // leading zero\n }\n output += date.secondsUTC + \" GMT\";\n\n return output;\n}\n\nvar dateString:String = \"Thu, 09 Oct 2008 01:09:43 GMT\";\n\ntrace(\"Round trip proof:\");\n\ntrace(\" RFC-802: \" + dateString);\ntrace(\"Date obj: \" + fromRFC802(dateString));\ntrace(\" RFC-802: \" + toRFC802(fromRFC802(dateString)));\ntrace(\"Date obj: \" + fromRFC802(toRFC802(fromRFC802(dateString))));\ntrace(\" RFC-802: \" + toRFC802(fromRFC802(toRFC802(fromRFC802(dateString)))));\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26331/"
] |
I'd like to know if Flash/AS3 has any nice way to convert an AS3 'Date' object to/from rfc-850 timestamp format (as used by HTTP date and last-modified).
This question is very similar to [this question about rfc 3339](https://stackoverflow.com/questions/17017/how-do-i-parse-and-convert-datetimes-to-the-rfc-3339-date-time-format), except it's specific to AS3 and rfc-850.
RFC-850 is like: `Thu, 09 Oct 2008 01:09:43 GMT`
|
Alright, so here's a couple of functions to do RFC-802/`Date` conversion in Flash.
I learned that the `Date` object doesn't really have any notion of a timezone, and assumes that it is in the local timezone. If you pass an RFC-802 date to the `Date()` constructor, it parses it everything except the "GMT" timezone token at the end, resulting in the correct time but possibly in the wrong timezone.
Subtracting the current timezone from the parsed Date compensates for this, so a timestamp can do a round-trip with these functions without becoming completely wrong.
(Wouldn't it have been *great* if *somebody* had included a `timezone` property when they were designing the `Date` class?)
```
/**
* Converts an RFC string to a Date object.
*/
function fromRFC802(date:String):Date {
// Passing in an RFC802 date to the Date constructor causes flash
// to conveniently ignore the "GMT" timezone at the end, and assumes
// that it's in the Local timezone.
// If we additionally convert it back to GMT, then we're sweet.
var outputDate:Date = new Date(date);
outputDate = new Date(outputDate.time - outputDate.getTimezoneOffset()*1000*60);
return outputDate;
}
/**
* Converts a Date object to an RFC802-formatted string (GMT/UTC).
*/
function toRFC802 (date:Date):String {
// example: Thu, 09 Oct 2008 01:09:43 GMT
// Convert to GMT
var output:String = "";
// Day
switch (date.dayUTC) {
case 0: output += "Sun"; break;
case 1: output += "Mon"; break;
case 2: output += "Tue"; break;
case 3: output += "Wed"; break;
case 4: output += "Thu"; break;
case 5: output += "Fri"; break;
case 6: output += "Sat"; break;
}
output += ", ";
// Date
if (date.dateUTC < 10) {
output += "0"; // leading zero
}
output += date.dateUTC + " ";
// Month
switch(date.month) {
case 0: output += "Jan"; break;
case 1: output += "Feb"; break;
case 2: output += "Mar"; break;
case 3: output += "Apr"; break;
case 4: output += "May"; break;
case 5: output += "Jun"; break;
case 6: output += "Jul"; break;
case 7: output += "Aug"; break;
case 8: output += "Sep"; break;
case 9: output += "Oct"; break;
case 10: output += "Nov"; break;
case 11: output += "Dec"; break;
}
output += " ";
// Year
output += date.fullYearUTC + " ";
// Hours
if (date.hoursUTC < 10) {
output += "0"; // leading zero
}
output += date.hoursUTC + ":";
// Minutes
if (date.minutesUTC < 10) {
output += "0"; // leading zero
}
output += date.minutesUTC + ":";
// Seconds
if (date.seconds < 10) {
output += "0"; // leading zero
}
output += date.secondsUTC + " GMT";
return output;
}
var dateString:String = "Thu, 09 Oct 2008 01:09:43 GMT";
trace("Round trip proof:");
trace(" RFC-802: " + dateString);
trace("Date obj: " + fromRFC802(dateString));
trace(" RFC-802: " + toRFC802(fromRFC802(dateString)));
trace("Date obj: " + fromRFC802(toRFC802(fromRFC802(dateString))));
trace(" RFC-802: " + toRFC802(fromRFC802(toRFC802(fromRFC802(dateString)))));
```
|
185,664 |
<p>I'm trying to create a user control that allows users to make something like the following:</p>
<pre><code> <uc1:MyControl id="controlThing" runat="server">
<uc1:BoundColumn id="column1" Column="Name" runat="server" />
<uc1:CheckBoxBoundColumn id="column2" Column="Selector" runat="server" />
<uc1:BoundColumn id="column3" Column="Description" runat="server" />
...etc
</uc1:MyControl>
</code></pre>
<p>There are only certain controls I would allow, in addition to the fact that you can have many of any type. I can picture this in XSD, but I'm not entirely sure for ASP.NET.</p>
<p>My ASP.NET voodoo is drawing a blank right now.. any thoughts?</p>
|
[
{
"answer_id": 185672,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 0,
"selected": false,
"text": "<p>Is it possible for you to override an existing control such as a ListView or GridView? That's your simplest option.</p>\n\n<p>But to create your own custom templated control you need to use ITemplate.</p>\n\n<p>I haven't done one but a quick google returned this: <a href=\"http://www.developerfusion.com/article/4410/in-depth-aspnet-using-adonet/2/\" rel=\"nofollow noreferrer\">http://www.developerfusion.com/article/4410/in-depth-aspnet-using-adonet/2/</a> it looked good.</p>\n\n<p>I have a book \"Developing Microsoft ASP.NET Server Controls and Components\" which covers it but I haven't read through it indepth yet (<a href=\"https://rads.stackoverflow.com/amzn/click/com/0735615829\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">http://www.amazon.com/exec/obidos/ASIN/0735615829/nikhilkothari-20</a>)</p>\n"
},
{
"answer_id": 185687,
"author": "nyxtom",
"author_id": 19753,
"author_profile": "https://Stackoverflow.com/users/19753",
"pm_score": 0,
"selected": false,
"text": "<p>I suppose the most difficult part I'm concerned with is being able to template any number of a given set of user controls inside my user control.</p>\n\n<pre><code><mycontrol id=\"control1\" runat=\"server\">\n <templateitem id=\"bleh1\" runat=\"server\" />\n <templateitem id=\"bleh2\" runat=\"server\" />\n <templateitem id=\"bleh3\" runat=\"server\" />\n ..etc\n</mycontrol>\n</code></pre>\n"
},
{
"answer_id": 185869,
"author": "sontek",
"author_id": 17176,
"author_profile": "https://Stackoverflow.com/users/17176",
"pm_score": 3,
"selected": true,
"text": "<p>The PersistenceMode.InnerProperty is what you want.. Here are the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.persistencemode.aspx\" rel=\"nofollow noreferrer\">MSDN docs.</a> Doing something like this will get you what you want:</p>\n\n<pre><code>[PersistenceMode(PersistenceMode.InnerProperty)]\npublic ListItem Items {\n get; set;\n}\n</code></pre>\n\n<p>and then you'll be able to use it like this:</p>\n\n<pre><code><cc1:MyControl runat=\"server\">\n <Items>\n <asp:ListItem Text=\"foo\" />\n </Items>\n</cc1:MyControl>\n</code></pre>\n\n<p>You can create your own custom classes to use in there as well.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19753/"
] |
I'm trying to create a user control that allows users to make something like the following:
```
<uc1:MyControl id="controlThing" runat="server">
<uc1:BoundColumn id="column1" Column="Name" runat="server" />
<uc1:CheckBoxBoundColumn id="column2" Column="Selector" runat="server" />
<uc1:BoundColumn id="column3" Column="Description" runat="server" />
...etc
</uc1:MyControl>
```
There are only certain controls I would allow, in addition to the fact that you can have many of any type. I can picture this in XSD, but I'm not entirely sure for ASP.NET.
My ASP.NET voodoo is drawing a blank right now.. any thoughts?
|
The PersistenceMode.InnerProperty is what you want.. Here are the [MSDN docs.](http://msdn.microsoft.com/en-us/library/system.web.ui.persistencemode.aspx) Doing something like this will get you what you want:
```
[PersistenceMode(PersistenceMode.InnerProperty)]
public ListItem Items {
get; set;
}
```
and then you'll be able to use it like this:
```
<cc1:MyControl runat="server">
<Items>
<asp:ListItem Text="foo" />
</Items>
</cc1:MyControl>
```
You can create your own custom classes to use in there as well.
|
185,680 |
<p>How do I define nested class in Java Script. </p>
<p>Here is the code snippet I have:</p>
<pre><code>objA = new TestA();
function TestB ()
{
this.testPrint = function ()
{
print ( " Inside testPrint " );
}
}
function TestA ()
{
var myObjB = new TestB();
}
</code></pre>
<p>Now I am trying to access testPrint using objA</p>
<pre><code>objA.myObjB.testPrint();
</code></pre>
<p>But its giving error "objA has no properties"</p>
<p>How can I access testB method using objA handler?</p>
|
[
{
"answer_id": 185684,
"author": "Leo",
"author_id": 20689,
"author_profile": "https://Stackoverflow.com/users/20689",
"pm_score": 3,
"selected": false,
"text": "<p>use this.myObjB instead of var myObjB</p>\n"
},
{
"answer_id": 185695,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/178904/simple-javascript-question-what-is-this-thing#178916\">Object literals</a>: </p>\n\n<pre><code>var objA = {\n myObjB: {\n testPrint: function(){\n print(\"Inside test print\");\n }\n }\n};\n\nobjA.myObjB.testPrint();\n</code></pre>\n"
},
{
"answer_id": 185750,
"author": "Sugendran",
"author_id": 22466,
"author_profile": "https://Stackoverflow.com/users/22466",
"pm_score": 1,
"selected": false,
"text": "<p>If you're trying to do inheritance then you may want to consider the <strong>prototype</strong> keyword.</p>\n\n<pre><code>var myObjB = function(){\n this.testPrint = function () {\n print ( \" Inside testPrint \" );\n }\n}\n\nvar myObjA = new myObjB();\nmyObjA.prototype = {\n var1 : \"hello world\",\n test : function(){\n this.testPrint(this.var1);\n }\n}\n</code></pre>\n\n<p>(i hope that made sense)</p>\n"
},
{
"answer_id": 185875,
"author": "harley.333",
"author_id": 26259,
"author_profile": "https://Stackoverflow.com/users/26259",
"pm_score": 1,
"selected": false,
"text": "<p>Your definition of TestA does not expose any public members.\nTo expose myObjB, you need to make it public:</p>\n\n<pre><code>function TestA() {\n this.myObjB = new TestB();\n}\nvar objA = new TestA();\nvar objB = objA.myObjB;\n</code></pre>\n"
},
{
"answer_id": 17379302,
"author": "Lorenzo Polidori",
"author_id": 885464,
"author_profile": "https://Stackoverflow.com/users/885464",
"pm_score": 4,
"selected": false,
"text": "<p>If you want the prototype definition of the inner nested classes to be not accessible from outside the outer class, as well as a cleaner OO implementation, take a look at this.</p>\n\n<pre><code>var BobsGarage = BobsGarage || {}; // namespace\n\n/**\n * BobsGarage.Car\n * @constructor\n * @returns {BobsGarage.Car}\n */\nBobsGarage.Car = function() {\n\n /**\n * Engine\n * @constructor\n * @returns {Engine}\n */\n var Engine = function() {\n // definition of an engine\n };\n\n Engine.prototype.constructor = Engine;\n Engine.prototype.start = function() {\n console.log('start engine');\n };\n\n /**\n * Tank\n * @constructor\n * @returns {Tank}\n */\n var Tank = function() {\n // definition of a tank\n };\n\n Tank.prototype.constructor = Tank;\n Tank.prototype.fill = function() {\n console.log('fill tank');\n };\n\n this.engine = new Engine();\n this.tank = new Tank();\n};\n\nBobsGarage.Car.prototype.constructor = BobsGarage.Car;\n\n/**\n * BobsGarage.Ferrari\n * Derived from BobsGarage.Car\n * @constructor\n * @returns {BobsGarage.Ferrari}\n */\nBobsGarage.Ferrari = function() {\n BobsGarage.Car.call(this);\n};\nBobsGarage.Ferrari.prototype = Object.create(BobsGarage.Car.prototype);\nBobsGarage.Ferrari.prototype.constructor = BobsGarage.Ferrari;\nBobsGarage.Ferrari.prototype.speedUp = function() {\n console.log('speed up');\n};\n\n// Test it on the road\n\nvar car = new BobsGarage.Car();\ncar.tank.fill();\ncar.engine.start();\n\nvar ferrari = new BobsGarage.Ferrari();\nferrari.tank.fill();\nferrari.engine.start();\nferrari.speedUp();\n\n// var engine = new Engine(); // ReferenceError\n\nconsole.log(ferrari);\n</code></pre>\n\n<p>This way you can have <em>prototype inheritance</em> and <em>nested classes</em> so that classes defined within <code>BobsGarage.Car</code> are not accessible outside the constructor of <code>BobsGarage.Car</code> but instances of them are accessible to derived classes, as shown in the test code.</p>\n\n<p>Note: I am referring to the concept of <em>Class</em> in Javascript as defined on the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript\">MDN</a>. </p>\n"
},
{
"answer_id": 73005177,
"author": "iNeobee",
"author_id": 19561960,
"author_profile": "https://Stackoverflow.com/users/19561960",
"pm_score": 0,
"selected": false,
"text": "<p>this is another way to do that.</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>class A {\n constructor(classB) {\n this.ObjB = classB\n }\n}\n\nclass B {\n Hello() {\n console.log(\"Hello from class B\")\n }\n}\n\nlet objA = new A(new B())\n\nobjA.ObjB.Hello()</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How do I define nested class in Java Script.
Here is the code snippet I have:
```
objA = new TestA();
function TestB ()
{
this.testPrint = function ()
{
print ( " Inside testPrint " );
}
}
function TestA ()
{
var myObjB = new TestB();
}
```
Now I am trying to access testPrint using objA
```
objA.myObjB.testPrint();
```
But its giving error "objA has no properties"
How can I access testB method using objA handler?
|
If you want the prototype definition of the inner nested classes to be not accessible from outside the outer class, as well as a cleaner OO implementation, take a look at this.
```
var BobsGarage = BobsGarage || {}; // namespace
/**
* BobsGarage.Car
* @constructor
* @returns {BobsGarage.Car}
*/
BobsGarage.Car = function() {
/**
* Engine
* @constructor
* @returns {Engine}
*/
var Engine = function() {
// definition of an engine
};
Engine.prototype.constructor = Engine;
Engine.prototype.start = function() {
console.log('start engine');
};
/**
* Tank
* @constructor
* @returns {Tank}
*/
var Tank = function() {
// definition of a tank
};
Tank.prototype.constructor = Tank;
Tank.prototype.fill = function() {
console.log('fill tank');
};
this.engine = new Engine();
this.tank = new Tank();
};
BobsGarage.Car.prototype.constructor = BobsGarage.Car;
/**
* BobsGarage.Ferrari
* Derived from BobsGarage.Car
* @constructor
* @returns {BobsGarage.Ferrari}
*/
BobsGarage.Ferrari = function() {
BobsGarage.Car.call(this);
};
BobsGarage.Ferrari.prototype = Object.create(BobsGarage.Car.prototype);
BobsGarage.Ferrari.prototype.constructor = BobsGarage.Ferrari;
BobsGarage.Ferrari.prototype.speedUp = function() {
console.log('speed up');
};
// Test it on the road
var car = new BobsGarage.Car();
car.tank.fill();
car.engine.start();
var ferrari = new BobsGarage.Ferrari();
ferrari.tank.fill();
ferrari.engine.start();
ferrari.speedUp();
// var engine = new Engine(); // ReferenceError
console.log(ferrari);
```
This way you can have *prototype inheritance* and *nested classes* so that classes defined within `BobsGarage.Car` are not accessible outside the constructor of `BobsGarage.Car` but instances of them are accessible to derived classes, as shown in the test code.
Note: I am referring to the concept of *Class* in Javascript as defined on the [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript).
|
185,681 |
<p>How to parse the DOM and determine what row is selected in an ASP.NET <code>ListView</code>? I'm able to interact with the DOM via the <code>HtmlElement</code> in Silverlight, but I have not been able to locate a property indicating the row is selected.</p>
<p>For reference, this managed method works fine for an ASP.NET ListBox</p>
<pre><code>var elm = HtmlPage.Document.GetElementById(ListBoxId);
foreach (var childElm in elm.Children)
{
if (!((bool)childElm.GetProperty("Selected")))
{
continue;
}
}
</code></pre>
|
[
{
"answer_id": 185897,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 0,
"selected": false,
"text": "<p>I don't have my dev environment up to test this, but could you call GetProperty('selectedIndex') on the ListBoxID element? Then from that you figure out which child is selected and return that child using the elm.Children. </p>\n\n<p><strong>Edit:</strong> Got my dev environment up this morning and did some testing. Here is a code snippet that worked for me:</p>\n\n<pre><code>HtmlElement elem = HtmlPage.Document.GetElementById(\"testSelect\");\nint index = Convert.ToInt32(elem.GetProperty(\"selectedIndex\"));\nvar options = (from c in elem.Children\n let he = c as HtmlElement\n where he.TagName == \"option\"\n select he).ToList();\n\noutput.Text = (string)options[index].GetProperty(\"innerText\");\n</code></pre>\n\n<p>Of course, you'll have to change \"textSelect\" to the name of your html select element. The linq query is needed since the Children property is made up of ScriptableObjects and only about half of them are the option elements which is what you care about.</p>\n"
},
{
"answer_id": 186700,
"author": "mathieu",
"author_id": 971,
"author_profile": "https://Stackoverflow.com/users/971",
"pm_score": 1,
"selected": false,
"text": "<p>If your listview has a specific css class for selected row, you can try to filter on it</p>\n"
},
{
"answer_id": 256389,
"author": "beckelmw",
"author_id": 25335,
"author_profile": "https://Stackoverflow.com/users/25335",
"pm_score": 1,
"selected": false,
"text": "<p>The suggestion mathieu provided should work fine. Since you mentioned row, I would say add an id to the tr element in your ListView that you can then find with jQuery. </p>\n\n<p>So,</p>\n\n<pre><code><tr id='selectedRow'>\n......\n</tr>\n\n$(document).ready(function() {\n $(\"#selectedRow\").click(function() {\n alert('This is the selected row');\n });\n\n});\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21410/"
] |
How to parse the DOM and determine what row is selected in an ASP.NET `ListView`? I'm able to interact with the DOM via the `HtmlElement` in Silverlight, but I have not been able to locate a property indicating the row is selected.
For reference, this managed method works fine for an ASP.NET ListBox
```
var elm = HtmlPage.Document.GetElementById(ListBoxId);
foreach (var childElm in elm.Children)
{
if (!((bool)childElm.GetProperty("Selected")))
{
continue;
}
}
```
|
If your listview has a specific css class for selected row, you can try to filter on it
|
185,690 |
<p>I'm using the <a href="http://www.componentace.com/zlib_.NET.htm" rel="noreferrer">zlib.NET</a> library to try and inflate files that are compressed by zlib (on a Linux box, perhaps). Here's what I'm doing:</p>
<pre><code>zlib.ZInputStream zinput =
new zlib.ZInputStream(File.Open(path, FileMode.Open, FileAccess.Read));
while (stopByte != (data = zinput.ReadByte()))
{
// check data here
}
zinput.Close();
</code></pre>
<p>The data bytes match the compressed data bytes, so I must be doing something wrong.</p>
|
[
{
"answer_id": 185736,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>Other than failing to use a \"using\" statement to close the stream even in the face of an exception, that looks okay to me. Is the data definitely compressed? Are you able to decompress it with zlib on the linux box?</p>\n\n<p>Having looked at the source code, it's pretty ghastly - a call to <code>int Read(buffer, offset, length)</code> will end up calling its internal <code>int Read()</code> method <code>length</code> times for example. Given that sort of shaky start, I'm not sure I'd trust the code particularly heavily, but I'd have expected it to work at least <em>slightly</em>! Have you tried using <a href=\"http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx\" rel=\"noreferrer\">SharpZipLib</a>?</p>\n"
},
{
"answer_id": 185924,
"author": "Brendan Kowitz",
"author_id": 25767,
"author_profile": "https://Stackoverflow.com/users/25767",
"pm_score": 0,
"selected": false,
"text": "<p>Look at the sample code more closely, it is copying data from a regular Filestream to the ZOutputStream. The decompression must be happening through that layer.</p>\n\n<pre><code>private void decompressFile(string inFile, string outFile)\n{\n System.IO.FileStream outFileStream = new System.IO.FileStream(outFile, System.IO.FileMode.Create);\n zlib.ZOutputStream outZStream = new zlib.ZOutputStream(outFileStream);\n System.IO.FileStream inFileStream = new System.IO.FileStream(inFile, System.IO.FileMode.Open); \n try\n {\n CopyStream(inFileStream, outZStream);\n }\n finally\n {\n outZStream.Close();\n outFileStream.Close();\n inFileStream.Close();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 187953,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 4,
"selected": true,
"text": "<p>It appears I made the mistake of assuming all virtual methods were overridden, which wasn't the case. I was using zlib.ZInputStream.ReadByte(), which is just the inherited Stream.ReadByte(), which doesn't do any inflate.</p>\n\n<p>I used zlib.ZInputStream.Read() instead, and it worked like it should.</p>\n"
},
{
"answer_id": 473570,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The below code could help you guys. Instantiate the object and make use of the functions.</p>\n\n<pre><code>public class FileCompressionUtility\n{\n public FileCompressionUtility()\n {\n }\n\n public static void CopyStream(System.IO.Stream input, System.IO.Stream output)\n {\n byte[] buffer = new byte[2000];\n int len;\n while ((len = input.Read(buffer, 0, 2000)) > 0)\n {\n output.Write(buffer, 0, len);\n }\n output.Flush();\n }\n\n public void compressFile(string inFile, string outFile)\n {\n System.IO.FileStream outFileStream = new System.IO.FileStream(outFile, System.IO.FileMode.Create);\n zlib.ZOutputStream outZStream = new zlib.ZOutputStream(outFileStream, zlib.zlibConst.Z_DEFAULT_COMPRESSION);\n System.IO.FileStream inFileStream = new System.IO.FileStream(inFile, System.IO.FileMode.Open);\n try\n {\n CopyStream(inFileStream, outZStream);\n }\n finally\n {\n outZStream.Close();\n outFileStream.Close();\n inFileStream.Close();\n }\n }\n\n public void uncompressFile(string inFile, string outFile)\n {\n int data = 0;\n int stopByte = -1;\n System.IO.FileStream outFileStream = new System.IO.FileStream(outFile, System.IO.FileMode.Create);\n zlib.ZInputStream inZStream = new zlib.ZInputStream(System.IO.File.Open(inFile, System.IO.FileMode.Open, System.IO.FileAccess.Read));\n while (stopByte != (data = inZStream.Read()))\n {\n byte _dataByte = (byte)data;\n outFileStream.WriteByte(_dataByte);\n }\n\n inZStream.Close();\n outFileStream.Close();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 15363606,
"author": "Scotty.NET",
"author_id": 1123275,
"author_profile": "https://Stackoverflow.com/users/1123275",
"pm_score": 2,
"selected": false,
"text": "<p>I recently had the misfortune of serving out docs previously zlib'd using php to a variety of browsers and platforms including IE7. Once I figured out that the docs were zlib'd and not gzip'd (as was thought at the time) I used <a href=\"http://www.icsharpcode.net/opensource/sharpziplib/\" rel=\"nofollow\">SharpZipLib</a> in the following way in .NET Framework v4 (taking advantage of <a href=\"http://msdn.microsoft.com/en-us/library/dd782932%28v=vs.100%29.aspx\" rel=\"nofollow\">Stream.CopyTo</a>):</p>\n\n<pre><code>public static byte[] DecompressZlib(Stream source)\n{\n byte[] result = null;\n using (MemoryStream outStream = new MemoryStream())\n {\n using (InflaterInputStream inf = new InflaterInputStream(source))\n {\n inf.CopyTo(outStream);\n }\n result = outStream.ToArray();\n }\n return result;\n}\n</code></pre>\n\n<p>Thought I would put it here in case anyone needs help with the classes to use from SharpZipLib.</p>\n"
},
{
"answer_id": 33855097,
"author": "CodesInChaos",
"author_id": 445517,
"author_profile": "https://Stackoverflow.com/users/445517",
"pm_score": 2,
"selected": false,
"text": "<p>Skipping the zlib header (first two bytes, <code>78 9C</code>) and then using the <a href=\"https://msdn.microsoft.com/en-us/library/system.io.compression.deflatestream.aspx\" rel=\"nofollow\"><code>DeflateStream</code></a> built into .net worked for me.</p>\n\n<pre><code>using(var input = File.OpenRead(...))\nusing(var output = File.Create(...))\n{\n // if there are additional headers before the zlib header, you can skip them:\n // input.Seek(xxx, SeekOrigin.Current);\n\n if (input.ReadByte() != 0x78 || input.ReadByte() != 0x9C)//zlib header\n throw new Exception(\"Incorrect zlib header\");\n\n using (var deflateStream = new DeflateStream(decryptedData, CompressionMode.Decompress, true))\n {\n deflateStream.CopyTo(output);\n }\n}\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3279/"
] |
I'm using the [zlib.NET](http://www.componentace.com/zlib_.NET.htm) library to try and inflate files that are compressed by zlib (on a Linux box, perhaps). Here's what I'm doing:
```
zlib.ZInputStream zinput =
new zlib.ZInputStream(File.Open(path, FileMode.Open, FileAccess.Read));
while (stopByte != (data = zinput.ReadByte()))
{
// check data here
}
zinput.Close();
```
The data bytes match the compressed data bytes, so I must be doing something wrong.
|
It appears I made the mistake of assuming all virtual methods were overridden, which wasn't the case. I was using zlib.ZInputStream.ReadByte(), which is just the inherited Stream.ReadByte(), which doesn't do any inflate.
I used zlib.ZInputStream.Read() instead, and it worked like it should.
|
185,697 |
<p>Input: A positive integer K and a big text. The text can actually be viewed as word sequence. So we don't have to worry about how to break down it into word sequence.<br>
Output: The most frequent K words in the text.</p>
<p>My thinking is like this. </p>
<ol>
<li><p>use a Hash table to record all words' frequency while traverse the whole word sequence. In this phase, the key is "word" and the value is "word-frequency". This takes O(n) time. </p></li>
<li><p>sort the (word, word-frequency) pair; and the key is "word-frequency". This takes O(n*lg(n)) time with normal sorting algorithm. </p></li>
<li><p>After sorting, we just take the first K words. This takes O(K) time. </p></li>
</ol>
<p>To summarize, the total time is O(n+n<em>lg(n)+K), Since K is surely smaller than N, so it is actually O(n</em>lg(n)).</p>
<p>We can improve this. Actually, we just want top K words. Other words' frequency is not concern for us. So, we can use "partial Heap sorting". For step 2) and 3), we don't just do sorting. Instead, we change it to be</p>
<p>2') build a heap of (word, word-frequency) pair with "word-frequency" as key. It takes O(n) time to build a heap;</p>
<p>3') extract top K words from the heap. Each extraction is O(lg(n)). So, total time is O(k*lg(n)).</p>
<p>To summarize, this solution cost time O(n+k*lg(n)).</p>
<p>This is just my thought. I haven't find out way to improve step 1).<br>
I Hope some Information Retrieval experts can shed more light on this question.</p>
|
[
{
"answer_id": 185705,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 3,
"selected": false,
"text": "<p>If your \"big word list\" is big enough, you can simply sample and get estimates. Otherwise, I like hash aggregation.</p>\n\n<p><em>Edit</em>:</p>\n\n<p>By sample I mean choose some subset of pages and calculate the most frequent word in those pages. Provided you select the pages in a reasonable way and select a statistically significant sample, your estimates of the most frequent words should be reasonable.</p>\n\n<p>This approach is really only reasonable if you have so much data that processing it all is just kind of silly. If you only have a few megs, you should be able to tear through the data and calculate an exact answer without breaking a sweat rather than bothering to calculate an estimate.</p>\n"
},
{
"answer_id": 185824,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You can cut down the time further by partitioning using the first letter of words, then partitioning the largest multi-word set using the next character until you have k single-word sets. You would use a sortof 256-way tree with lists of partial/complete words at the leafs. You would need to be very careful to not cause string copies everywhere.</p>\n\n<p>This algorithm is O(m), where m is the number of characters. It avoids that dependence on k, which is very nice for large k [by the way your posted running time is wrong, it should be O(n*lg(k)), and I'm not sure what that is in terms of m].</p>\n\n<p>If you run both algorithms side by side you will get what I'm pretty sure is an asymptotically optimal O(min(m, n*lg(k))) algorithm, but mine should be faster on average because it doesn't involve hashing or sorting.</p>\n"
},
{
"answer_id": 186319,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 5,
"selected": false,
"text": "<p>You're not going to get generally better runtime than the solution you've described. You have to do at least O(n) work to evaluate all the words, and then O(k) extra work to find the top k terms.</p>\n\n<p>If your problem set is <em>really</em> big, you can use a distributed solution such as map/reduce. Have n map workers count frequencies on 1/nth of the text each, and for each word, send it to one of m reducer workers calculated based on the hash of the word. The reducers then sum the counts. Merge sort over the reducers' outputs will give you the most popular words in order of popularity.</p>\n"
},
{
"answer_id": 186878,
"author": "Morgan Cheng",
"author_id": 26349,
"author_profile": "https://Stackoverflow.com/users/26349",
"pm_score": 0,
"selected": false,
"text": "<p>Suppose we have a word sequence \"ad\" \"ad\" \"boy\" \"big\" \"bad\" \"com\" \"come\" \"cold\". And K=2.\nas you mentioned \"partitioning using the first letter of words\", we got\n(\"ad\", \"ad\") (\"boy\", \"big\", \"bad\") (\"com\" \"come\" \"cold\")\n\"then partitioning the largest multi-word set using the next character until you have k single-word sets.\"\nit will partition (\"boy\", \"big\", \"bad\") (\"com\" \"come\" \"cold\"), the first partition (\"ad\", \"ad\") is missed, while \"ad\" is actually the most frequent word.</p>\n\n<p>Perhaps I misunderstand your point. Can you please detail your process about partition?</p>\n"
},
{
"answer_id": 393327,
"author": "martinus",
"author_id": 48181,
"author_profile": "https://Stackoverflow.com/users/48181",
"pm_score": 2,
"selected": false,
"text": "<p>You have a bug in your description: Counting takes O(n) time, but sorting takes O(m*lg(m)), where m is the number of <strong>unique</strong> words. This is usually much smaller than the total number of words, so probably should just optimize how the hash is built.</p>\n"
},
{
"answer_id": 393345,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>A small variation on your solution yields an <strong>O(n)</strong> algorithm if we don't care about ranking the top K, and a <strong>O(n+k*lg(k))</strong> solution if we do. I believe both of these bounds are optimal within a constant factor.</p>\n\n<p>The optimization here comes again after we run through the list, inserting into the hash table. We can use the <a href=\"http://en.wikipedia.org/wiki/Selection_algorithm#Linear_general_selection_algorithm_-_.22Median_of_Medians_algorithm.22\" rel=\"noreferrer\">median of medians</a> algorithm to select the Kth largest element in the list. This algorithm is provably O(n).</p>\n\n<p>After selecting the Kth smallest element, we partition the list around that element just as in quicksort. This is obviously also O(n). Anything on the \"left\" side of the pivot is in our group of K elements, so we're done (we can simply throw away everything else as we go along).</p>\n\n<p>So this strategy is:</p>\n\n<ol>\n<li>Go through each word and insert it into a hash table: O(n)</li>\n<li>Select the Kth smallest element: O(n)</li>\n<li>Partition around that element: O(n)</li>\n</ol>\n\n<p>If you want to rank the K elements, simply sort them with any efficient comparison sort in O(k * lg(k)) time, yielding a total run time of O(n+k * lg(k)).</p>\n\n<p>The O(n) time bound is optimal within a constant factor because we must examine each word at least once. </p>\n\n<p>The O(n + k * lg(k)) time bound is also optimal because there is no comparison-based way to sort k elements in less than k * lg(k) time. </p>\n"
},
{
"answer_id": 17078513,
"author": "Aly Farahat",
"author_id": 2480652,
"author_profile": "https://Stackoverflow.com/users/2480652",
"pm_score": 0,
"selected": false,
"text": "<p>I believe this problem can be solved by an O(n) algorithm. We could make the sorting on the fly. In other words, the sorting in that case is a sub-problem of the traditional sorting problem since only one counter gets incremented by one every time we access the hash table. Initially, the list is sorted since all counters are zero. As we keep incrementing counters in the hash table, we bookkeep another array of hash values ordered by frequency as follows. Every time we increment a counter, we check its index in the ranked array and check if its count exceeds its predecessor in the list. If so, we swap these two elements. As such we obtain a solution that is at most O(n) where n is the number of words in the original text.</p>\n"
},
{
"answer_id": 19460906,
"author": "Shawn",
"author_id": 165835,
"author_profile": "https://Stackoverflow.com/users/165835",
"pm_score": 0,
"selected": false,
"text": "<p>I was struggling with this as well and get inspired by @aly. Instead of sorting afterwards, we can just maintain a presorted list of words (<code>List<Set<String>></code>) and the word will be in the set at position X where X is the current count of the word. In generally, here's how it works:</p>\n\n<ol>\n<li>for each word, store it as part of map of it's occurrence: <code>Map<String, Integer></code>.</li>\n<li>then, based on the count, remove it from the previous count set, and add it into the new count set.</li>\n</ol>\n\n<p>The drawback of this is the list maybe big - can be optimized by using a <code>TreeMap<Integer, Set<String>></code> - but this will add some overhead. Ultimately we can use a mix of HashMap or our own data structure.</p>\n\n<p>The code</p>\n\n<pre><code>public class WordFrequencyCounter {\n private static final int WORD_SEPARATOR_MAX = 32; // UNICODE 0000-001F: control chars\n Map<String, MutableCounter> counters = new HashMap<String, MutableCounter>();\n List<Set<String>> reverseCounters = new ArrayList<Set<String>>();\n\n private static class MutableCounter {\n int i = 1;\n }\n\n public List<String> countMostFrequentWords(String text, int max) {\n int lastPosition = 0;\n int length = text.length();\n for (int i = 0; i < length; i++) {\n char c = text.charAt(i);\n if (c <= WORD_SEPARATOR_MAX) {\n if (i != lastPosition) {\n String word = text.substring(lastPosition, i);\n MutableCounter counter = counters.get(word);\n if (counter == null) {\n counter = new MutableCounter();\n counters.put(word, counter);\n } else {\n Set<String> strings = reverseCounters.get(counter.i);\n strings.remove(word);\n counter.i ++;\n }\n addToReverseLookup(counter.i, word);\n }\n lastPosition = i + 1;\n }\n }\n\n List<String> ret = new ArrayList<String>();\n int count = 0;\n for (int i = reverseCounters.size() - 1; i >= 0; i--) {\n Set<String> strings = reverseCounters.get(i);\n for (String s : strings) {\n ret.add(s);\n System.out.print(s + \":\" + i);\n count++;\n if (count == max) break;\n }\n if (count == max) break;\n }\n return ret;\n }\n\n private void addToReverseLookup(int count, String word) {\n while (count >= reverseCounters.size()) {\n reverseCounters.add(new HashSet<String>());\n }\n Set<String> strings = reverseCounters.get(count);\n strings.add(word);\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 21665287,
"author": "zproject89",
"author_id": 2851854,
"author_profile": "https://Stackoverflow.com/users/2851854",
"pm_score": 0,
"selected": false,
"text": "<p>I just find out the other solution for this problem. But I am not sure it is right.\nSolution:</p>\n\n<ol>\n<li>Use a Hash table to record all words' frequency T(n) = O(n)</li>\n<li>Choose first k elements of hash table, and restore them in one buffer (whose space = k). T(n) = O(k)</li>\n<li>Each time, firstly we need find the current min element of the buffer, and just compare the min element of the buffer with the (n - k) elements of hash table one by one. If the element of hash table is greater than this min element of buffer, then drop the current buffer's min, and add the element of the hash table. So each time we find the min one in the buffer need T(n) = O(k), and traverse the whole hash table need T(n) = O(n - k). So the whole time complexity for this process is T(n) = O((n-k) * k).</li>\n<li>After traverse the whole hash table, the result is in this buffer.</li>\n<li>The whole time complexity: T(n) = O(n) + O(k) + O(kn - k^2) = O(kn + n - k^2 + k). Since, k is really smaller than n in general. So for this solution, the time complexity is <strong>T(n) = O(kn)</strong>. That is linear time, when k is really small. Is it right? I am really not sure.</li>\n</ol>\n"
},
{
"answer_id": 22341665,
"author": "Chihung Yu",
"author_id": 1320928,
"author_profile": "https://Stackoverflow.com/users/1320928",
"pm_score": 6,
"selected": false,
"text": "<p>This can be done in O(n) time</p>\n\n<p><strong>Solution 1:</strong></p>\n\n<p>Steps:</p>\n\n<ol>\n<li><p>Count words and hash it, which will end up in the structure like this</p>\n\n<pre><code>var hash = {\n \"I\" : 13,\n \"like\" : 3,\n \"meow\" : 3,\n \"geek\" : 3,\n \"burger\" : 2,\n \"cat\" : 1,\n \"foo\" : 100,\n ...\n ...\n</code></pre></li>\n<li><p>Traverse through the hash and find the most frequently used word (in this case \"foo\" 100), then create the array of that size</p></li>\n<li><p>Then we can traverse the hash again and use the number of occurrences of words as array index, if there is nothing in the index, create an array else append it in the array. Then we end up with an array like:</p>\n\n<pre><code> 0 1 2 3 100\n[[ ],[cat],[burger],[like, meow, geek],[]...[foo]]\n</code></pre></li>\n<li><p>Then just traverse the array from the end, and collect the k words.</p></li>\n</ol>\n\n<p><strong>Solution 2:</strong></p>\n\n<p>Steps:</p>\n\n<ol>\n<li>Same as above</li>\n<li>Use min heap and keep the size of min heap to k, and for each word in the hash we compare the occurrences of words with the min, 1) if it's greater than the min value, remove the min (if the size of the min heap is equal to k) and insert the number in the min heap. 2) rest simple conditions.</li>\n<li>After traversing through the array, we just convert the min heap to array and return the array.</li>\n</ol>\n"
},
{
"answer_id": 26278494,
"author": "blueberry0xff",
"author_id": 3059453,
"author_profile": "https://Stackoverflow.com/users/3059453",
"pm_score": 0,
"selected": false,
"text": "<p>Try to think of special data structure to approach this kind of problems. In this case special kind of tree like trie to store strings in specific way, very efficient. Or second way to build your own solution like counting words. I guess this TB of data would be in English then we do have around 600,000 words in general so it'll be possible to store only those words and counting which strings would be repeated + this solution will need regex to eliminate some special characters. First solution will be faster, I'm pretty sure. </p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Trie\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Trie</a></p>\n"
},
{
"answer_id": 28139341,
"author": "Jitendra Rathor",
"author_id": 3710011,
"author_profile": "https://Stackoverflow.com/users/3710011",
"pm_score": 2,
"selected": false,
"text": "<p>Your problem is same as this- \n <a href=\"http://www.geeksforgeeks.org/find-the-k-most-frequent-words-from-a-file/\" rel=\"nofollow\">http://www.geeksforgeeks.org/find-the-k-most-frequent-words-from-a-file/</a></p>\n\n<p>Use Trie and min heap to efficieinty solve it.</p>\n"
},
{
"answer_id": 28855596,
"author": "Anayag",
"author_id": 1271300,
"author_profile": "https://Stackoverflow.com/users/1271300",
"pm_score": 0,
"selected": false,
"text": "<p>This is an interesting idea to search and I could find this paper related to Top-K <a href=\"https://icmi.cs.ucsb.edu/research/tech_reports/reports/2005-23.pdf\" rel=\"nofollow\">https://icmi.cs.ucsb.edu/research/tech_reports/reports/2005-23.pd</a>f </p>\n\n<p>Also there is an implementation of it <a href=\"https://github.com/addthis/stream-lib/blob/master/src/main/java/com/clearspring/analytics/util/TopK.java\" rel=\"nofollow\">here</a>.</p>\n"
},
{
"answer_id": 30064549,
"author": "Nikana Reklawyks",
"author_id": 1449460,
"author_profile": "https://Stackoverflow.com/users/1449460",
"pm_score": 2,
"selected": false,
"text": "<p>If what you're after is the list of <em>k</em> most frequent words in your text for any practical <em>k</em> and for any natural langage, then the complexity of your algorithm is not relevant. </p>\n\n<p>Just <strong>sample</strong>, say, a few million words from your text, process that with any algorithm <em>in a matter of seconds</em>, and the most frequent counts will be very accurate.</p>\n\n<p>As a side note, the complexity of the dummy algorithm (1. count all 2. sort the counts 3. take the best) is O(n+m*log(m)), where m is the number of different words in your text. log(m) is much smaller than (n/m), so it remains O(n). </p>\n\n<p><strong>Practically, the long step is counting.</strong></p>\n"
},
{
"answer_id": 33015973,
"author": "ngLover",
"author_id": 3062346,
"author_profile": "https://Stackoverflow.com/users/3062346",
"pm_score": 0,
"selected": false,
"text": "<p>Simplest code to get the occurrence of most frequently used word.</p>\n\n<pre><code> function strOccurence(str){\n var arr = str.split(\" \");\n var length = arr.length,temp = {},max; \n while(length--){\n if(temp[arr[length]] == undefined && arr[length].trim().length > 0)\n {\n temp[arr[length]] = 1;\n }\n else if(arr[length].trim().length > 0)\n {\n temp[arr[length]] = temp[arr[length]] + 1;\n\n }\n}\n console.log(temp);\n var max = [];\n for(i in temp)\n {\n max[temp[i]] = i;\n }\n console.log(max[max.length])\n //if you want second highest\n console.log(max[max.length - 2])\n}\n</code></pre>\n"
},
{
"answer_id": 36002610,
"author": "craftsmannadeem",
"author_id": 1709793,
"author_profile": "https://Stackoverflow.com/users/1709793",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li>Utilize memory efficient data structure to store the words</li>\n<li>Use MaxHeap, to find the top K frequent words.</li>\n</ol>\n\n<p>Here is the code</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Comparator;\nimport java.util.List;\nimport java.util.PriorityQueue;\n\nimport com.nadeem.app.dsa.adt.Trie;\nimport com.nadeem.app.dsa.adt.Trie.TrieEntry;\nimport com.nadeem.app.dsa.adt.impl.TrieImpl;\n\npublic class TopKFrequentItems {\n\nprivate int maxSize;\n\nprivate Trie trie = new TrieImpl();\nprivate PriorityQueue<TrieEntry> maxHeap;\n\npublic TopKFrequentItems(int k) {\n this.maxSize = k;\n this.maxHeap = new PriorityQueue<TrieEntry>(k, maxHeapComparator());\n}\n\nprivate Comparator<TrieEntry> maxHeapComparator() {\n return new Comparator<TrieEntry>() {\n @Override\n public int compare(TrieEntry o1, TrieEntry o2) {\n return o1.frequency - o2.frequency;\n } \n };\n}\n\npublic void add(String word) {\n this.trie.insert(word);\n}\n\npublic List<TopK> getItems() {\n\n for (TrieEntry trieEntry : this.trie.getAll()) {\n if (this.maxHeap.size() < this.maxSize) {\n this.maxHeap.add(trieEntry);\n } else if (this.maxHeap.peek().frequency < trieEntry.frequency) {\n this.maxHeap.remove();\n this.maxHeap.add(trieEntry);\n }\n }\n List<TopK> result = new ArrayList<TopK>();\n for (TrieEntry entry : this.maxHeap) {\n result.add(new TopK(entry));\n } \n return result;\n}\n\npublic static class TopK {\n public String item;\n public int frequency;\n\n public TopK(String item, int frequency) {\n this.item = item;\n this.frequency = frequency;\n }\n public TopK(TrieEntry entry) {\n this(entry.word, entry.frequency);\n }\n @Override\n public String toString() {\n return String.format(\"TopK [item=%s, frequency=%s]\", item, frequency);\n }\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + frequency;\n result = prime * result + ((item == null) ? 0 : item.hashCode());\n return result;\n }\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n TopK other = (TopK) obj;\n if (frequency != other.frequency)\n return false;\n if (item == null) {\n if (other.item != null)\n return false;\n } else if (!item.equals(other.item))\n return false;\n return true;\n }\n\n} \n</code></pre>\n\n<p>}</p>\n\n<p>Here is the unit tests</p>\n\n<pre><code>@Test\npublic void test() {\n TopKFrequentItems stream = new TopKFrequentItems(2);\n\n stream.add(\"hell\");\n stream.add(\"hello\");\n stream.add(\"hello\");\n stream.add(\"hello\");\n stream.add(\"hello\");\n stream.add(\"hello\");\n stream.add(\"hero\");\n stream.add(\"hero\");\n stream.add(\"hero\");\n stream.add(\"hello\");\n stream.add(\"hello\");\n stream.add(\"hello\");\n stream.add(\"home\");\n stream.add(\"go\");\n stream.add(\"go\");\n assertThat(stream.getItems()).hasSize(2).contains(new TopK(\"hero\", 3), new TopK(\"hello\", 8));\n}\n</code></pre>\n\n<p>For more details refer <a href=\"https://github.com/mnadeem/data-structures-algorithms/blob/master/src/test/java/com/nadeem/app/dsa/algo/stream/TopKFrequentItemsTest.java\" rel=\"nofollow\">this test case</a></p>\n"
},
{
"answer_id": 39690987,
"author": "Mohammad",
"author_id": 5475941,
"author_profile": "https://Stackoverflow.com/users/5475941",
"pm_score": 0,
"selected": false,
"text": "<p>In these situations, I recommend to use Java built-in features. Since, they are already well tested and stable. In this problem, I find the repetitions of the words by using HashMap data structure. Then, I push the results to an array of objects. I sort the object by Arrays.sort() and print the top k words and their repetitions. </p>\n\n<pre><code>import java.io.*;\nimport java.lang.reflect.Array;\nimport java.util.*;\n\npublic class TopKWordsTextFile {\n\n static class SortObject implements Comparable<SortObject>{\n\n private String key;\n private int value;\n\n public SortObject(String key, int value) {\n super();\n this.key = key;\n this.value = value;\n }\n\n @Override\n public int compareTo(SortObject o) {\n //descending order\n return o.value - this.value;\n }\n }\n\n\n public static void main(String[] args) {\n HashMap<String,Integer> hm = new HashMap<>();\n int k = 1;\n try {\n BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(\"words.in\")));\n\n String line;\n while ((line = br.readLine()) != null) {\n // process the line.\n //System.out.println(line);\n String[] tokens = line.split(\" \");\n for(int i=0; i<tokens.length; i++){\n if(hm.containsKey(tokens[i])){\n //If the key already exists\n Integer prev = hm.get(tokens[i]);\n hm.put(tokens[i],prev+1);\n }else{\n //If the key doesn't exist\n hm.put(tokens[i],1);\n }\n }\n }\n //Close the input\n br.close();\n //Print all words with their repetitions. You can use 3 for printing top 3 words.\n k = hm.size();\n // Get a set of the entries\n Set set = hm.entrySet();\n // Get an iterator\n Iterator i = set.iterator();\n int index = 0;\n // Display elements\n SortObject[] objects = new SortObject[hm.size()];\n while(i.hasNext()) {\n Map.Entry e = (Map.Entry)i.next();\n //System.out.print(\"Key: \"+e.getKey() + \": \");\n //System.out.println(\" Value: \"+e.getValue());\n String tempS = (String) e.getKey();\n int tempI = (int) e.getValue();\n objects[index] = new SortObject(tempS,tempI);\n index++;\n }\n System.out.println();\n //Sort the array\n Arrays.sort(objects);\n //Print top k\n for(int j=0; j<k; j++){\n System.out.println(objects[j].key+\":\"+objects[j].value);\n }\n\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n}\n</code></pre>\n\n<p>For more information, please visit <a href=\"https://github.com/m-vahidalizadeh/foundations/blob/master/src/algorithms/TopKWordsTextFile.java\" rel=\"nofollow\">https://github.com/m-vahidalizadeh/foundations/blob/master/src/algorithms/TopKWordsTextFile.java</a>. I hope it helps.</p>\n"
},
{
"answer_id": 43336284,
"author": "M Sach",
"author_id": 802050,
"author_profile": "https://Stackoverflow.com/users/802050",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li><p>use a Hash table to record all words' frequency while traverse the whole word sequence. In this phase, the key is \"word\" and the value is \"word-frequency\". This takes O(n) time.This is same as every one explained above</p></li>\n<li><p>While insertion itself in hashmap , keep the Treeset(specific to java, there are implementations in every language) of size 10(k=10) to keep the top 10 frequent words. Till size is less than 10, keep adding it. If size equal to 10, if inserted element is greater than minimum element i.e. first element. If yes remove it and insert new element</p></li>\n</ol>\n\n<p>To restrict the size of treeset see <a href=\"http://www.java2s.com/Code/Java/Collections-Data-Structure/ATreeSetthatensuresitnevergrowsbeyondamaxsize.htm\" rel=\"nofollow noreferrer\">this link</a></p>\n"
},
{
"answer_id": 46003913,
"author": "asad_nitp",
"author_id": 5066038,
"author_profile": "https://Stackoverflow.com/users/5066038",
"pm_score": 0,
"selected": false,
"text": "<pre><code>**\n</code></pre>\n\n<blockquote>\n <p>C++11 Implementation of the above thought</p>\n</blockquote>\n\n<p>**</p>\n\n<pre><code>class Solution {\npublic:\nvector<int> topKFrequent(vector<int>& nums, int k) {\n\n unordered_map<int,int> map;\n for(int num : nums){\n map[num]++;\n }\n\n vector<int> res;\n // we use the priority queue, like the max-heap , we will keep (size-k) smallest elements in the queue\n // pair<first, second>: first is frequency, second is number \n priority_queue<pair<int,int>> pq; \n for(auto it = map.begin(); it != map.end(); it++){\n pq.push(make_pair(it->second, it->first));\n\n // onece the size bigger than size-k, we will pop the value, which is the top k frequent element value \n\n if(pq.size() > (int)map.size() - k){\n res.push_back(pq.top().second);\n pq.pop();\n }\n }\n return res;\n\n}\n</code></pre>\n\n<p>};</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] |
Input: A positive integer K and a big text. The text can actually be viewed as word sequence. So we don't have to worry about how to break down it into word sequence.
Output: The most frequent K words in the text.
My thinking is like this.
1. use a Hash table to record all words' frequency while traverse the whole word sequence. In this phase, the key is "word" and the value is "word-frequency". This takes O(n) time.
2. sort the (word, word-frequency) pair; and the key is "word-frequency". This takes O(n\*lg(n)) time with normal sorting algorithm.
3. After sorting, we just take the first K words. This takes O(K) time.
To summarize, the total time is O(n+n*lg(n)+K), Since K is surely smaller than N, so it is actually O(n*lg(n)).
We can improve this. Actually, we just want top K words. Other words' frequency is not concern for us. So, we can use "partial Heap sorting". For step 2) and 3), we don't just do sorting. Instead, we change it to be
2') build a heap of (word, word-frequency) pair with "word-frequency" as key. It takes O(n) time to build a heap;
3') extract top K words from the heap. Each extraction is O(lg(n)). So, total time is O(k\*lg(n)).
To summarize, this solution cost time O(n+k\*lg(n)).
This is just my thought. I haven't find out way to improve step 1).
I Hope some Information Retrieval experts can shed more light on this question.
|
This can be done in O(n) time
**Solution 1:**
Steps:
1. Count words and hash it, which will end up in the structure like this
```
var hash = {
"I" : 13,
"like" : 3,
"meow" : 3,
"geek" : 3,
"burger" : 2,
"cat" : 1,
"foo" : 100,
...
...
```
2. Traverse through the hash and find the most frequently used word (in this case "foo" 100), then create the array of that size
3. Then we can traverse the hash again and use the number of occurrences of words as array index, if there is nothing in the index, create an array else append it in the array. Then we end up with an array like:
```
0 1 2 3 100
[[ ],[cat],[burger],[like, meow, geek],[]...[foo]]
```
4. Then just traverse the array from the end, and collect the k words.
**Solution 2:**
Steps:
1. Same as above
2. Use min heap and keep the size of min heap to k, and for each word in the hash we compare the occurrences of words with the min, 1) if it's greater than the min value, remove the min (if the size of the min heap is equal to k) and insert the number in the min heap. 2) rest simple conditions.
3. After traversing through the array, we just convert the min heap to array and return the array.
|
185,698 |
<p>I have a directory with several subdirectories with files.<br>
How can I copy all files in the subdirectories to a new location?<br></p>
<p><strong>Edit:</strong> I do not want to copy the directories, just the files...</p>
<p>As this is still on XP, I chose the below solution:</p>
<pre><code> for /D %S IN ("src\*.*") DO @COPY "%S\" "dest\"
</code></pre>
<p>Thanks!</p>
|
[
{
"answer_id": 185703,
"author": "Eric Tuttleman",
"author_id": 25677,
"author_profile": "https://Stackoverflow.com/users/25677",
"pm_score": 2,
"selected": false,
"text": "<p>The Xcopy command should help here.</p>\n\n<pre><code>XCOPY /E SrcDir\\*.* DestDir\\\n</code></pre>\n\n<p>Or if you don't want any of the files in SrcDir, just the sub directories, you can use XCOPY in conjunction with the FOR command:</p>\n\n<pre><code>FOR /D %s IN (SrcDir\\*) DO @XCOPY /E %s DestDir\\%~ns\\\n</code></pre>\n"
},
{
"answer_id": 185711,
"author": "Cowan",
"author_id": 17041,
"author_profile": "https://Stackoverflow.com/users/17041",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to keep the same folder structure on the other end, sounds as simple as XCOPY</p>\n\n<blockquote>\n <p>xcopy c:\\old\\*.* d:\\new\\ /s</p>\n</blockquote>\n\n<p>Use /e instead of /s if you want empty directories copied too.</p>\n"
},
{
"answer_id": 185715,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p><code>robocopy \"c:\\source\" \"c:\\destination\" /E</code></p>\n"
},
{
"answer_id": 185752,
"author": "Mark Allen",
"author_id": 5948,
"author_profile": "https://Stackoverflow.com/users/5948",
"pm_score": 1,
"selected": false,
"text": "<p>If I understood you correctly you have a big directory tree and you want all the files inside it to be in one directory. If that's correct, then I can do it in two lines: </p>\n\n<pre><code>dir /s /b \"yourSourceDirectoryTreeHere\" > filelist.txt\nfor /f %f in (filelist.txt) do @copy %f \"yourDestinationDirHere\"\n</code></pre>\n\n<p>In a batch file vs. the command line change %f to %%f</p>\n"
},
{
"answer_id": 185758,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 0,
"selected": false,
"text": "<pre><code> for /D %S IN (\"src\\*.*\") DO @COPY \"%S\\\" \"dest\\\"\n</code></pre>\n"
},
{
"answer_id": 185785,
"author": "Eric Tuttleman",
"author_id": 25677,
"author_profile": "https://Stackoverflow.com/users/25677",
"pm_score": 4,
"selected": true,
"text": "<p>Ok. With your edit that says you don't want the directory structure, i think you're going to want to use something like this:</p>\n\n<pre><code>for /F \"usebackq\" %s IN (`DIR /B /S /A-D SrcDir`) DO @(\n XCOPY %s DestDir\\%~nxs\n)\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14484/"
] |
I have a directory with several subdirectories with files.
How can I copy all files in the subdirectories to a new location?
**Edit:** I do not want to copy the directories, just the files...
As this is still on XP, I chose the below solution:
```
for /D %S IN ("src\*.*") DO @COPY "%S\" "dest\"
```
Thanks!
|
Ok. With your edit that says you don't want the directory structure, i think you're going to want to use something like this:
```
for /F "usebackq" %s IN (`DIR /B /S /A-D SrcDir`) DO @(
XCOPY %s DestDir\%~nxs
)
```
|
185,741 |
<p>We can use Bitmapsource object as the content of a Image control, However if I only have Bitmap object, can I use it directly, if I convert Bitmap to Bitmapsouce using the following method:</p>
<pre><code> Bitmap bitmap = imageObjToBeConvert;
IntPtr HBitmap = bitmap.GetHbitmap();
result = Imaging.CreateBitmapSourceFromHBitmap
(HBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
DeleteObject(HBitmap);
bitmap.Dispose();
</code></pre>
<p>It take some time. Is there any way to use Bitmap directly?</p>
<p>And I found BitmapSource seems can't be released directly, Is there a sample method to release the memory immediately, after the Bitmapsouce is not used again.</p>
|
[
{
"answer_id": 185775,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "<p>I think REST would make more sense than traditional RPC. Even the <a href=\"http://msdn.microsoft.com/en-us/library/bb466255.aspx\" rel=\"noreferrer\">Micorosft Robotics Studio runtime application model</a> uses REST.</p>\n\n<p>The robot can consist of different resources that are identified by URI, including one for each sensor and actuator or composite abstractions thereof.</p>\n\n<p>REST puts emphasis on guaranteeing what the side effects of certain methods are and also it facilitates caching, both of which can be useful for something like controlling and monitoring a distant robot. And just because you can use REST it <strong>doesn't</strong> have to be the HTTP protocol.</p>\n\n<p>A SAFE and IDEMPOTENT method like GET, though, is good for tracking the state of the robot and polling its sensor data. You can use something like the Last-Modified header to retrieve cached sensor data that doesn't change often (e.g., humidity or light levels). </p>\n\n<p>For long distances you can use relay proxies for caching.</p>\n\n<p>For commands that move the robot, something like POST would be used where every such message will change the robot (e.g., turn right ). A status code can be returned indicating whether the command was immediately executed or queued for processing. </p>\n\n<p>The absolute state of any resources can be set using something like PUT where multiple messages will not change things any more than just a single message (e.g., point to north pole or dim front lights to 10% brightness). This allows for reliable messaging in case of probablity of messages getting lost en route.</p>\n\n<p>A new resource may be created via a POST-like operation as well, e.g., a data-collection routine and a set of parameters. The POST request can send back a CREATED result with a URI for the new resource, which can be used to DELETE when no longer needed.</p>\n\n<p>A group of robots may also speak to each other using the same REST based protocol and can enjoy the same benefits.</p>\n\n<p>Granted, for something simple like one person controlling a single isolated local robot, a REST API may be overkill. But for multi-user and/or unreliable-communications-channels and/or Web-scale-networking, REST is something to consider.</p>\n"
},
{
"answer_id": 185784,
"author": "Chris Noe",
"author_id": 14749,
"author_profile": "https://Stackoverflow.com/users/14749",
"pm_score": 1,
"selected": false,
"text": "<p>REST principles ensure that your application scales well, and plays well with intermediaries across the internet, (proxies, caching, etc). If your \"virtual machine\" network is large scale then a RESTful architecture could be advantageous. If you are building a small-scale network, then REST would not be as compelling.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25749/"
] |
We can use Bitmapsource object as the content of a Image control, However if I only have Bitmap object, can I use it directly, if I convert Bitmap to Bitmapsouce using the following method:
```
Bitmap bitmap = imageObjToBeConvert;
IntPtr HBitmap = bitmap.GetHbitmap();
result = Imaging.CreateBitmapSourceFromHBitmap
(HBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
DeleteObject(HBitmap);
bitmap.Dispose();
```
It take some time. Is there any way to use Bitmap directly?
And I found BitmapSource seems can't be released directly, Is there a sample method to release the memory immediately, after the Bitmapsouce is not used again.
|
I think REST would make more sense than traditional RPC. Even the [Micorosft Robotics Studio runtime application model](http://msdn.microsoft.com/en-us/library/bb466255.aspx) uses REST.
The robot can consist of different resources that are identified by URI, including one for each sensor and actuator or composite abstractions thereof.
REST puts emphasis on guaranteeing what the side effects of certain methods are and also it facilitates caching, both of which can be useful for something like controlling and monitoring a distant robot. And just because you can use REST it **doesn't** have to be the HTTP protocol.
A SAFE and IDEMPOTENT method like GET, though, is good for tracking the state of the robot and polling its sensor data. You can use something like the Last-Modified header to retrieve cached sensor data that doesn't change often (e.g., humidity or light levels).
For long distances you can use relay proxies for caching.
For commands that move the robot, something like POST would be used where every such message will change the robot (e.g., turn right ). A status code can be returned indicating whether the command was immediately executed or queued for processing.
The absolute state of any resources can be set using something like PUT where multiple messages will not change things any more than just a single message (e.g., point to north pole or dim front lights to 10% brightness). This allows for reliable messaging in case of probablity of messages getting lost en route.
A new resource may be created via a POST-like operation as well, e.g., a data-collection routine and a set of parameters. The POST request can send back a CREATED result with a URI for the new resource, which can be used to DELETE when no longer needed.
A group of robots may also speak to each other using the same REST based protocol and can enjoy the same benefits.
Granted, for something simple like one person controlling a single isolated local robot, a REST API may be overkill. But for multi-user and/or unreliable-communications-channels and/or Web-scale-networking, REST is something to consider.
|
185,747 |
<p>I am trying to convert an <code>int</code> into three <code>bytes</code> representing that <code>int</code> (big endian).</p>
<p>I'm sure it has something to do with bit-wise and and bit shifting. But I have no idea how to go about doing it.</p>
<p>For example:</p>
<pre><code>int myInt;
// some code
byte b1, b2 , b3; // b1 is most significant, then b2 then b3.
</code></pre>
<p>*Note, I am aware that an int is 4 bytes and the three bytes have a chance of over/underflowing.</p>
|
[
{
"answer_id": 185763,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "<p>An int doesn't fit into 3 bytes. However, assuming that you know these particular ones do:</p>\n\n<pre><code> byte b1 = (myInt & 0xff);\n myInt >>= 8;\n byte b2 = (myInt & 0xff);\n myInt >>= 8;\n byte b3 = (myInt & 0xff);\n</code></pre>\n"
},
{
"answer_id": 185766,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 2,
"selected": false,
"text": "<pre><code>byte b1 = (myint >> 16) & 0xff;\nbyte b2 = (myint >> 8) & 0xff;\nbyte b3 = myint & 0xff;\n</code></pre>\n\n<p>I am unsure how this holfds in java though, i aam not a java dev</p>\n"
},
{
"answer_id": 185774,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 5,
"selected": true,
"text": "<p>To get the least significant byte:</p>\n\n<pre><code>b3 = myInt & 0xFF;\n</code></pre>\n\n<p>The 2nd least significant byte:</p>\n\n<pre><code>b2 = (myInt >> 8) & 0xFF;\n</code></pre>\n\n<p>And the 3rd least significant byte:</p>\n\n<pre><code>b1 = (myInt >> 16) & 0xFF;\n</code></pre>\n\n<p><strong>Explanation:</strong></p>\n\n<p>Bitwise ANDing a value with 0xFF (11111111 in binary) will return the least significant 8 bits (bits 0 to 7) in that number. Shifting the number to the right 8 times puts bits 8 to 15 into bit positions 0 to 7 so ANDing with 0xFF will return the second byte. Similarly, shifting the number to the right 16 times puts bits 16 to 23 into bit positions 0 to 7 so ANDing with 0xFF returns the 3rd byte.</p>\n"
},
{
"answer_id": 1648743,
"author": "akjain",
"author_id": 108769,
"author_profile": "https://Stackoverflow.com/users/108769",
"pm_score": 2,
"selected": false,
"text": "<p>In Java</p>\n\n<pre><code>int myInt = 1;\nbyte b1,b2,b3;\nb3 = (byte)(myInt & 0xFF);\nb2 = (byte)((myInt >> 8) & 0xFF);\nb1 = (byte)((myInt >> 16) & 0xFF);\nSystem.out.println(b1+\" \"+b2+\" \"+b3);\n</code></pre>\n\n<p>outputs <strong>0 0 1</strong></p>\n"
},
{
"answer_id": 61238296,
"author": "Marek Manduch",
"author_id": 688820,
"author_profile": "https://Stackoverflow.com/users/688820",
"pm_score": 0,
"selected": false,
"text": "<p>The answer of Jeremy is correct in case of positive integer value. If the conversion should be correct for negative values, it is little more complicated due to two's-complement format (<a href=\"https://en.wikipedia.org/wiki/Two%27s_complement\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Two%27s_complement</a>). The trick is to remove the gap between the interesting bits (the less significant bits) and the 'sign' bit. One easy method is multiplication of the number.</p>\n\n<pre><code> int myIntMultiplied = myInt * 256;\n\n byte b1, b2, b3;\n\n b3 = (byte) ((myIntMultiplied >> 8) & 0xFF);\n b2 = (byte) ((myIntMultiplied >> 16) & 0xFF);\n b1 = (byte) ((myIntMultiplied >> 24) & 0xFF);\n</code></pre>\n\n<p>This will end up with correct two's-complement format for negative values.</p>\n\n<p>PS: You can check and compare binary representation this way:</p>\n\n<pre><code>Integer.toBinaryString(myInt);\nInteger.toBinaryString(myIntMultiplied );\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
] |
I am trying to convert an `int` into three `bytes` representing that `int` (big endian).
I'm sure it has something to do with bit-wise and and bit shifting. But I have no idea how to go about doing it.
For example:
```
int myInt;
// some code
byte b1, b2 , b3; // b1 is most significant, then b2 then b3.
```
\*Note, I am aware that an int is 4 bytes and the three bytes have a chance of over/underflowing.
|
To get the least significant byte:
```
b3 = myInt & 0xFF;
```
The 2nd least significant byte:
```
b2 = (myInt >> 8) & 0xFF;
```
And the 3rd least significant byte:
```
b1 = (myInt >> 16) & 0xFF;
```
**Explanation:**
Bitwise ANDing a value with 0xFF (11111111 in binary) will return the least significant 8 bits (bits 0 to 7) in that number. Shifting the number to the right 8 times puts bits 8 to 15 into bit positions 0 to 7 so ANDing with 0xFF will return the second byte. Similarly, shifting the number to the right 16 times puts bits 16 to 23 into bit positions 0 to 7 so ANDing with 0xFF returns the 3rd byte.
|
185,778 |
<p>I am using trigger_error to "throw" errors in a custom class. My problem is that trigger_error prints out the line number where trigger_error was called. For example, given the following code:</p>
<pre><code>01 <?php
02 class Test {
03 function doAction() {
04 $this->doSubAction();
05 }
06
07 function doSubAction() {
08 if(true)
09 trigger_error('Custom error', E_USER_WARNING);
10 }
11 }
12
13 $var = new Test();
14 $var->doAction();
15 ?>
</code></pre>
<p>PHP will print out the following:</p>
<blockquote>
<p><strong>Warning:</strong> Custom error in <strong>test.php</strong> on line <strong>9</strong></p>
</blockquote>
<p>How would you make PHP return the line where the doAction() function was called (the method called outside the class, ignoring all calls made internally) as follows?</p>
<blockquote>
<p><strong>Warning:</strong> Custom error in <strong>test.php</strong> on line <strong>14</strong></p>
</blockquote>
<p><strong>Edit:</strong> Modified my example to be something a bit closer to what I'm trying to achieve.</p>
|
[
{
"answer_id": 185793,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 2,
"selected": false,
"text": "<p>The best thing to do is set up an error handler that shows a full stack trace.</p>\n\n<p>Set up a custom error handler, and call debug_print_backtrace() in it. You will find this useful in general, as well in this specific circumstance.</p>\n"
},
{
"answer_id": 185817,
"author": "Rob Howard",
"author_id": 3528,
"author_profile": "https://Stackoverflow.com/users/3528",
"pm_score": 0,
"selected": false,
"text": "<p>Two options, neither one are particularly palatable:</p>\n\n<ul>\n<li><p>Override Have test() provide <code>__LINE__</code> in the arguments (eg. \"<code>test(__LINE__)</code>\", and give the argument to trigger_error). Set an error handler to print a custom error message. <strong>NOTE:</strong> This is horrifically ugly. :-)</p></li>\n<li><p>Set up an error handler, and have it call and process the horrifically-large output of debug_backtrace(). This function can be useful when debugging... But is overkill for what you're trying to do. Please don't use this function as part of the regular operation of a system.</p></li>\n</ul>\n\n<p>Short answer: too hard, don't try. :-|</p>\n"
},
{
"answer_id": 185932,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 0,
"selected": false,
"text": "<p>I usually put a trigger_error() there also. This ensure that I know exactly where it's called and exactly where the actual error occured. I then send all of the errors to myself in an email when in production. I know this isn't automatic, but at least you can trace what happened.</p>\n"
},
{
"answer_id": 1145375,
"author": "Andrew Moore",
"author_id": 26210,
"author_profile": "https://Stackoverflow.com/users/26210",
"pm_score": 2,
"selected": true,
"text": "<p>Alright, for those of you who are interested in my final solution, I integrated the following piece of code in our framework which returns the correct line number in all the cases that we could of tested. We are using it in production.</p>\n\n<p><a href=\"http://pastebin.com/f12a290d1\" rel=\"nofollow noreferrer\"><code>ErrorHandler</code> class</a></p>\n\n<p>It catches uncaught PHP exceptions, PHP errors and <code>PEAR::Error</code> s. You will need to modify it a bit has the code has some framework specific functions, but they shouldn't be to hard to track down. Enjoy!</p>\n"
},
{
"answer_id": 35304970,
"author": "Borgboy",
"author_id": 2708979,
"author_profile": "https://Stackoverflow.com/users/2708979",
"pm_score": 0,
"selected": false,
"text": "<p>I thought I'd throw my two cents into the pot and discuss what I generally use, either as is or with small customizations, for PHP libraries that I build that are often used by other developers.</p>\n\n<p>I subdivide errors that may arise during execution of the program into two categories: those that are a result of erroneous programming and those that occur due to either user error or some outside factor. For the former, I use trigger_error in conjunction with E_USER_ERROR and the latter an Exception, specifically a package Exception that is then inherited by all other Exceptions in the library.</p>\n\n<p>An example of a development error would be passing an integer in a parameter that is expected to be a string (pre V7) or accessing a method or property of a class that doesn't exist. (You can use your own developer imagination here.) Obviously another developer isn't going to care that the error was generated deep in the bowels of a __get or __set statement or some other magic construct, but rather, they'll want to know specifically where their mistake is. Let's face it...developers don't like to wade through a backtrace.</p>\n\n<p>So the method I employ to localize the error message with is simply:</p>\n\n<pre><code>function localize_error_msg($msg, $level) {\n $level = (int)$level;\n $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $level + 1)[$level];\n return $msg . \" in \" . $backtrace['file'] . \" on line \" . $backtrace['line'];\n}\n</code></pre>\n\n<p>I pass in the backtrace level that depends on the construct used which is generally 1 or 2 and the rest is self explanatory.</p>\n\n<p>To prevent the repetitive sequence of \"in file on line n\", I add this error handler:</p>\n\n<pre><code>set_error_handler(function($errno, $errstr, $errfile, $errline) {\n if (preg_match('/on line \\d+$/', $errstr) === 1)\n die($errstr);\n else return false;\n}, E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE);\n</code></pre>\n\n<p>Again, I like to keep it simple. One can argue that the localization of the error message should take place in the handler but then, you have to be able to pass in the depth, which is now an additional 2 levels deep inside the handler, and, well, it gets messy after that.</p>\n\n<p>Happy Trails!</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26210/"
] |
I am using trigger\_error to "throw" errors in a custom class. My problem is that trigger\_error prints out the line number where trigger\_error was called. For example, given the following code:
```
01 <?php
02 class Test {
03 function doAction() {
04 $this->doSubAction();
05 }
06
07 function doSubAction() {
08 if(true)
09 trigger_error('Custom error', E_USER_WARNING);
10 }
11 }
12
13 $var = new Test();
14 $var->doAction();
15 ?>
```
PHP will print out the following:
>
> **Warning:** Custom error in **test.php** on line **9**
>
>
>
How would you make PHP return the line where the doAction() function was called (the method called outside the class, ignoring all calls made internally) as follows?
>
> **Warning:** Custom error in **test.php** on line **14**
>
>
>
**Edit:** Modified my example to be something a bit closer to what I'm trying to achieve.
|
Alright, for those of you who are interested in my final solution, I integrated the following piece of code in our framework which returns the correct line number in all the cases that we could of tested. We are using it in production.
[`ErrorHandler` class](http://pastebin.com/f12a290d1)
It catches uncaught PHP exceptions, PHP errors and `PEAR::Error` s. You will need to modify it a bit has the code has some framework specific functions, but they shouldn't be to hard to track down. Enjoy!
|
185,780 |
<p>I'm adding repeating events to a Cocoa app I'm working on. I have repeat every day and week fine because I can define these mathematically (3600*24*7 = 1 week). I use the following code to modify the date:</p>
<pre><code>[NSDate dateWithTimeIntervalSinceNow:(3600*24*7*(weeks))]
</code></pre>
<p>I know how many months have passed since the event was repeated but I can't figure out how to make an NSDate object that represents 1 month/3 months/6 months/9 months into the future. Ideally I want the user to say repeat monthly starting Oct. 14 and it will repeat the 14th of every month.</p>
|
[
{
"answer_id": 185927,
"author": "Heng-Cheong Leong",
"author_id": 6904,
"author_profile": "https://Stackoverflow.com/users/6904",
"pm_score": 0,
"selected": false,
"text": "<p>I'll probably use NSCalendarDate.</p>\n\n<p>Get current date's dayOfMonth, monthOfYear and yearOfCommonEra, as three numbers.</p>\n\n<p>Add the required number of months (1/3/6/9), taking care of 1) whether that date exist (e.g. 31 April, 29 Feb on a non-leap year), and 2) roll-over of year.</p>\n\n<p>Create that new date with NSCalendarDate's initWithYear:month:day:hour:minute:second:timeZone:</p>\n"
},
{
"answer_id": 186104,
"author": "mmalc",
"author_id": 23233,
"author_profile": "https://Stackoverflow.com/users/23233",
"pm_score": 6,
"selected": true,
"text": "<p>(Almost the same as <a href=\"https://stackoverflow.com/questions/181459/is-there-a-better-way-to-find-midnight-tomorrow/181495#181495\">this question</a>.)</p>\n\n<p>From the <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSCalendarDate_Class/Reference/Reference.html\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n\n<blockquote>\n <p>Use of NSCalendarDate strongly\n discouraged. It is not deprecated yet,\n however it may be in the next major OS\n release after Mac OS X v10.5. For\n calendrical calculations, you should\n use suitable combinations of\n NSCalendar, NSDate, and\n NSDateComponents, as described in\n Calendars in <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html\" rel=\"nofollow noreferrer\">Dates and Times\n Programming Topics for Cocoa</a>.</p>\n</blockquote>\n\n<p>Following that advice:</p>\n\n<pre><code>NSDate *today = [NSDate date];\n\nNSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];\n\nNSDateComponents *components = [[NSDateComponents alloc] init];\ncomponents.month = 1;\nNSDate *nextMonth = [gregorian dateByAddingComponents:components toDate:today options:0];\n[components release];\n\nNSDateComponents *nextMonthComponents = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit fromDate:nextMonth];\n\nNSDateComponents *todayDayComponents = [gregorian components:NSDayCalendarUnit fromDate:today];\n\nnextMonthComponents.day = todayDayComponents.day;\nNSDate *nextMonthDay = [gregorian dateFromComponents:nextMonthComponents];\n\n[gregorian release];\n</code></pre>\n\n<p>There may be a more direct or efficient implementation, but this should be accurate and should point in the right direction.</p>\n"
},
{
"answer_id": 552495,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p><strong>NSCalendarDate</strong> is no longer supported by new SDK , will have problem while building for distribution.</p>\n"
},
{
"answer_id": 2577000,
"author": "Nick Forge",
"author_id": 86046,
"author_profile": "https://Stackoverflow.com/users/86046",
"pm_score": 5,
"selected": false,
"text": "<p>Use NSCalender, NSDateComponents and NSDate:</p>\n\n<pre><code>NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];\ncomponents.month = 1;\nNSDate *oneMonthFromNow = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:[NSDate date] options:0];\n</code></pre>\n\n<p>Just set the different properties of <code>components</code> to get different periods of time (e.g. 3 months, 6 months etc).</p>\n\n<p>Note: Depending on the context, you may want to use <code>[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]</code> instead of <code>[NSCalendar currentCalendar]</code>, if by \"1 month\" you mean \"1 month on the Gregorian calendar\".</p>\n"
},
{
"answer_id": 11517039,
"author": "Shanmugaraja G",
"author_id": 663965,
"author_profile": "https://Stackoverflow.com/users/663965",
"pm_score": 0,
"selected": false,
"text": "<p>You can do like the below:</p>\n\n<pre><code>NSDate *today = [NSDate date];\n\nNSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];\n\nNSDateComponents *components = [[NSDateComponents alloc] init];\ncomponents.month = 1;\nNSDate *nextMonth = [gregorian dateByAddingComponents:components toDate:today options:0];\n[components release];\n\nNSDateComponents *nextMonthComponents = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:nextMonth];\nNSDate *nextMonthDay = [gregorian dateFromComponents:nextMonthComponents];\n\n[gregorian release]; \n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13069/"
] |
I'm adding repeating events to a Cocoa app I'm working on. I have repeat every day and week fine because I can define these mathematically (3600\*24\*7 = 1 week). I use the following code to modify the date:
```
[NSDate dateWithTimeIntervalSinceNow:(3600*24*7*(weeks))]
```
I know how many months have passed since the event was repeated but I can't figure out how to make an NSDate object that represents 1 month/3 months/6 months/9 months into the future. Ideally I want the user to say repeat monthly starting Oct. 14 and it will repeat the 14th of every month.
|
(Almost the same as [this question](https://stackoverflow.com/questions/181459/is-there-a-better-way-to-find-midnight-tomorrow/181495#181495).)
From the [documentation](http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSCalendarDate_Class/Reference/Reference.html):
>
> Use of NSCalendarDate strongly
> discouraged. It is not deprecated yet,
> however it may be in the next major OS
> release after Mac OS X v10.5. For
> calendrical calculations, you should
> use suitable combinations of
> NSCalendar, NSDate, and
> NSDateComponents, as described in
> Calendars in [Dates and Times
> Programming Topics for Cocoa](http://developer.apple.com/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html).
>
>
>
Following that advice:
```
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.month = 1;
NSDate *nextMonth = [gregorian dateByAddingComponents:components toDate:today options:0];
[components release];
NSDateComponents *nextMonthComponents = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit fromDate:nextMonth];
NSDateComponents *todayDayComponents = [gregorian components:NSDayCalendarUnit fromDate:today];
nextMonthComponents.day = todayDayComponents.day;
NSDate *nextMonthDay = [gregorian dateFromComponents:nextMonthComponents];
[gregorian release];
```
There may be a more direct or efficient implementation, but this should be accurate and should point in the right direction.
|
185,781 |
<p>I read an interesting DailyWTF post today, <a href="http://thedailywtf.com/Articles/Out-of-All-the-Possible-Answers.aspx" rel="noreferrer">"Out of All The Possible Answers..."</a> and it interested me enough to dig up the original <a href="http://forums.thedailywtf.com/forums/t/10030.aspx" rel="noreferrer">forum post</a> where it was submitted. This got me thinking how I would solve this interesting problem - the original question is posed on <a href="http://projecteuler.net/index.php?section=problems&id=5" rel="noreferrer">Project Euler</a> as: </p>
<blockquote>
<p>2520 is the smallest number that can be divided by each of the
numbers from 1 to 10 without any remainder.</p>
<p>What is the smallest number that is evenly divisible by all of
the numbers from 1 to 20?</p>
</blockquote>
<p>To reform this as a programming question, <strong>how would you create a function that can find the Least Common Multiple for an arbitrary list of numbers?</strong></p>
<p>I'm incredibly bad with pure math, despite my interest in programming, but I was able to solve this after a little Googling and some experimenting. I'm curious what other approaches SO users might take. If you're so inclined, post some code below, hopefully along with an explanation. Note that while I'm sure libraries exist to compute the GCD and LCM in various languages, I'm more interested in something that displays the logic more directly than calling a library function :-) </p>
<p>I'm most familiar with Python, C, C++, and Perl, but any language you prefer is welcome. Bonus points for explaining the logic for other mathematically-challenged folks out there like myself.</p>
<p><strong>EDIT</strong>: After submitting I did find this similar question <a href="https://stackoverflow.com/questions/147515">Least common multiple for 3 or more numbers</a> but it was answered with the same basic code I already figured out and there's no real explanation, so I felt this was different enough to leave open.</p>
|
[
{
"answer_id": 185815,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": -1,
"selected": false,
"text": "<p>In expanding on @Alexander's comment, I'd point out that if you can factor the numbers to their primes, remove duplicates, then multiply-out, you'll have your answer.</p>\n\n<p>For example, 1-5 have the prime factors of 2,3,2,2,5. Remove the duplicated '2' from the factor list of the '4', and you have 2,2,3,5. Multiplying those together yields 60, which is your answer.</p>\n\n<p>The Wolfram link provided in the previous comment, <a href=\"http://mathworld.wolfram.com/LeastCommonMultiple.html\" rel=\"nofollow noreferrer\">http://mathworld.wolfram.com/LeastCommonMultiple.html</a> goes into a much more formal approach, but the short version is above.</p>\n\n<p>Cheers.</p>\n"
},
{
"answer_id": 185823,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 2,
"selected": false,
"text": "<p>The LCM of one or more numbers is the product of all of the distinct prime factors in all of the numbers, each prime to the power of the max of all the powers to which that prime appears in the numbers one is taking the LCM of.</p>\n\n<p>Say 900 = 2^3 * 3^2 * 5^2, 26460 = 2^2 * 3^3 * 5^1 * 7^2.\nThe max power of 2 is 3, the max power of 3 is 3, the max power of 5 is 1, the max power of 7 is 2, and the max power of any higher prime is 0.\nSo the LCM is: 264600 = 2^3 * 3^3 * 5^2 * 7^2.</p>\n"
},
{
"answer_id": 185920,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 5,
"selected": true,
"text": "<p>This problem is interesting because it doesn't require you to find the LCM of an arbitrary set of numbers, you're given a consecutive range. You can use a variation of the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes</a> to find the answer.</p>\n\n<pre><code>def RangeLCM(first, last):\n factors = range(first, last+1)\n for i in range(0, len(factors)):\n if factors[i] != 1:\n n = first + i\n for j in range(2*n, last+1, n):\n factors[j-first] = factors[j-first] / factors[i]\n return reduce(lambda a,b: a*b, factors, 1)\n</code></pre>\n\n<p><hr>\nEdit: A recent upvote made me re-examine this answer which is over 3 years old. My first observation is that I would have written it a little differently today, using <code>enumerate</code> for example. A couple of small changes were necessary to make it compatible with Python 3.</p>\n\n<p>The second observation is that this algorithm only works if the start of the range is 2 or less, because it doesn't try to sieve out the common factors below the start of the range. For example, RangeLCM(10, 12) returns 1320 instead of the correct 660.</p>\n\n<p>The third observation is that nobody attempted to time this answer against any other answers. My gut said that this would improve over a brute force LCM solution as the range got larger. Testing proved my gut correct, at least this once.</p>\n\n<p>Since the algorithm doesn't work for arbitrary ranges, I rewrote it to assume that the range starts at 1. I removed the call to <code>reduce</code> at the end, as it was easier to compute the result as the factors were generated. I believe the new version of the function is both more correct and easier to understand.</p>\n\n<pre><code>def RangeLCM2(last):\n factors = list(range(last+1))\n result = 1\n for n in range(last+1):\n if factors[n] > 1:\n result *= factors[n]\n for j in range(2*n, last+1, n):\n factors[j] //= factors[n]\n return result\n</code></pre>\n\n<p>Here are some timing comparisons against the original and the solution proposed by <a href=\"https://stackoverflow.com/a/196472/5987\">Joe Bebel</a> which is called <code>RangeEuclid</code> in my tests.</p>\n\n<pre><code>>>> t=timeit.timeit\n>>> t('RangeLCM.RangeLCM(1, 20)', 'import RangeLCM')\n17.999292996735676\n>>> t('RangeLCM.RangeEuclid(1, 20)', 'import RangeLCM')\n11.199833288867922\n>>> t('RangeLCM.RangeLCM2(20)', 'import RangeLCM')\n14.256165588084514\n>>> t('RangeLCM.RangeLCM(1, 100)', 'import RangeLCM')\n93.34979585394194\n>>> t('RangeLCM.RangeEuclid(1, 100)', 'import RangeLCM')\n109.25695507389901\n>>> t('RangeLCM.RangeLCM2(100)', 'import RangeLCM')\n66.09684505991709\n</code></pre>\n\n<p>For the range of 1 to 20 given in the question, Euclid's algorithm beats out both my old and new answers. For the range of 1 to 100 you can see the sieve-based algorithm pull ahead, especially the optimized version.</p>\n"
},
{
"answer_id": 193572,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 1,
"selected": false,
"text": "<p>An algorithm in Haskell. This is the language I think in nowadays for algorithmic thinking. This might seem strange, complicated, and uninviting -- welcome to Haskell!</p>\n\n<pre><code>primes :: (Integral a) => [a]\n--implementation of primes is to be left for another day.\n\nprimeFactors :: (Integral a) => a -> [a]\nprimeFactors n = go n primes where\n go n ps@(p : pt) =\n if q < 1 then [] else\n if r == 0 then p : go q ps else\n go n pt\n where (q, r) = quotRem n p\n\nmultiFactors :: (Integral a) => a -> [(a, Int)]\nmultiFactors n = [ (head xs, length xs) | xs <- group $ primeFactors $ n ]\n\nmultiProduct :: (Integral a) => [(a, Int)] -> a\nmultiProduct xs = product $ map (uncurry (^)) $ xs\n\nmergeFactorsPairwise [] bs = bs\nmergeFactorsPairwise as [] = as\nmergeFactorsPairwise a@((an, am) : _) b@((bn, bm) : _) =\n case compare an bn of\n LT -> (head a) : mergeFactorsPairwise (tail a) b\n GT -> (head b) : mergeFactorsPairwise a (tail b)\n EQ -> (an, max am bm) : mergeFactorsPairwise (tail a) (tail b)\n\nwideLCM :: (Integral a) => [a] -> a\nwideLCM nums = multiProduct $ foldl mergeFactorsPairwise [] $ map multiFactors $ nums\n</code></pre>\n"
},
{
"answer_id": 194081,
"author": "Kirk Strauser",
"author_id": 32538,
"author_profile": "https://Stackoverflow.com/users/32538",
"pm_score": 0,
"selected": false,
"text": "<p>Here's my Python stab at it:</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 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>Step one gets the prime factors of a number. Step two builds a hash table of the maximum number of times each factor was seen, then multiplies them all together.</p>\n"
},
{
"answer_id": 196463,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 3,
"selected": false,
"text": "<p>One-liner in Haskell.</p>\n\n<pre><code>wideLCM = foldl lcm 1\n</code></pre>\n\n<p>This is what I used for my own Project Euler Problem 5.</p>\n"
},
{
"answer_id": 196472,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>The answer does not require any fancy footwork at all in terms of factoring or prime powers, and most certainly does not require the Sieve of Eratosthenes.</p>\n\n<p>Instead, you should calculate the LCM of a single pair by computing the GCD using Euclid's algorithm (which does NOT require factorization, and in fact is significantly faster):</p>\n\n<pre><code>\ndef lcm(a,b):\n gcd, tmp = a,b\n while tmp != 0:\n gcd,tmp = tmp, gcd % tmp\n return a*b/gcd\n</code></pre>\n\n<p>then you can find the total LCM my reducing the array using the above lcm() function:</p>\n\n<pre><code>\nreduce(lcm, range(1,21))\n</code></pre>\n"
},
{
"answer_id": 5600361,
"author": "Bill Cressman",
"author_id": 699306,
"author_profile": "https://Stackoverflow.com/users/699306",
"pm_score": 2,
"selected": false,
"text": "<pre><code>print \"LCM of 4 and 5 = \".LCM(4,5).\"\\n\";\n\nsub LCM {\n my ($a,$b) = @_; \n my ($af,$bf) = (1,1); # The factors to apply to a & b\n\n # Loop and increase until A times its factor equals B times its factor\n while ($a*$af != $b*$bf) {\n if ($a*$af>$b*$bf) {$bf++} else {$af++};\n }\n return $a*$af;\n}\n</code></pre>\n"
},
{
"answer_id": 10648539,
"author": "Michael Anderson",
"author_id": 221955,
"author_profile": "https://Stackoverflow.com/users/221955",
"pm_score": 3,
"selected": false,
"text": "<p>There's a fast solution to this, so long as the range is 1 to N.</p>\n\n<p>The key observation is that if <code>n</code> (< N) has prime factorization <code>p_1^a_1 * p_2^a_2 * ... p_k * a_k</code>, \nthen it will contribute exactly the same factors to the LCM as <code>p_1^a_1</code> and <code>p_2^a_2</code>, ... <code>p_k^a_k</code>. And each of these powers is also in the 1 to N range. Thus we only need to consider the highest pure prime powers less than N.</p>\n\n<p>For example for 20 we have</p>\n\n<pre><code>2^4 = 16 < 20\n3^2 = 9 < 20\n5^1 = 5 < 20\n7\n11\n13\n17\n19\n</code></pre>\n\n<p>Multiplying all these prime powers together we get the required result of </p>\n\n<pre><code>2*2*2*2*3*3*5*7*11*13*17*19 = 232792560\n</code></pre>\n\n<p>So in pseudo code:</p>\n\n<pre><code>def lcm_upto(N):\n total = 1;\n foreach p in primes_less_than(N):\n x=1;\n while x*p <= N:\n x=x*p;\n total = total * x\n return total\n</code></pre>\n\n<p>Now you can tweak the inner loop to work slightly differently to get more speed, and you can precalculate the <code>primes_less_than(N)</code> function.</p>\n\n<p>EDIT:</p>\n\n<p>Due to a recent upvote I decideded to revisit this, to see how the speed comparison with the other listed algorithms went.</p>\n\n<p>Timing for range 1-160 with 10k iterations, against Joe Beibers and Mark Ransoms methods are as follows:</p>\n\n<p>Joes : 1.85s\nMarks : 3.26s\nMine : 0.33s</p>\n\n<p>Here's a log-log graph with the results up to 300.</p>\n\n<p><img src=\"https://i.stack.imgur.com/CpGUw.png\" alt=\"A log-log graph with the results\"></p>\n\n<p>Code for my test can be found here:</p>\n\n<pre><code>import timeit\n\n\ndef RangeLCM2(last):\n factors = range(last+1)\n result = 1\n for n in range(last+1):\n if factors[n] > 1:\n result *= factors[n]\n for j in range(2*n, last+1, n):\n factors[j] /= factors[n]\n return result\n\n\ndef lcm(a,b):\n gcd, tmp = a,b\n while tmp != 0:\n gcd,tmp = tmp, gcd % tmp\n return a*b/gcd\n\ndef EuclidLCM(last):\n return reduce(lcm,range(1,last+1))\n\nprimes = [\n 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, \n 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, \n 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, \n 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, \n 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, \n 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, \n 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, \n 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, \n 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, \n 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, \n 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, \n 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, \n 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, \n 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, \n 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, \n 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, \n 947, 953, 967, 971, 977, 983, 991, 997 ]\n\ndef FastRangeLCM(last):\n total = 1\n for p in primes:\n if p>last:\n break\n x = 1\n while x*p <= last:\n x = x * p\n total = total * x\n return total\n\n\nprint RangeLCM2(20)\nprint EculidLCM(20)\nprint FastRangeLCM(20)\n\nprint timeit.Timer( 'RangeLCM2(20)', \"from __main__ import RangeLCM2\").timeit(number=10000)\nprint timeit.Timer( 'EuclidLCM(20)', \"from __main__ import EuclidLCM\" ).timeit(number=10000)\nprint timeit.Timer( 'FastRangeLCM(20)', \"from __main__ import FastRangeLCM\" ).timeit(number=10000)\n\nprint timeit.Timer( 'RangeLCM2(40)', \"from __main__ import RangeLCM2\").timeit(number=10000)\nprint timeit.Timer( 'EuclidLCM(40)', \"from __main__ import EuclidLCM\" ).timeit(number=10000)\nprint timeit.Timer( 'FastRangeLCM(40)', \"from __main__ import FastRangeLCM\" ).timeit(number=10000)\n\nprint timeit.Timer( 'RangeLCM2(60)', \"from __main__ import RangeLCM2\").timeit(number=10000)\nprint timeit.Timer( 'EuclidLCM(60)', \"from __main__ import EuclidLCM\" ).timeit(number=10000)\nprint timeit.Timer( 'FastRangeLCM(60)', \"from __main__ import FastRangeLCM\" ).timeit(number=10000)\n\nprint timeit.Timer( 'RangeLCM2(80)', \"from __main__ import RangeLCM2\").timeit(number=10000)\nprint timeit.Timer( 'EuclidLCM(80)', \"from __main__ import EuclidLCM\" ).timeit(number=10000)\nprint timeit.Timer( 'FastRangeLCM(80)', \"from __main__ import FastRangeLCM\" ).timeit(number=10000)\n\nprint timeit.Timer( 'RangeLCM2(100)', \"from __main__ import RangeLCM2\").timeit(number=10000)\nprint timeit.Timer( 'EuclidLCM(100)', \"from __main__ import EuclidLCM\" ).timeit(number=10000)\nprint timeit.Timer( 'FastRangeLCM(100)', \"from __main__ import FastRangeLCM\" ).timeit(number=10000)\n\nprint timeit.Timer( 'RangeLCM2(120)', \"from __main__ import RangeLCM2\").timeit(number=10000)\nprint timeit.Timer( 'EuclidLCM(120)', \"from __main__ import EuclidLCM\" ).timeit(number=10000)\nprint timeit.Timer( 'FastRangeLCM(120)', \"from __main__ import FastRangeLCM\" ).timeit(number=10000)\n\nprint timeit.Timer( 'RangeLCM2(140)', \"from __main__ import RangeLCM2\").timeit(number=10000)\nprint timeit.Timer( 'EuclidLCM(140)', \"from __main__ import EuclidLCM\" ).timeit(number=10000)\nprint timeit.Timer( 'FastRangeLCM(140)', \"from __main__ import FastRangeLCM\" ).timeit(number=10000)\n\nprint timeit.Timer( 'RangeLCM2(160)', \"from __main__ import RangeLCM2\").timeit(number=10000)\nprint timeit.Timer( 'EuclidLCM(160)', \"from __main__ import EuclidLCM\" ).timeit(number=10000)\nprint timeit.Timer( 'FastRangeLCM(160)', \"from __main__ import FastRangeLCM\" ).timeit(number=10000)\n</code></pre>\n"
},
{
"answer_id": 12992384,
"author": "Charlie",
"author_id": 1762129,
"author_profile": "https://Stackoverflow.com/users/1762129",
"pm_score": 2,
"selected": false,
"text": "<p>In Haskell:</p>\n\n<pre><code>listLCM xs = foldr (lcm) 1 xs\n</code></pre>\n\n<p>Which you can pass a list eg:</p>\n\n<pre><code>*Main> listLCM [1..10]\n2520\n*Main> listLCM [1..2518]\n266595767785593803705412270464676976610857635334657316692669925537787454299898002207461915073508683963382517039456477669596355816643394386272505301040799324518447104528530927421506143709593427822789725553843015805207718967822166927846212504932185912903133106741373264004097225277236671818323343067283663297403663465952182060840140577104161874701374415384744438137266768019899449317336711720217025025587401208623105738783129308128750455016347481252967252000274360749033444720740958140380022607152873903454009665680092965785710950056851148623283267844109400949097830399398928766093150813869944897207026562740359330773453263501671059198376156051049807365826551680239328345262351788257964260307551699951892369982392731547941790155541082267235224332660060039217194224518623199770191736740074323689475195782613618695976005218868557150389117325747888623795360149879033894667051583457539872594336939497053549704686823966843769912686273810907202177232140876251886218209049469761186661055766628477277347438364188994340512556761831159033404181677107900519850780882430019800537370374545134183233280000\n</code></pre>\n"
},
{
"answer_id": 29588969,
"author": "fixxxer",
"author_id": 170005,
"author_profile": "https://Stackoverflow.com/users/170005",
"pm_score": 0,
"selected": false,
"text": "<p>This is probably the cleanest, shortest answer (both in terms of lines of code) that I've seen so far. </p>\n\n<pre><code>def gcd(a,b): return b and gcd(b, a % b) or a\ndef lcm(a,b): return a * b / gcd(a,b)\n\nn = 1\nfor i in xrange(1, 21):\n n = lcm(n, i)\n</code></pre>\n\n<p>source : <a href=\"http://www.s-anand.net/euler.html\" rel=\"nofollow\">http://www.s-anand.net/euler.html</a></p>\n"
},
{
"answer_id": 29783687,
"author": "Shazam",
"author_id": 3546295,
"author_profile": "https://Stackoverflow.com/users/3546295",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my answer in JavaScript. I first approached this from primes, and developed a nice function of reusable code to find primes and also to find prime factors, but in the end decided that this approach was simpler. </p>\n\n<p>There's nothing unique in my answer that's not posted above, it's just in Javascript which I did not see specifically. </p>\n\n<pre><code>//least common multipe of a range of numbers\nfunction smallestCommons(arr) {\n arr = arr.sort();\n var scm = 1; \n for (var i = arr[0]; i<=arr[1]; i+=1) { \n scm = scd(scm, i); \n }\n return scm;\n}\n\n\n//smallest common denominator of two numbers (scd)\nfunction scd (a,b) {\n return a*b/gcd(a,b);\n}\n\n\n//greatest common denominator of two numbers (gcd)\nfunction gcd(a, b) {\n if (b === 0) { \n return a;\n } else {\n return gcd(b, a%b);\n }\n} \n\nsmallestCommons([1,20]);\n</code></pre>\n"
},
{
"answer_id": 39483016,
"author": "Yup.",
"author_id": 2038363,
"author_profile": "https://Stackoverflow.com/users/2038363",
"pm_score": 0,
"selected": false,
"text": "<p>Here's my javascript solution, I hope you find it easy to follow:</p>\n\n<pre><code>function smallestCommons(arr) {\n var min = Math.min(arr[0], arr[1]);\n var max = Math.max(arr[0], arr[1]);\n\n var smallestCommon = min * max;\n\n var doneCalc = 0;\n\n while (doneCalc === 0) {\n for (var i = min; i <= max; i++) {\n if (smallestCommon % i !== 0) {\n smallestCommon += max;\n doneCalc = 0;\n break;\n }\n else {\n doneCalc = 1;\n }\n }\n }\n\n return smallestCommon;\n}\n</code></pre>\n"
},
{
"answer_id": 51806618,
"author": "NEURON",
"author_id": 10093600,
"author_profile": "https://Stackoverflow.com/users/10093600",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the solution using C Lang</p>\n\n<pre><code>#include<stdio.h>\n int main(){\n int a,b,lcm=1,small,gcd=1,done=0,i,j,large=1,div=0;\n printf(\"Enter range\\n\");\n printf(\"From:\");\n scanf(\"%d\",&a);\n printf(\"To:\");\n scanf(\"%d\",&b);\n int n=b-a+1;\n int num[30];\n for(i=0;i<n;i++){\n num[i]=a+i;\n }\n //Finds LCM\n while(!done){\n for(i=0;i<n;i++){\n if(num[i]==1){\n done=1;continue;\n }\n done=0;\n break;\n }\n if(done){\n continue;\n }\n done=0;\n large=1;\n for(i=0;i<n;i++){\n if(num[i]>large){\n large=num[i];\n }\n }\n div=0;\n for(i=2;i<=large;i++){\n for(j=0;j<n;j++){\n if(num[j]%i==0){\n num[j]/=i;div=1;\n }\n continue;\n }\n if(div){\n lcm*=i;div=0;break;\n }\n }\n }\n done=0;\n //Finds GCD\n while(!done){\n small=num[0];\n for(i=0;i<n;i++){\n if(num[i]<small){\n small=num[i];\n }\n }\n div=0;\n for(i=2;i<=small;i++){\n for(j=0;j<n;j++){\n if(num[j]%i==0){\n div=1;continue;\n }\n div=0;break;\n }\n if(div){\n for(j=0;j<n;j++){\n num[j]/=i;\n }\n gcd*=i;div=0;break;\n }\n }\n if(i==small+1){\n done=1;\n }\n }\n printf(\"LCM = %d\\n\",lcm);\n printf(\"GCD = %d\\n\",gcd);\n return 0;\n}\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20840/"
] |
I read an interesting DailyWTF post today, ["Out of All The Possible Answers..."](http://thedailywtf.com/Articles/Out-of-All-the-Possible-Answers.aspx) and it interested me enough to dig up the original [forum post](http://forums.thedailywtf.com/forums/t/10030.aspx) where it was submitted. This got me thinking how I would solve this interesting problem - the original question is posed on [Project Euler](http://projecteuler.net/index.php?section=problems&id=5) as:
>
> 2520 is the smallest number that can be divided by each of the
> numbers from 1 to 10 without any remainder.
>
>
> What is the smallest number that is evenly divisible by all of
> the numbers from 1 to 20?
>
>
>
To reform this as a programming question, **how would you create a function that can find the Least Common Multiple for an arbitrary list of numbers?**
I'm incredibly bad with pure math, despite my interest in programming, but I was able to solve this after a little Googling and some experimenting. I'm curious what other approaches SO users might take. If you're so inclined, post some code below, hopefully along with an explanation. Note that while I'm sure libraries exist to compute the GCD and LCM in various languages, I'm more interested in something that displays the logic more directly than calling a library function :-)
I'm most familiar with Python, C, C++, and Perl, but any language you prefer is welcome. Bonus points for explaining the logic for other mathematically-challenged folks out there like myself.
**EDIT**: After submitting I did find this similar question [Least common multiple for 3 or more numbers](https://stackoverflow.com/questions/147515) but it was answered with the same basic code I already figured out and there's no real explanation, so I felt this was different enough to leave open.
|
This problem is interesting because it doesn't require you to find the LCM of an arbitrary set of numbers, you're given a consecutive range. You can use a variation of the [Sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) to find the answer.
```
def RangeLCM(first, last):
factors = range(first, last+1)
for i in range(0, len(factors)):
if factors[i] != 1:
n = first + i
for j in range(2*n, last+1, n):
factors[j-first] = factors[j-first] / factors[i]
return reduce(lambda a,b: a*b, factors, 1)
```
---
Edit: A recent upvote made me re-examine this answer which is over 3 years old. My first observation is that I would have written it a little differently today, using `enumerate` for example. A couple of small changes were necessary to make it compatible with Python 3.
The second observation is that this algorithm only works if the start of the range is 2 or less, because it doesn't try to sieve out the common factors below the start of the range. For example, RangeLCM(10, 12) returns 1320 instead of the correct 660.
The third observation is that nobody attempted to time this answer against any other answers. My gut said that this would improve over a brute force LCM solution as the range got larger. Testing proved my gut correct, at least this once.
Since the algorithm doesn't work for arbitrary ranges, I rewrote it to assume that the range starts at 1. I removed the call to `reduce` at the end, as it was easier to compute the result as the factors were generated. I believe the new version of the function is both more correct and easier to understand.
```
def RangeLCM2(last):
factors = list(range(last+1))
result = 1
for n in range(last+1):
if factors[n] > 1:
result *= factors[n]
for j in range(2*n, last+1, n):
factors[j] //= factors[n]
return result
```
Here are some timing comparisons against the original and the solution proposed by [Joe Bebel](https://stackoverflow.com/a/196472/5987) which is called `RangeEuclid` in my tests.
```
>>> t=timeit.timeit
>>> t('RangeLCM.RangeLCM(1, 20)', 'import RangeLCM')
17.999292996735676
>>> t('RangeLCM.RangeEuclid(1, 20)', 'import RangeLCM')
11.199833288867922
>>> t('RangeLCM.RangeLCM2(20)', 'import RangeLCM')
14.256165588084514
>>> t('RangeLCM.RangeLCM(1, 100)', 'import RangeLCM')
93.34979585394194
>>> t('RangeLCM.RangeEuclid(1, 100)', 'import RangeLCM')
109.25695507389901
>>> t('RangeLCM.RangeLCM2(100)', 'import RangeLCM')
66.09684505991709
```
For the range of 1 to 20 given in the question, Euclid's algorithm beats out both my old and new answers. For the range of 1 to 100 you can see the sieve-based algorithm pull ahead, especially the optimized version.
|
185,804 |
<p>I created an app for a small business. Some of the employees in the office can not see the form correctly. The reason is they have their DPI setting set to above 96dpi. Does anybody know of a way to control this?</p>
<p>For all of you who have experience with winforms apps, how do you control your form layout so that DPI does not affect the look of the application?</p>
|
[
{
"answer_id": 187626,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 4,
"selected": false,
"text": "<p>Set the AutoScaleMode to Inherit everywhere (ie all your UserControls) via a global search/replace, then set the AutoScaleMode to Dpi on your main form.</p>\n\n<p>I also find that layout containers work better than anchors for this type of situation.</p>\n"
},
{
"answer_id": 202172,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 6,
"selected": false,
"text": "<p>Assuming you do not try to honor the user's UI font choice (SystemFonts.IconTitleFont), and hard-code your forms for one font size only (e.g. Tahoma 8pt, Microsoft Sans Serif 8.25pt), you can set your form's <code>AutoScaleMode</code> to <code>ScaleMode.Dpi</code>.</p>\n\n<p>This will scale the size of the form and <em>most</em> of it child controls by the factor <code>CurrentDpiSetting / 96</code> by calling <code>Form.Scale()</code>, which in turns calls the protected <code>ScaleControl()</code> method recursivly on itself and all child controls. <code>ScaleControl</code> will increase a control's position, size, font, etc as needed for the new scaling factor.</p>\n\n<blockquote>\n <p><strong>Warning:</strong> Not all controls properly scale themselves. The columns of a\n listview, for example, will not get\n wider as the font gets larger. In\n order to handle that you'll have to\n manually perform additional scaling as\n required. i do this by overriding the\n protected <code>ScaleControl()</code> method, and\n scaling the listview columns manually:</p>\n\n<pre><code>public class MyForm : Form\n{\n protected override void ScaleControl(SizeF factor, BoundsSpecified specified)\n {\n base.ScaleControl(factor, specified);\n Toolkit.ScaleListViewColumns(listView1, factor);\n }\n}\n\npublic class Toolkit \n{\n /// <summary>\n /// Scale the columns of a listview by the Width scale factor specified in factor\n /// </summary>\n /// <param name=\"listview\"></param>\n /// <param name=\"factor\"></param>\n /// <example>/*\n /// protected override void ScaleControl(SizeF factor, BoundsSpecified specified)\n /// {\n /// base.ScaleControl(factor, specified);\n /// \n /// //ListView columns are not automatically scaled with the ListView, so we\n /// //must do it manually\n /// Toolkit.ScaleListViewColumns(lvPermissions, factor);\n /// }\n ///</example>\n public static void ScaleListViewColumns(ListView listview, SizeF factor)\n {\n foreach (ColumnHeader column in listview.Columns)\n {\n column.Width = (int)Math.Round(column.Width * factor.Width);\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>This is all well and good if you're just using controls. But if you ever use any hard-coded pixel sizes, you'll need to scale your pixel widths and lengths by the current scale factor of the form. Some examples of situations that could have hard-coded pixel sizes:</p>\n\n<ul>\n<li>drawing a 25px high rectangle</li>\n<li>drawing an image at location (11,56) on the form</li>\n<li>stretch drawing an icon to 48x48</li>\n<li>drawing text using Microsoft Sans Serif 8.25pt</li>\n<li>getting the 32x32 format of an icon and stuffing it into a PictureBox</li>\n</ul>\n\n<p>If this is the case, you'll need to scale those hard-coded values by the \"<em>current scaling factor</em>\". Unfortunatly the \"current\" scale factor is not provided, we need to record it ourselves. The solution is to assume that initially the scaling factor is 1.0 and each time <code>ScaleControl()</code> is called, modify the running scale factor by the new factor.</p>\n\n<pre><code>public class MyForm : Form\n{\n private SizeF currentScaleFactor = new SizeF(1f, 1f);\n\n protected override void ScaleControl(SizeF factor, BoundsSpecified specified)\n {\n base.ScaleControl(factor, specified);\n\n //Record the running scale factor used\n this.currentScaleFactor = new SizeF(\n this.currentScaleFactor.Width * factor.Width,\n this.currentScaleFactor.Height * factor.Height);\n\n Toolkit.ScaleListViewColumns(listView1, factor);\n }\n}\n</code></pre>\n\n<p>Initially the scaling factor is <code>1.0</code>. If form is then scaled by <code>1.25</code>, the scaling factor then becomes: </p>\n\n<pre><code>1.00 * 1.25 = 1.25 //scaling current factor by 125%\n</code></pre>\n\n<p>If the form is then scaled by <code>0.95</code>, the new scaling factor becomes </p>\n\n<pre><code>1.25 * 0.95 = 1.1875 //scaling current factor by 95%\n</code></pre>\n\n<p>The reason a <code>SizeF</code> is used (rather than a single floating point value) is that scaling amounts can be different in the x and y directions. If a form is set to <code>ScaleMode.Font</code>, the form is scaled to the new font size. Fonts can have different aspect ratios (<em>e.g.</em> <strong>Segoe UI</strong> is taller font than <strong>Tahoma</strong>). This means you have to scale x and y values independantly.</p>\n\n<p>So if you wanted to place a control at location <code>(11,56)</code>, you would have to change your positioning code from:</p>\n\n<pre><code>Point pt = new Point(11, 56);\ncontrol1.Location = pt;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>Point pt = new Point(\n (int)Math.Round(11.0*this.scaleFactor.Width),\n (int)Math.Round(56.0*this.scaleFactor.Height));\ncontrol1.Location = pt;\n</code></pre>\n\n<p>The same applies if you were going to pick a font size:</p>\n\n<pre><code>Font f = new Font(\"Segoe UI\", 8, GraphicsUnit.Point);\n</code></pre>\n\n<p>would have to become:</p>\n\n<pre><code>Font f = new Font(\"Segoe UI\", 8.0*this.scaleFactor.Width, GraphicsUnit.Point);\n</code></pre>\n\n<p>And extracting a 32x32 icon to a bitmap would change from:</p>\n\n<pre><code>Image i = new Icon(someIcon, new Size(32, 32)).ToBitmap();\n</code></pre>\n\n<p>to</p>\n\n<pre><code>Image i = new Icon(someIcon, new Size(\n (int)Math.Round(32.0*this.scaleFactor.Width), \n (int)Math.Round(32.0*this.scaleFactor.Height))).ToBitmap();\n</code></pre>\n\n<p>etc.</p>\n\n<p>Supporting non-standard DPI displays is a <a href=\"http://blogs.msdn.com/oldnewthing/archive/2004/07/14/182971.aspx\" rel=\"noreferrer\">tax that all developers should pay</a>. But the fact that nobody wants to is why <a href=\"http://blogs.msdn.com/greg_schechter/archive/2006/08/07/690704.aspx\" rel=\"noreferrer\">Microsoft gave up and added to Vista the ability for the graphics card to stretch any applications that don't say they properly handle high-dpi</a>. </p>\n"
},
{
"answer_id": 26784687,
"author": "Guildenstern70",
"author_id": 754388,
"author_profile": "https://Stackoverflow.com/users/754388",
"pm_score": 2,
"selected": false,
"text": "<p>I know it's somewhat drastic, but consider to rewrite your app in WPF. WPF applications have the same look on every DPI setting.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21325/"
] |
I created an app for a small business. Some of the employees in the office can not see the form correctly. The reason is they have their DPI setting set to above 96dpi. Does anybody know of a way to control this?
For all of you who have experience with winforms apps, how do you control your form layout so that DPI does not affect the look of the application?
|
Assuming you do not try to honor the user's UI font choice (SystemFonts.IconTitleFont), and hard-code your forms for one font size only (e.g. Tahoma 8pt, Microsoft Sans Serif 8.25pt), you can set your form's `AutoScaleMode` to `ScaleMode.Dpi`.
This will scale the size of the form and *most* of it child controls by the factor `CurrentDpiSetting / 96` by calling `Form.Scale()`, which in turns calls the protected `ScaleControl()` method recursivly on itself and all child controls. `ScaleControl` will increase a control's position, size, font, etc as needed for the new scaling factor.
>
> **Warning:** Not all controls properly scale themselves. The columns of a
> listview, for example, will not get
> wider as the font gets larger. In
> order to handle that you'll have to
> manually perform additional scaling as
> required. i do this by overriding the
> protected `ScaleControl()` method, and
> scaling the listview columns manually:
>
>
>
> ```
> public class MyForm : Form
> {
> protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
> {
> base.ScaleControl(factor, specified);
> Toolkit.ScaleListViewColumns(listView1, factor);
> }
> }
>
> public class Toolkit
> {
> /// <summary>
> /// Scale the columns of a listview by the Width scale factor specified in factor
> /// </summary>
> /// <param name="listview"></param>
> /// <param name="factor"></param>
> /// <example>/*
> /// protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
> /// {
> /// base.ScaleControl(factor, specified);
> ///
> /// //ListView columns are not automatically scaled with the ListView, so we
> /// //must do it manually
> /// Toolkit.ScaleListViewColumns(lvPermissions, factor);
> /// }
> ///</example>
> public static void ScaleListViewColumns(ListView listview, SizeF factor)
> {
> foreach (ColumnHeader column in listview.Columns)
> {
> column.Width = (int)Math.Round(column.Width * factor.Width);
> }
> }
> }
>
> ```
>
>
---
This is all well and good if you're just using controls. But if you ever use any hard-coded pixel sizes, you'll need to scale your pixel widths and lengths by the current scale factor of the form. Some examples of situations that could have hard-coded pixel sizes:
* drawing a 25px high rectangle
* drawing an image at location (11,56) on the form
* stretch drawing an icon to 48x48
* drawing text using Microsoft Sans Serif 8.25pt
* getting the 32x32 format of an icon and stuffing it into a PictureBox
If this is the case, you'll need to scale those hard-coded values by the "*current scaling factor*". Unfortunatly the "current" scale factor is not provided, we need to record it ourselves. The solution is to assume that initially the scaling factor is 1.0 and each time `ScaleControl()` is called, modify the running scale factor by the new factor.
```
public class MyForm : Form
{
private SizeF currentScaleFactor = new SizeF(1f, 1f);
protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
{
base.ScaleControl(factor, specified);
//Record the running scale factor used
this.currentScaleFactor = new SizeF(
this.currentScaleFactor.Width * factor.Width,
this.currentScaleFactor.Height * factor.Height);
Toolkit.ScaleListViewColumns(listView1, factor);
}
}
```
Initially the scaling factor is `1.0`. If form is then scaled by `1.25`, the scaling factor then becomes:
```
1.00 * 1.25 = 1.25 //scaling current factor by 125%
```
If the form is then scaled by `0.95`, the new scaling factor becomes
```
1.25 * 0.95 = 1.1875 //scaling current factor by 95%
```
The reason a `SizeF` is used (rather than a single floating point value) is that scaling amounts can be different in the x and y directions. If a form is set to `ScaleMode.Font`, the form is scaled to the new font size. Fonts can have different aspect ratios (*e.g.* **Segoe UI** is taller font than **Tahoma**). This means you have to scale x and y values independantly.
So if you wanted to place a control at location `(11,56)`, you would have to change your positioning code from:
```
Point pt = new Point(11, 56);
control1.Location = pt;
```
to
```
Point pt = new Point(
(int)Math.Round(11.0*this.scaleFactor.Width),
(int)Math.Round(56.0*this.scaleFactor.Height));
control1.Location = pt;
```
The same applies if you were going to pick a font size:
```
Font f = new Font("Segoe UI", 8, GraphicsUnit.Point);
```
would have to become:
```
Font f = new Font("Segoe UI", 8.0*this.scaleFactor.Width, GraphicsUnit.Point);
```
And extracting a 32x32 icon to a bitmap would change from:
```
Image i = new Icon(someIcon, new Size(32, 32)).ToBitmap();
```
to
```
Image i = new Icon(someIcon, new Size(
(int)Math.Round(32.0*this.scaleFactor.Width),
(int)Math.Round(32.0*this.scaleFactor.Height))).ToBitmap();
```
etc.
Supporting non-standard DPI displays is a [tax that all developers should pay](http://blogs.msdn.com/oldnewthing/archive/2004/07/14/182971.aspx). But the fact that nobody wants to is why [Microsoft gave up and added to Vista the ability for the graphics card to stretch any applications that don't say they properly handle high-dpi](http://blogs.msdn.com/greg_schechter/archive/2006/08/07/690704.aspx).
|
185,836 |
<p>Does anyone know if it possible to define the equivalent of a "java custom class loader" in .NET?</p>
<p><strong>To give a little background:</strong></p>
<p>I am in the process of developing a new programming language that targets the CLR, called "Liberty". One of the features of the language is its ability to define "type constructors", which are methods that are executed by the compiler at compile time and generate types as output. They are sort of a generalization of generics (the language does have normal generics in it), and allow code like this to be written (in "Liberty" syntax):</p>
<pre><code>var t as tuple<i as int, j as int, k as int>;
t.i = 2;
t.j = 4;
t.k = 5;
</code></pre>
<p>Where "tuple" is defined like so:</p>
<pre><code>public type tuple(params variables as VariableDeclaration[]) as TypeDeclaration
{
//...
}
</code></pre>
<p>In this particular example, the type constructor <code>tuple</code> provides something similar to anonymous types in VB and C#.</p>
<p>However, unlike anonymous types, "tuples" have names and can be used inside public method signatures.</p>
<p>This means that I need a way for the type that eventually ends up being emitted by the compiler to be shareable across multiple assemblies. For example, I want</p>
<p><code>tuple<x as int></code> defined in Assembly A to end up being the same type as <code>tuple<x as int></code> defined in Assembly B.</p>
<p>The problem with this, of course, is that Assembly A and Assembly B are going to be compiled at different times, which means they would both end up emitting their own incompatible versions of the tuple type.</p>
<p>I looked into using some sort of "type erasure" to do this, so that I would have a shared library with a bunch of types like this (this is "Liberty" syntax):</p>
<pre><code>class tuple<T>
{
public Field1 as T;
}
class tuple<T, R>
{
public Field2 as T;
public Field2 as R;
}
</code></pre>
<p>and then just redirect access from the i, j, and k tuple fields to <code>Field1</code>, <code>Field2</code>, and <code>Field3</code>.</p>
<p>However that is not really a viable option. This would mean that at compile time <code>tuple<x as int></code> and <code>tuple<y as int></code> would end up being different types, while at runtime time they would be treated as the same type. That would cause many problems for things like equality and type identity. That is too leaky of an abstraction for my tastes. </p>
<p>Other possible options would be to use "state bag objects". However, using a state bag would defeat the whole purpose of having support for "type constructors" in the language. The idea there is to enable "custom language extensions" to generate new types at compile time that the compiler can do static type checking with.</p>
<p>In Java, this could be done using custom class loaders. Basically the code that uses tuple types could be emitted without actually defining the type on disk. A custom "class loader" could then be defined that would dynamically generate the tuple type at runtime. That would allow static type checking inside the compiler, and would unify the tuple types across compilation boundaries.</p>
<p>Unfortunately, however, the CLR does not provide support for custom class loading. All loading in the CLR is done at the assembly level. It would be possible to define a separate assembly for each "constructed type", but that would very quickly lead to performance problems (having many assemblies with only one type in them would use too many resources).</p>
<p><strong>So, what I want to know is:</strong></p>
<p>Is it possible to simulate something like Java Class Loaders in .NET, where I can emit a reference to a non-existing type in and then dynamically generate a reference to that type at runtime before the code the needs to use it runs?</p>
<p><strong>NOTE:</strong></p>
<p>*I actually already know the answer to the question, which I provide as an answer below. However, it took me about 3 days of research, and quite a bit of IL hacking in order to come up with a solution. I figured it would be a good idea to document it here in case anyone else ran into the same problem. *</p>
|
[
{
"answer_id": 185854,
"author": "Kevin Dostalek",
"author_id": 22732,
"author_profile": "https://Stackoverflow.com/users/22732",
"pm_score": -1,
"selected": false,
"text": "<p>I think this is the type of thing the DLR is supposed to provide in C# 4.0. Kind of hard to come by information yet, but perhaps we'll learn more at PDC08. Eagerly waiting to see your C# 3 solution though... I'm guessing it uses anonymous types.</p>\n"
},
{
"answer_id": 185856,
"author": "Scott Wisniewski",
"author_id": 1737192,
"author_profile": "https://Stackoverflow.com/users/1737192",
"pm_score": 7,
"selected": true,
"text": "<p>The answer is yes, but the solution is a little tricky.</p>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.emit.aspx\" rel=\"noreferrer\"><code>System.Reflection.Emit</code></a> namespace defines types that allows assemblies to be generated dynamically. They also allow the generated assemblies to be defined incrementally. In other words it is possible to add types to the dynamic assembly, execute the generated code, and then latter add more types to the assembly. </p>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain.aspx\" rel=\"noreferrer\"><code>System.AppDomain</code></a> class also defines an <a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx\" rel=\"noreferrer\">AssemblyResolve</a> event that fires whenever the framework fails to load an assembly. By adding a handler for that event, it is possible to define a single \"runtime\" assembly into which all \"constructed\" types are placed. The code generated by the compiler that uses a constructed type would refer to a type in the runtime assembly. Because the runtime assembly doesn't actually exist on disk, the <a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx\" rel=\"noreferrer\">AssemblyResolve</a> event would be fired the first time the compiled code tried to access a constructed type. The handle for the event would then generate the dynamic assembly and return it to the CLR.</p>\n\n<p>Unfortunately, there are a few tricky points to getting this to work. The first problem is ensuring that the event handler will always be installed before the compiled code is run. With a console application this is easy. The code to hookup the event handler can just be added to the <code>Main</code> method before the other code runs. For class libraries, however, there is no main method. A dll may be loaded as part of an application written in another language, so it's not really possible to assume there is always a main method available to hookup the event handler code.</p>\n\n<p>The second problem is ensuring that the referenced types all get inserted into the dynamic assembly before any code that references them is used. The <a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain.aspx\" rel=\"noreferrer\"><code>System.AppDomain</code></a> class also defines a <a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain.typeresolve.aspx\" rel=\"noreferrer\"><code>TypeResolve</code></a> event that is executed whenever the CLR is unable to resolve a type in a dynamic assembly. It gives the event handler the opportunity to define the type inside the dynamic assembly before the code that uses it runs. However, that event will not work in this case. The CLR will not fire the event for assemblies that are \"statically referenced\" by other assemblies, even if the referenced assembly is defined dynamically. This means that we need a way to run code before any other code in the compiled assembly runs and have it dynamically inject the types it needs into the runtime assembly if they have not already been defined. Otherwise when the CLR tried to load those types it will notice that the dynamic assembly does not contain the types they need and will throw a type load exception.</p>\n\n<p>Fortunately, the CLR offers a solution to both problems: Module Initializers. A module initializer is the equivalent of a \"static class constructor\", except that it initializes an entire module, not just a single class. Baiscally, the CLR will:</p>\n\n<ol>\n<li>Run the module constructor before any types inside the module are accessed.</li>\n<li>Guarantee that only those types directly accessed by the module constructor will be loaded while it is executing</li>\n<li>Not allow code outside the module to access any of it's members until after the constructor has finished.</li>\n</ol>\n\n<p>It does this for all assemblies, including both class libraries and executables, and for EXEs will run the module constructor before executing the Main method.</p>\n\n<p>See this <a href=\"http://blogs.msdn.com/junfeng/archive/2005/11/19/494914.aspx\" rel=\"noreferrer\">blog post</a> for more information about constructors.</p>\n\n<p>In any case, a complete solution to my problem requires several pieces:</p>\n\n<ol>\n<li><p>The following class definition, defined inside a \"language runtime dll\", that is referenced by all assemblies produced by the compiler (this is C# code).</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Reflection.Emit;\n\nnamespace SharedLib\n{\n public class Loader\n {\n private Loader(ModuleBuilder dynamicModule)\n {\n m_dynamicModule = dynamicModule;\n m_definedTypes = new HashSet<string>();\n }\n\n private static readonly Loader m_instance;\n private readonly ModuleBuilder m_dynamicModule;\n private readonly HashSet<string> m_definedTypes;\n\n static Loader()\n {\n var name = new AssemblyName(\"$Runtime\");\n var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);\n var module = assemblyBuilder.DefineDynamicModule(\"$Runtime\");\n m_instance = new Loader(module);\n AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);\n }\n\n static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n {\n if (args.Name == Instance.m_dynamicModule.Assembly.FullName)\n {\n return Instance.m_dynamicModule.Assembly;\n }\n else\n {\n return null;\n }\n }\n\n public static Loader Instance\n {\n get\n {\n return m_instance;\n }\n }\n\n public bool IsDefined(string name)\n {\n return m_definedTypes.Contains(name);\n }\n\n public TypeBuilder DefineType(string name)\n {\n //in a real system we would not expose the type builder.\n //instead a AST for the type would be passed in, and we would just create it.\n var type = m_dynamicModule.DefineType(name, TypeAttributes.Public);\n m_definedTypes.Add(name);\n return type;\n }\n }\n}\n</code></pre>\n\n<p>The class defines a singleton that holds a reference to the dynamic assembly that the constructed types will be created in. It also holds a \"hash set\" that stores the set of types that have already been dynamically generated, and finally defines a member that can be used to define the type. This example just returns a System.Reflection.Emit.TypeBuilder instance that can then be used to define the class being generated. In a real system, the method would probably take in an AST representation of the class, and just do the generation it's self.</p></li>\n<li><p>Compiled assemblies that emit the following two references (shown in ILASM syntax):</p>\n\n<pre><code>.assembly extern $Runtime\n{\n .ver 0:0:0:0\n}\n.assembly extern SharedLib\n{\n .ver 1:0:0:0\n}\n</code></pre>\n\n<p>Here \"SharedLib\" is the Language's predefined runtime library that includes the \"Loader\" class defined above and \"$Runtime\" is the dynamic runtime assembly that the consructed types will be inserted into.</p></li>\n<li><p>A \"module constructor\" inside every assembly compiled in the language.</p>\n\n<p>As far as I know, there are no .NET languages that allow Module Constructors to be defined in source. The C++ /CLI compiler is the only compiler I know of that generates them. In IL, they look like this, defined directly in the module and not inside any type definitions:</p>\n\n<pre><code>.method privatescope specialname rtspecialname static \n void .cctor() cil managed\n{\n //generate any constructed types dynamically here...\n}\n</code></pre>\n\n<p>For me, It's not a problem that I have to write custom IL to get this to work. I'm writing a compiler, so code generation is not an issue.</p>\n\n<p>In the case of an assembly that used the types <code>tuple<i as int, j as int></code> and <code>tuple<x as double, y as double, z as double></code> the module constructor would need to generate types like the following (here in C# syntax):</p>\n\n<pre><code>class Tuple_i_j<T, R>\n{\n public T i;\n public R j;\n}\n\nclass Tuple_x_y_z<T, R, S>\n{\n public T x;\n public R y;\n public S z;\n}\n</code></pre>\n\n<p>The tuple classes are generated as generic types to get around accessibility issues. That would allow code in the compiled assembly to use <code>tuple<x as Foo></code>, where Foo was some non-public type.</p>\n\n<p>The body of the module constructor that did this (here only showing one type, and written in C# syntax) would look like this:</p>\n\n<pre><code>var loader = SharedLib.Loader.Instance;\nlock (loader)\n{\n if (! loader.IsDefined(\"$Tuple_i_j\"))\n {\n //create the type.\n var Tuple_i_j = loader.DefineType(\"$Tuple_i_j\");\n //define the generic parameters <T,R>\n var genericParams = Tuple_i_j.DefineGenericParameters(\"T\", \"R\");\n var T = genericParams[0];\n var R = genericParams[1];\n //define the field i\n var fieldX = Tuple_i_j.DefineField(\"i\", T, FieldAttributes.Public);\n //define the field j\n var fieldY = Tuple_i_j.DefineField(\"j\", R, FieldAttributes.Public);\n //create the default constructor.\n var constructor= Tuple_i_j.DefineDefaultConstructor(MethodAttributes.Public);\n\n //\"close\" the type so that it can be used by executing code.\n Tuple_i_j.CreateType();\n }\n}\n</code></pre></li>\n</ol>\n\n<p>So in any case, this was the mechanism I was able to come up with to enable the rough equivalent of custom class loaders in the CLR.</p>\n\n<p>Does anyone know of an easier way to do this?</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1737192/"
] |
Does anyone know if it possible to define the equivalent of a "java custom class loader" in .NET?
**To give a little background:**
I am in the process of developing a new programming language that targets the CLR, called "Liberty". One of the features of the language is its ability to define "type constructors", which are methods that are executed by the compiler at compile time and generate types as output. They are sort of a generalization of generics (the language does have normal generics in it), and allow code like this to be written (in "Liberty" syntax):
```
var t as tuple<i as int, j as int, k as int>;
t.i = 2;
t.j = 4;
t.k = 5;
```
Where "tuple" is defined like so:
```
public type tuple(params variables as VariableDeclaration[]) as TypeDeclaration
{
//...
}
```
In this particular example, the type constructor `tuple` provides something similar to anonymous types in VB and C#.
However, unlike anonymous types, "tuples" have names and can be used inside public method signatures.
This means that I need a way for the type that eventually ends up being emitted by the compiler to be shareable across multiple assemblies. For example, I want
`tuple<x as int>` defined in Assembly A to end up being the same type as `tuple<x as int>` defined in Assembly B.
The problem with this, of course, is that Assembly A and Assembly B are going to be compiled at different times, which means they would both end up emitting their own incompatible versions of the tuple type.
I looked into using some sort of "type erasure" to do this, so that I would have a shared library with a bunch of types like this (this is "Liberty" syntax):
```
class tuple<T>
{
public Field1 as T;
}
class tuple<T, R>
{
public Field2 as T;
public Field2 as R;
}
```
and then just redirect access from the i, j, and k tuple fields to `Field1`, `Field2`, and `Field3`.
However that is not really a viable option. This would mean that at compile time `tuple<x as int>` and `tuple<y as int>` would end up being different types, while at runtime time they would be treated as the same type. That would cause many problems for things like equality and type identity. That is too leaky of an abstraction for my tastes.
Other possible options would be to use "state bag objects". However, using a state bag would defeat the whole purpose of having support for "type constructors" in the language. The idea there is to enable "custom language extensions" to generate new types at compile time that the compiler can do static type checking with.
In Java, this could be done using custom class loaders. Basically the code that uses tuple types could be emitted without actually defining the type on disk. A custom "class loader" could then be defined that would dynamically generate the tuple type at runtime. That would allow static type checking inside the compiler, and would unify the tuple types across compilation boundaries.
Unfortunately, however, the CLR does not provide support for custom class loading. All loading in the CLR is done at the assembly level. It would be possible to define a separate assembly for each "constructed type", but that would very quickly lead to performance problems (having many assemblies with only one type in them would use too many resources).
**So, what I want to know is:**
Is it possible to simulate something like Java Class Loaders in .NET, where I can emit a reference to a non-existing type in and then dynamically generate a reference to that type at runtime before the code the needs to use it runs?
**NOTE:**
\*I actually already know the answer to the question, which I provide as an answer below. However, it took me about 3 days of research, and quite a bit of IL hacking in order to come up with a solution. I figured it would be a good idea to document it here in case anyone else ran into the same problem. \*
|
The answer is yes, but the solution is a little tricky.
The [`System.Reflection.Emit`](http://msdn.microsoft.com/en-us/library/system.reflection.emit.aspx) namespace defines types that allows assemblies to be generated dynamically. They also allow the generated assemblies to be defined incrementally. In other words it is possible to add types to the dynamic assembly, execute the generated code, and then latter add more types to the assembly.
The [`System.AppDomain`](http://msdn.microsoft.com/en-us/library/system.appdomain.aspx) class also defines an [AssemblyResolve](http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx) event that fires whenever the framework fails to load an assembly. By adding a handler for that event, it is possible to define a single "runtime" assembly into which all "constructed" types are placed. The code generated by the compiler that uses a constructed type would refer to a type in the runtime assembly. Because the runtime assembly doesn't actually exist on disk, the [AssemblyResolve](http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx) event would be fired the first time the compiled code tried to access a constructed type. The handle for the event would then generate the dynamic assembly and return it to the CLR.
Unfortunately, there are a few tricky points to getting this to work. The first problem is ensuring that the event handler will always be installed before the compiled code is run. With a console application this is easy. The code to hookup the event handler can just be added to the `Main` method before the other code runs. For class libraries, however, there is no main method. A dll may be loaded as part of an application written in another language, so it's not really possible to assume there is always a main method available to hookup the event handler code.
The second problem is ensuring that the referenced types all get inserted into the dynamic assembly before any code that references them is used. The [`System.AppDomain`](http://msdn.microsoft.com/en-us/library/system.appdomain.aspx) class also defines a [`TypeResolve`](http://msdn.microsoft.com/en-us/library/system.appdomain.typeresolve.aspx) event that is executed whenever the CLR is unable to resolve a type in a dynamic assembly. It gives the event handler the opportunity to define the type inside the dynamic assembly before the code that uses it runs. However, that event will not work in this case. The CLR will not fire the event for assemblies that are "statically referenced" by other assemblies, even if the referenced assembly is defined dynamically. This means that we need a way to run code before any other code in the compiled assembly runs and have it dynamically inject the types it needs into the runtime assembly if they have not already been defined. Otherwise when the CLR tried to load those types it will notice that the dynamic assembly does not contain the types they need and will throw a type load exception.
Fortunately, the CLR offers a solution to both problems: Module Initializers. A module initializer is the equivalent of a "static class constructor", except that it initializes an entire module, not just a single class. Baiscally, the CLR will:
1. Run the module constructor before any types inside the module are accessed.
2. Guarantee that only those types directly accessed by the module constructor will be loaded while it is executing
3. Not allow code outside the module to access any of it's members until after the constructor has finished.
It does this for all assemblies, including both class libraries and executables, and for EXEs will run the module constructor before executing the Main method.
See this [blog post](http://blogs.msdn.com/junfeng/archive/2005/11/19/494914.aspx) for more information about constructors.
In any case, a complete solution to my problem requires several pieces:
1. The following class definition, defined inside a "language runtime dll", that is referenced by all assemblies produced by the compiler (this is C# code).
```
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace SharedLib
{
public class Loader
{
private Loader(ModuleBuilder dynamicModule)
{
m_dynamicModule = dynamicModule;
m_definedTypes = new HashSet<string>();
}
private static readonly Loader m_instance;
private readonly ModuleBuilder m_dynamicModule;
private readonly HashSet<string> m_definedTypes;
static Loader()
{
var name = new AssemblyName("$Runtime");
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
var module = assemblyBuilder.DefineDynamicModule("$Runtime");
m_instance = new Loader(module);
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
if (args.Name == Instance.m_dynamicModule.Assembly.FullName)
{
return Instance.m_dynamicModule.Assembly;
}
else
{
return null;
}
}
public static Loader Instance
{
get
{
return m_instance;
}
}
public bool IsDefined(string name)
{
return m_definedTypes.Contains(name);
}
public TypeBuilder DefineType(string name)
{
//in a real system we would not expose the type builder.
//instead a AST for the type would be passed in, and we would just create it.
var type = m_dynamicModule.DefineType(name, TypeAttributes.Public);
m_definedTypes.Add(name);
return type;
}
}
}
```
The class defines a singleton that holds a reference to the dynamic assembly that the constructed types will be created in. It also holds a "hash set" that stores the set of types that have already been dynamically generated, and finally defines a member that can be used to define the type. This example just returns a System.Reflection.Emit.TypeBuilder instance that can then be used to define the class being generated. In a real system, the method would probably take in an AST representation of the class, and just do the generation it's self.
2. Compiled assemblies that emit the following two references (shown in ILASM syntax):
```
.assembly extern $Runtime
{
.ver 0:0:0:0
}
.assembly extern SharedLib
{
.ver 1:0:0:0
}
```
Here "SharedLib" is the Language's predefined runtime library that includes the "Loader" class defined above and "$Runtime" is the dynamic runtime assembly that the consructed types will be inserted into.
3. A "module constructor" inside every assembly compiled in the language.
As far as I know, there are no .NET languages that allow Module Constructors to be defined in source. The C++ /CLI compiler is the only compiler I know of that generates them. In IL, they look like this, defined directly in the module and not inside any type definitions:
```
.method privatescope specialname rtspecialname static
void .cctor() cil managed
{
//generate any constructed types dynamically here...
}
```
For me, It's not a problem that I have to write custom IL to get this to work. I'm writing a compiler, so code generation is not an issue.
In the case of an assembly that used the types `tuple<i as int, j as int>` and `tuple<x as double, y as double, z as double>` the module constructor would need to generate types like the following (here in C# syntax):
```
class Tuple_i_j<T, R>
{
public T i;
public R j;
}
class Tuple_x_y_z<T, R, S>
{
public T x;
public R y;
public S z;
}
```
The tuple classes are generated as generic types to get around accessibility issues. That would allow code in the compiled assembly to use `tuple<x as Foo>`, where Foo was some non-public type.
The body of the module constructor that did this (here only showing one type, and written in C# syntax) would look like this:
```
var loader = SharedLib.Loader.Instance;
lock (loader)
{
if (! loader.IsDefined("$Tuple_i_j"))
{
//create the type.
var Tuple_i_j = loader.DefineType("$Tuple_i_j");
//define the generic parameters <T,R>
var genericParams = Tuple_i_j.DefineGenericParameters("T", "R");
var T = genericParams[0];
var R = genericParams[1];
//define the field i
var fieldX = Tuple_i_j.DefineField("i", T, FieldAttributes.Public);
//define the field j
var fieldY = Tuple_i_j.DefineField("j", R, FieldAttributes.Public);
//create the default constructor.
var constructor= Tuple_i_j.DefineDefaultConstructor(MethodAttributes.Public);
//"close" the type so that it can be used by executing code.
Tuple_i_j.CreateType();
}
}
```
So in any case, this was the mechanism I was able to come up with to enable the rough equivalent of custom class loaders in the CLR.
Does anyone know of an easier way to do this?
|
185,844 |
<p>What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:</p>
<pre><code>class foo
{
private:
static int i;
};
int foo::i = 0;
</code></pre>
<p>I'm guessing this is because I can't initialize a private member from outside the class. So what's the best way to do this?</p>
|
[
{
"answer_id": 185848,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 10,
"selected": true,
"text": "<p>The class declaration should be in the header file (Or in the source file if not shared).<br>\nFile: foo.h</p>\n<pre><code>class foo\n{\n private:\n static int i;\n};\n</code></pre>\n<p>But the initialization should be in source file.<br>\nFile: foo.cpp</p>\n<pre><code>int foo::i = 0;\n</code></pre>\n<p>If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files.\nThe initialisation of the <code>static int i</code> must be done outside of any function.</p>\n<p><b>Note:</b> Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of <a href=\"https://en.cppreference.com/w/cpp/language/types\" rel=\"noreferrer\">const integer type</a> (<em><code>bool</code>, <code>char</code>, <code>char8_t</code> [since C++20], <code>char16_t</code>, <code>char32_t</code>, <code>wchar_t</code>, <code>short</code>, <code>int</code>, <code>long</code>, <code>long long</code>, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants.</em>). You can then declare and initialize the member variable directly inside the class declaration in the header file:</p>\n<pre><code>class foo\n{\n private:\n static int const i = 42;\n};\n</code></pre>\n"
},
{
"answer_id": 185863,
"author": "Matt Curtis",
"author_id": 17221,
"author_profile": "https://Stackoverflow.com/users/17221",
"pm_score": 7,
"selected": false,
"text": "<p>For a <strong>variable</strong>:</p>\n\n<p>foo.h:</p>\n\n<pre><code>class foo\n{\nprivate:\n static int i;\n};\n</code></pre>\n\n<p>foo.cpp:</p>\n\n<pre><code>int foo::i = 0;\n</code></pre>\n\n<p>This is because there can only be one instance of <code>foo::i</code> in your program. It's sort of the equivalent of <code>extern int i</code> in a header file and <code>int i</code> in a source file.</p>\n\n<p>For a <strong>constant</strong> you can put the value straight in the class declaration:</p>\n\n<pre><code>class foo\n{\nprivate:\n static int i;\n const static int a = 42;\n};\n</code></pre>\n"
},
{
"answer_id": 185864,
"author": "David Dibben",
"author_id": 5022,
"author_profile": "https://Stackoverflow.com/users/5022",
"pm_score": 4,
"selected": false,
"text": "<pre><code>int foo::i = 0; \n</code></pre>\n\n<p>Is the correct syntax for initializing the variable, but it must go in the source file (.cpp) rather than in the header. </p>\n\n<p>Because it is a static variable the compiler needs to create only one copy of it. You have to have a line \"int foo:i\" some where in your code to tell the compiler where to put it otherwise you get a link error. If that is in a header you will get a copy in every file that includes the header, so get multiply defined symbol errors from the linker. </p>\n"
},
{
"answer_id": 186042,
"author": "Johann Gerell",
"author_id": 6345,
"author_profile": "https://Stackoverflow.com/users/6345",
"pm_score": 5,
"selected": false,
"text": "<p>With a Microsoft compiler[1], static variables that are not <code>int</code>-like can also be defined in a header file, but outside of the class declaration, using the Microsoft specific <code>__declspec(selectany)</code>.</p>\n\n<pre><code>class A\n{\n static B b;\n}\n\n__declspec(selectany) A::b;\n</code></pre>\n\n<p>Note that I'm not saying this is good, I just say it can be done.</p>\n\n<p>[1] These days, more compilers than MSC support <code>__declspec(selectany)</code> - at least gcc and clang. Maybe even more.</p>\n"
},
{
"answer_id": 8772501,
"author": "monkey0506",
"author_id": 1136311,
"author_profile": "https://Stackoverflow.com/users/1136311",
"pm_score": 3,
"selected": false,
"text": "<p>I don't have enough rep here to add this as a comment, but IMO it's good style to write your headers with <a href=\"http://en.wikipedia.org/wiki/Include_guard\" rel=\"noreferrer\">#include guards</a> anyway, which as noted by Paranaix a few hours ago would prevent a multiple-definition error. Unless you're already using a separate CPP file, it's not necessary to use one just to initialize static non-integral members.</p>\n\n<pre><code>#ifndef FOO_H\n#define FOO_H\n#include \"bar.h\"\n\nclass foo\n{\nprivate:\n static bar i;\n};\n\nbar foo::i = VALUE;\n#endif\n</code></pre>\n\n<p>I see no need to use a separate CPP file for this. Sure, you can, but there's no technical reason why you should have to.</p>\n"
},
{
"answer_id": 14057180,
"author": "Joshua Clayton",
"author_id": 1419731,
"author_profile": "https://Stackoverflow.com/users/1419731",
"pm_score": 5,
"selected": false,
"text": "<p>For future viewers of this question, I want to point out that you should avoid what <a href=\"https://stackoverflow.com/a/8772501/5571184\">monkey0506 is suggesting</a>.</p>\n<p>Header files are for declarations.</p>\n<p>Header files get compiled once for every <code>.cpp</code> file that directly or indirectly <code>#includes</code> them, and code outside of any function is run at program initialization, before <code>main()</code>.</p>\n<p>By putting: <code>foo::i = VALUE;</code> into the header, <code>foo:i</code> will be assigned the value <code>VALUE</code> (whatever that is) for every <code>.cpp</code> file, and these assignments will happen in an indeterminate order (determined by the linker) before <code>main()</code> is run.</p>\n<p>What if we <code>#define VALUE</code> to be a different number in one of our <code>.cpp</code> files? It will compile fine and we will have no way of knowing which one wins until we run the program.</p>\n<p>Never put executed code into a header for the same reason that you never <code>#include</code> a <code>.cpp</code> file.</p>\n<p>Include guards (which I agree you should always use) protect you from something different: the same header being indirectly <code>#include</code>d multiple times while compiling a single <code>.cpp</code> file.</p>\n"
},
{
"answer_id": 15959493,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>You can also include the assignment in the header file if you use header guards. I have used this technique for a C++ library I have created. Another way to achieve the same result is to use static methods. For example...</p>\n\n<pre><code>class Foo\n {\n public:\n int GetMyStatic() const\n {\n return *MyStatic();\n }\n\n private:\n static int* MyStatic()\n {\n static int mStatic = 0;\n return &mStatic;\n }\n }\n</code></pre>\n\n<p>The above code has the \"bonus\" of not requiring a CPP/source file. Again, a method I use for my C++ libraries.</p>\n"
},
{
"answer_id": 20858946,
"author": "Alejadro Xalabarder",
"author_id": 1191101,
"author_profile": "https://Stackoverflow.com/users/1191101",
"pm_score": 2,
"selected": false,
"text": "<p>I follow the idea from Karl. I like it and now I use it as well. \nI've changed a little bit the notation and add some functionality</p>\n\n<pre><code>#include <stdio.h>\n\nclass Foo\n{\n public:\n\n int GetMyStaticValue () const { return MyStatic(); }\n int & GetMyStaticVar () { return MyStatic(); }\n static bool isMyStatic (int & num) { return & num == & MyStatic(); }\n\n private:\n\n static int & MyStatic ()\n {\n static int mStatic = 7;\n return mStatic;\n }\n};\n\nint main (int, char **)\n{\n Foo obj;\n\n printf (\"mystatic value %d\\n\", obj.GetMyStaticValue());\n obj.GetMyStaticVar () = 3;\n printf (\"mystatic value %d\\n\", obj.GetMyStaticValue());\n\n int valMyS = obj.GetMyStaticVar ();\n int & iPtr1 = obj.GetMyStaticVar ();\n int & iPtr2 = valMyS;\n\n printf (\"is my static %d %d\\n\", Foo::isMyStatic(iPtr1), Foo::isMyStatic(iPtr2));\n}\n</code></pre>\n\n<p>this outputs </p>\n\n<pre><code>mystatic value 7\nmystatic value 3\nis my static 1 0\n</code></pre>\n"
},
{
"answer_id": 21362729,
"author": "andrew",
"author_id": 1693143,
"author_profile": "https://Stackoverflow.com/users/1693143",
"pm_score": 2,
"selected": false,
"text": "<p>Also working in privateStatic.cpp file :</p>\n\n<pre><code>#include <iostream>\n\nusing namespace std;\n\nclass A\n{\nprivate:\n static int v;\n};\n\nint A::v = 10; // possible initializing\n\nint main()\n{\nA a;\n//cout << A::v << endl; // no access because of private scope\nreturn 0;\n}\n\n// g++ privateStatic.cpp -o privateStatic && ./privateStatic\n</code></pre>\n"
},
{
"answer_id": 23831857,
"author": "Arturo Ruiz Mañas",
"author_id": 3595315,
"author_profile": "https://Stackoverflow.com/users/3595315",
"pm_score": 2,
"selected": false,
"text": "<p>What about a <code>set_default()</code> method?</p>\n\n<pre><code>class foo\n{\n public:\n static void set_default(int);\n private:\n static int i;\n};\n\nvoid foo::set_default(int x) {\n i = x;\n}\n</code></pre>\n\n<p>We would only have to use the <code>set_default(int x)</code> method and our <code>static</code> variable would be initialized.</p>\n\n<p>This would not be in disagreement with the rest of the comments, actually it follows the same principle of initializing the variable in a global scope, but by using this method we make it explicit (and easy to see-understand) instead of having the definition of the variable hanging there.</p>\n"
},
{
"answer_id": 27088552,
"author": "Kris Kwiatkowski",
"author_id": 4284117,
"author_profile": "https://Stackoverflow.com/users/4284117",
"pm_score": 4,
"selected": false,
"text": "<p>If you want to initialize some compound type (f.e. string) you can do something like that:</p>\n\n<pre><code>class SomeClass {\n static std::list<string> _list;\n\n public:\n static const std::list<string>& getList() {\n struct Initializer {\n Initializer() {\n // Here you may want to put mutex\n _list.push_back(\"FIRST\");\n _list.push_back(\"SECOND\");\n ....\n }\n }\n static Initializer ListInitializationGuard;\n return _list;\n }\n};\n</code></pre>\n\n<p>As the <code>ListInitializationGuard</code> is a static variable inside <code>SomeClass::getList()</code> method it will be constructed only once, which means that constructor is called once. This will <code>initialize _list</code> variable to value you need. Any subsequent call to <code>getList</code> will simply return already initialized <code>_list</code> object.</p>\n\n<p>Of course you have to access <code>_list</code> object always by calling <code>getList()</code> method.</p>\n"
},
{
"answer_id": 39291737,
"author": "corporateAbaper",
"author_id": 2146694,
"author_profile": "https://Stackoverflow.com/users/2146694",
"pm_score": 0,
"selected": false,
"text": "<p>Does this serves your purpose?</p>\n\n<pre><code>//header file\n\nstruct MyStruct {\npublic:\n const std::unordered_map<std::string, uint32_t> str_to_int{\n { \"a\", 1 },\n { \"b\", 2 },\n ...\n { \"z\", 26 }\n };\n const std::unordered_map<int , std::string> int_to_str{\n { 1, \"a\" },\n { 2, \"b\" },\n ...\n { 26, \"z\" }\n };\n std::string some_string = \"justanotherstring\"; \n uint32_t some_int = 42;\n\n static MyStruct & Singleton() {\n static MyStruct instance;\n return instance;\n }\nprivate:\n MyStruct() {};\n};\n\n//Usage in cpp file\nint main(){\n std::cout<<MyStruct::Singleton().some_string<<std::endl;\n std::cout<<MyStruct::Singleton().some_int<<std::endl;\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 39802056,
"author": "Tyler Heers",
"author_id": 4905767,
"author_profile": "https://Stackoverflow.com/users/4905767",
"pm_score": 1,
"selected": false,
"text": "<p>I just wanted to mention something a little strange to me when I first encountered this.</p>\n\n<p>I needed to initialize a private static data member in a template class.</p>\n\n<p>in the .h or .hpp, it looks something like this to initialize a static data member of a template class:</p>\n\n<pre><code>template<typename T>\nType ClassName<T>::dataMemberName = initialValue;\n</code></pre>\n"
},
{
"answer_id": 45062055,
"author": "Die in Sente",
"author_id": 40756,
"author_profile": "https://Stackoverflow.com/users/40756",
"pm_score": 6,
"selected": false,
"text": "<p>Since C++17, static members may be defined in the header with the <strong>inline</strong> keyword.</p>\n\n<p><a href=\"http://en.cppreference.com/w/cpp/language/static\" rel=\"noreferrer\">http://en.cppreference.com/w/cpp/language/static</a></p>\n\n<p>\"A static data member may be declared inline. An inline static data member can be defined in the class definition and may specify a default member initializer. It does not need an out-of-class definition:\"</p>\n\n<pre><code>struct X\n{\n inline static int n = 1;\n};\n</code></pre>\n"
},
{
"answer_id": 46139631,
"author": "no one special",
"author_id": 5892157,
"author_profile": "https://Stackoverflow.com/users/5892157",
"pm_score": 3,
"selected": false,
"text": "<p>The linker problem you encountered is probably caused by:</p>\n\n<ul>\n<li>Providing both class and static member definition in header file,</li>\n<li>Including this header in two or more source files.</li>\n</ul>\n\n<p>This is a common problem for those who starts with C++. Static class member must be initialized in single translation unit i.e. in single source file.</p>\n\n<p>Unfortunately, the static class member must be initialized outside of the class body. This complicates writing header-only code, and, therefore, I am using quite different approach. You can provide your static object through static or non-static class function for example:</p>\n\n<pre><code>class Foo\n{\n // int& getObjectInstance() const {\n static int& getObjectInstance() {\n static int object;\n return object;\n }\n\n void func() {\n int &object = getValueInstance();\n object += 5;\n }\n};\n</code></pre>\n"
},
{
"answer_id": 48337288,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 4,
"selected": false,
"text": "<p><strong>C++11 static constructor pattern that works for multiple objects</strong></p>\n<p>One idiom was proposed at: <a href=\"https://stackoverflow.com/a/27088552/895245\">https://stackoverflow.com/a/27088552/895245</a> but here goes a cleaner version that does not require creating a new method per member.</p>\n<p>main.cpp</p>\n<pre><code>#include <cassert>\n#include <vector>\n\n// Normally on the .hpp file.\nclass MyClass {\npublic:\n static std::vector<int> v, v2;\n static struct StaticConstructor {\n StaticConstructor() {\n v.push_back(1);\n v.push_back(2);\n v2.push_back(3);\n v2.push_back(4);\n }\n } _staticConstructor;\n};\n\n// Normally on the .cpp file.\nstd::vector<int> MyClass::v;\nstd::vector<int> MyClass::v2;\n// Must come after every static member.\nMyClass::StaticConstructor MyClass::_staticConstructor;\n\nint main() {\n assert(MyClass::v[0] == 1);\n assert(MyClass::v[1] == 2);\n assert(MyClass::v2[0] == 3);\n assert(MyClass::v2[1] == 4);\n}\n</code></pre>\n<p><a href=\"https://github.com/cirosantilli/cpp-cheat/blob/45295e6acc4af330f79436b4cbb90f139e00a344/cpp/static_constructor_private.cpp\" rel=\"nofollow noreferrer\">GitHub upstream</a>.</p>\n<p>Compile and run:</p>\n<pre><code>g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp\n./main.out\n</code></pre>\n<p>See also: <a href=\"https://stackoverflow.com/questions/1197106/static-constructors-in-c-i-need-to-initialize-private-static-objects\">static constructors in C++? I need to initialize private static objects</a></p>\n<p>Tested on Ubuntu 19.04.</p>\n<p><strong>C++17 inline variable</strong></p>\n<p>Mentioned at: <a href=\"https://stackoverflow.com/a/45062055/895245\">https://stackoverflow.com/a/45062055/895245</a> but here is a multifile runnable example to make it even clearer: <a href=\"https://stackoverflow.com/questions/38043442/how-do-inline-variables-work/53896763#53896763\">How do inline variables work?</a></p>\n<p>This awesome C++17 feature allow us to:</p>\n<ul>\n<li>conveniently use just a single memory address for each constant</li>\n<li>store it as a <code>constexpr</code>: <a href=\"https://stackoverflow.com/questions/30208685/how-to-declare-constexpr-extern\">How to declare constexpr extern?</a></li>\n<li>do it in a single line from one header</li>\n</ul>\n<p>main.cpp</p>\n<pre><code>#include <cassert>\n\n#include "notmain.hpp"\n\nint main() {\n // Both files see the same memory address.\n assert(&notmain_i == notmain_func());\n assert(notmain_i == 42);\n}\n</code></pre>\n<p>notmain.hpp</p>\n<pre><code>#ifndef NOTMAIN_HPP\n#define NOTMAIN_HPP\n\ninline constexpr int notmain_i = 42;\n\nconst int* notmain_func();\n\n#endif\n</code></pre>\n<p>notmain.cpp</p>\n<pre><code>#include "notmain.hpp"\n\nconst int* notmain_func() {\n return &notmain_i;\n}\n</code></pre>\n<p>Compile and run:</p>\n<pre><code>g++ -c -o notmain.o -std=c++17 -Wall -Wextra -pedantic notmain.cpp\ng++ -c -o main.o -std=c++17 -Wall -Wextra -pedantic main.cpp\ng++ -o main -std=c++17 -Wall -Wextra -pedantic main.o notmain.o\n./main\n</code></pre>\n<p><a href=\"https://github.com/cirosantilli/cpp-cheat/tree/085c4b22b1b290a6d033a44958d05054e7e303c7/cpp/inline_variable\" rel=\"nofollow noreferrer\">GitHub upstream</a>.</p>\n"
},
{
"answer_id": 50846528,
"author": "anatolyg",
"author_id": 509868,
"author_profile": "https://Stackoverflow.com/users/509868",
"pm_score": 2,
"selected": false,
"text": "<p>One \"old-school\" way to define constants is to replace them by a <code>enum</code>:</p>\n\n<pre><code>class foo\n{\n private:\n enum {i = 0}; // default type = int\n enum: int64_t {HUGE = 1000000000000}; // may specify another type\n};\n</code></pre>\n\n<p>This way doesn't require providing a definition, and avoids making the constant <a href=\"https://stackoverflow.com/q/3601602/509868\">lvalue</a>, which can save you some headaches, e.g. when you accidentally <a href=\"https://stackoverflow.com/q/4209433/509868\">ODR-use</a> it.</p>\n"
},
{
"answer_id": 69280007,
"author": "cat",
"author_id": 712124,
"author_profile": "https://Stackoverflow.com/users/712124",
"pm_score": 2,
"selected": false,
"text": "<p>Here are all possibilities and errors in one simple example ...</p>\n<pre><code>#ifndef Foo_h\n#define Foo_h\n\nclass Foo\n{\n static const int a = 42; // OK\n static const int b {7}; // OK\n //static int x = 42; // ISO C++ forbids in-class initialization of non-const static member 'Foo::x'\n //static int y {7}; // ISO C++ forbids in-class initialization of non-const static member 'Foo::x'\n static int x;\n static int y;\n int m = 42;\n int n {7};\n};\n\n// Foo::x = 42; // error: 'int Foo::x' is private\nint Foo::x = 42; // OK in Foo.h if included in only one *.cpp -> *.o file!\nint Foo::y {7}; // OK\n\n// int Foo::y {7}; // error: redefinition of 'int Foo::y'\n // ONLY if the compiler can see both declarations at the same time it, \n // OTHERWISE you get a linker error\n\n#endif // Foo_h\n</code></pre>\n<p>But better place this in Foo.cpp. This way you can separately compile each file and link them later, otherwise Foo:x will be present in multiple object files and cause a linker error. ...</p>\n<pre><code>// Foo::x = 42; // error: 'int Foo::x' is private, bad if Foo::X is public!\nint Foo::x = 42; // OK in Foo.h if included in only one *.cpp -> *.o file!\nint Foo::y {7}; // OK\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:
```
class foo
{
private:
static int i;
};
int foo::i = 0;
```
I'm guessing this is because I can't initialize a private member from outside the class. So what's the best way to do this?
|
The class declaration should be in the header file (Or in the source file if not shared).
File: foo.h
```
class foo
{
private:
static int i;
};
```
But the initialization should be in source file.
File: foo.cpp
```
int foo::i = 0;
```
If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files.
The initialisation of the `static int i` must be done outside of any function.
**Note:** Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of [const integer type](https://en.cppreference.com/w/cpp/language/types) (*`bool`, `char`, `char8_t` [since C++20], `char16_t`, `char32_t`, `wchar_t`, `short`, `int`, `long`, `long long`, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants.*). You can then declare and initialize the member variable directly inside the class declaration in the header file:
```
class foo
{
private:
static int const i = 42;
};
```
|
185,934 |
<p>It appears that in PHP objects are passed by reference. Even assignment operators do not appear to be creating a copy of the Object.</p>
<p>Here's a simple, contrived proof:</p>
<pre><code><?php
class A {
public $b;
}
function set_b($obj) { $obj->b = "after"; }
$a = new A();
$a->b = "before";
$c = $a; //i would especially expect this to create a copy.
set_b($a);
print $a->b; //i would expect this to show 'before'
print $c->b; //i would ESPECIALLY expect this to show 'before'
?>
</code></pre>
<p>In both print cases I am getting 'after'</p>
<p>So, how do I pass <strong>$a</strong> to <strong><em>set_b()</em></strong> by value, not by reference?</p>
|
[
{
"answer_id": 185938,
"author": "Leo",
"author_id": 20689,
"author_profile": "https://Stackoverflow.com/users/20689",
"pm_score": 4,
"selected": false,
"text": "<p>According to the docs (<a href=\"http://ca3.php.net/language.oop5.cloning\" rel=\"noreferrer\">http://ca3.php.net/language.oop5.cloning</a>):</p>\n\n<pre><code>$a = clone $b;\n</code></pre>\n"
},
{
"answer_id": 185939,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 9,
"selected": true,
"text": "<p>In PHP 5+ objects are passed by reference. In PHP 4 they are passed by value (that's why it had runtime pass by reference, which became deprecated).</p>\n\n<p>You can use the 'clone' operator in PHP5 to copy objects:</p>\n\n<pre><code>$objectB = clone $objectA;\n</code></pre>\n\n<p>Also, it's just objects that are passed by reference, not everything as you've said in your question...</p>\n"
},
{
"answer_id": 186008,
"author": "yogman",
"author_id": 24349,
"author_profile": "https://Stackoverflow.com/users/24349",
"pm_score": 7,
"selected": false,
"text": "<p>The answers are commonly found in Java books.</p>\n\n<ol>\n<li><p>cloning:\nIf you don't override clone method, the default behavior is shallow copy. If your objects have only primitive member variables, it's totally ok. But in a typeless language with another object as member variables, it's a headache.</p></li>\n<li><p>serialization/deserialization</p></li>\n</ol>\n\n<p><code>$new_object = unserialize(serialize($your_object))</code></p>\n\n<p>This achieves deep copy with a heavy cost depending on the complexity of the object.</p>\n"
},
{
"answer_id": 186191,
"author": "Stanislav",
"author_id": 21504,
"author_profile": "https://Stackoverflow.com/users/21504",
"pm_score": 5,
"selected": false,
"text": "<p>According to previous comment, if you have another object as a member variable, do following:</p>\n\n<pre><code>class MyClass {\n private $someObject;\n\n public function __construct() {\n $this->someObject = new SomeClass();\n }\n\n public function __clone() {\n $this->someObject = clone $this->someObject;\n }\n\n}\n</code></pre>\n\n<p>Now you can do cloning:</p>\n\n<pre><code>$bar = new MyClass();\n$foo = clone $bar;\n</code></pre>\n"
},
{
"answer_id": 18337033,
"author": "diy_nunez",
"author_id": 2612387,
"author_profile": "https://Stackoverflow.com/users/2612387",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to fully copy properties of an object in a different instance, you may want to use this technique:</p>\n\n<p>Serialize it to JSON and then de-serialize it back to Object.</p>\n"
},
{
"answer_id": 19168638,
"author": "zloctb",
"author_id": 1673376,
"author_profile": "https://Stackoverflow.com/users/1673376",
"pm_score": 1,
"selected": false,
"text": "<p>This code help clone methods</p>\n\n<pre><code>class Foo{\n\n private $run=10;\n public $foo=array(2,array(2,8));\n public function hoo(){return 5;}\n\n\n public function __clone(){\n\n $this->boo=function(){$this->hoo();};\n\n }\n}\n$obj=new Foo;\n\n$news= clone $obj;\nvar_dump($news->hoo());\n</code></pre>\n"
},
{
"answer_id": 21317602,
"author": "Pyetro",
"author_id": 3229228,
"author_profile": "https://Stackoverflow.com/users/3229228",
"pm_score": 1,
"selected": false,
"text": "<p>I was doing some testing and got this:\n \n\n<pre><code>class A {\n public $property;\n}\n\nfunction set_property($obj) {\n $obj->property = \"after\";\n var_dump($obj);\n}\n\n$a = new A();\n$a->property = \"before\";\n\n// Creates a new Object from $a. Like \"new A();\"\n$b = new $a;\n// Makes a Copy of var $a, not referenced.\n$c = clone $a;\n\nset_property($a);\n// object(A)#1 (1) { [\"property\"]=> string(5) \"after\" }\n\nvar_dump($a); // Because function set_property get by reference\n// object(A)#1 (1) { [\"property\"]=> string(5) \"after\" }\nvar_dump($b);\n// object(A)#2 (1) { [\"property\"]=> NULL }\nvar_dump($c);\n// object(A)#3 (1) { [\"property\"]=> string(6) \"before\" }\n\n// Now creates a new obj A and passes to the function by clone (will copied)\n$d = new A();\n$d->property = \"before\";\n\nset_property(clone $d); // A new variable was created from $d, and not made a reference\n// object(A)#5 (1) { [\"property\"]=> string(5) \"after\" }\n\nvar_dump($d);\n// object(A)#4 (1) { [\"property\"]=> string(6) \"before\" }\n\n?>\n</code></pre>\n"
},
{
"answer_id": 30065558,
"author": "Patricio Rossi",
"author_id": 1902051,
"author_profile": "https://Stackoverflow.com/users/1902051",
"pm_score": 3,
"selected": false,
"text": "<p>Just to clarify PHP uses copy on write, so basically everything is a reference until you modify it, but for objects you need to use clone and the __clone() magic method like in the accepted answer.</p>\n"
},
{
"answer_id": 47100920,
"author": "Muhammad Ebrahim",
"author_id": 8726495,
"author_profile": "https://Stackoverflow.com/users/8726495",
"pm_score": 1,
"selected": false,
"text": "<p>In this example we will create <strong>iPhone</strong> class and make exact copy from it by <strong>cloning</strong></p>\n<pre><code>class iPhone\n{\n public $name;\n public $email;\n\n public function __construct($n, $e) {\n\n $this->name = $n;\n $this->email = $e;\n\n }\n}\n\n$main = new iPhone('Dark', '[email protected]');\n$copy = clone $main;\n\n// if you want to print both objects, just write this \n\necho "<pre>"; print_r($main); echo "</pre>";\necho "<pre>"; print_r($copy); echo "</pre>";\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4960/"
] |
It appears that in PHP objects are passed by reference. Even assignment operators do not appear to be creating a copy of the Object.
Here's a simple, contrived proof:
```
<?php
class A {
public $b;
}
function set_b($obj) { $obj->b = "after"; }
$a = new A();
$a->b = "before";
$c = $a; //i would especially expect this to create a copy.
set_b($a);
print $a->b; //i would expect this to show 'before'
print $c->b; //i would ESPECIALLY expect this to show 'before'
?>
```
In both print cases I am getting 'after'
So, how do I pass **$a** to ***set\_b()*** by value, not by reference?
|
In PHP 5+ objects are passed by reference. In PHP 4 they are passed by value (that's why it had runtime pass by reference, which became deprecated).
You can use the 'clone' operator in PHP5 to copy objects:
```
$objectB = clone $objectA;
```
Also, it's just objects that are passed by reference, not everything as you've said in your question...
|
185,936 |
<p>How can I delete the contents of a local folder in Python?</p>
<p>The current project is for Windows, but I would like to see *nix also.</p>
|
[
{
"answer_id": 185941,
"author": "Nick Stinemates",
"author_id": 4960,
"author_profile": "https://Stackoverflow.com/users/4960",
"pm_score": 10,
"selected": true,
"text": "<pre><code>import os, shutil\nfolder = '/path/to/folder'\nfor filename in os.listdir(folder):\n file_path = os.path.join(folder, filename)\n try:\n if os.path.isfile(file_path) or os.path.islink(file_path):\n os.unlink(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n except Exception as e:\n print('Failed to delete %s. Reason: %s' % (file_path, e))\n</code></pre>\n"
},
{
"answer_id": 186049,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 3,
"selected": false,
"text": "<p>You might be better off using <code>os.walk()</code> for this.</p>\n\n<p><code>os.listdir()</code> doesn't distinguish files from directories and you will quickly get into trouble trying to unlink these. There is a good example of using <code>os.walk()</code> to recursively remove a directory <a href=\"http://docs.python.org/library/os.html#os.walk\" rel=\"noreferrer\">here</a>, and hints on how to adapt it to your circumstances.</p>\n"
},
{
"answer_id": 186236,
"author": "Oli",
"author_id": 22035,
"author_profile": "https://Stackoverflow.com/users/22035",
"pm_score": 8,
"selected": false,
"text": "<p>You can delete the folder itself, as well as all its contents, using <a href=\"https://docs.python.org/library/shutil.html#shutil.rmtree\" rel=\"noreferrer\"><code>shutil.rmtree</code></a>:</p>\n\n<pre><code>import shutil\nshutil.rmtree('/path/to/folder')\n</code></pre>\n\n<blockquote>\n <code>shutil.<b>rmtree</b>(<i>path</i>, <i>ignore_errors=False</i>, <i>onerror=None</i>)</code>\n \n <p><br>\n Delete an entire directory tree; <em>path</em> must point to a directory (but not a symbolic link to a directory). If <em>ignore_errors</em> is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by <em>onerror</em> or, if that is omitted, they raise an exception.</p>\n</blockquote>\n"
},
{
"answer_id": 1073382,
"author": "Iker Jimenez",
"author_id": 2697,
"author_profile": "https://Stackoverflow.com/users/2697",
"pm_score": 7,
"selected": false,
"text": "<p>Expanding on mhawke's answer this is what I've implemented. It removes all the content of a folder but not the folder itself. Tested on Linux with files, folders and symbolic links, should work on Windows as well.</p>\n\n<pre><code>import os\nimport shutil\n\nfor root, dirs, files in os.walk('/path/to/folder'):\n for f in files:\n os.unlink(os.path.join(root, f))\n for d in dirs:\n shutil.rmtree(os.path.join(root, d))\n</code></pre>\n"
},
{
"answer_id": 5756937,
"author": "Blueicefield",
"author_id": 720691,
"author_profile": "https://Stackoverflow.com/users/720691",
"pm_score": 9,
"selected": false,
"text": "<p>You can simply do this:</p>\n\n<pre><code>import os\nimport glob\n\nfiles = glob.glob('/YOUR/PATH/*')\nfor f in files:\n os.remove(f)\n</code></pre>\n\n<p>You can of course use an other filter in you path, for example : /YOU/PATH/*.txt for removing all text files in a directory.</p>\n"
},
{
"answer_id": 6615332,
"author": "jgoeders",
"author_id": 609215,
"author_profile": "https://Stackoverflow.com/users/609215",
"pm_score": 6,
"selected": false,
"text": "<p>Using <code>rmtree</code> and recreating the folder could work, but I have run into errors when deleting and immediately recreating folders on network drives.</p>\n\n<p>The proposed solution using walk does not work as it uses <code>rmtree</code> to remove folders and then may attempt to use <code>os.unlink</code> on the files that were previously in those folders. This causes an error.</p>\n\n<p>The posted <code>glob</code> solution will also attempt to delete non-empty folders, causing errors.</p>\n\n<p>I suggest you use:</p>\n\n<pre><code>folder_path = '/path/to/folder'\nfor file_object in os.listdir(folder_path):\n file_object_path = os.path.join(folder_path, file_object)\n if os.path.isfile(file_object_path) or os.path.islink(file_object_path):\n os.unlink(file_object_path)\n else:\n shutil.rmtree(file_object_path)\n</code></pre>\n"
},
{
"answer_id": 12526809,
"author": "Jon Chu",
"author_id": 652602,
"author_profile": "https://Stackoverflow.com/users/652602",
"pm_score": 5,
"selected": false,
"text": "<p>This:</p>\n\n<ul>\n<li>removes all symbolic links\n\n<ul>\n<li>dead links</li>\n<li>links to directories</li>\n<li>links to files</li>\n</ul></li>\n<li>removes subdirectories</li>\n<li>does not remove the parent directory</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>for filename in os.listdir(dirpath):\n filepath = os.path.join(dirpath, filename)\n try:\n shutil.rmtree(filepath)\n except OSError:\n os.remove(filepath)\n</code></pre>\n\n<p>As many other answers, this does not try to adjust permissions to enable removal of files/directories.</p>\n"
},
{
"answer_id": 13666792,
"author": "Jacob Wan",
"author_id": 414524,
"author_profile": "https://Stackoverflow.com/users/414524",
"pm_score": 5,
"selected": false,
"text": "<p>Using <a href=\"https://docs.python.org/3/library/os.html#os.scandir.close\" rel=\"noreferrer\">os.scandir and context manager protocol</a> in Python 3.6+:</p>\n<pre><code>import os\nimport shutil\n\nwith os.scandir(target_dir) as entries:\n for entry in entries:\n if entry.is_dir() and not entry.is_symlink():\n shutil.rmtree(entry.path)\n else:\n os.remove(entry.path)\n</code></pre>\n<p>Earlier versions of Python:</p>\n<pre><code>import os\nimport shutil\n\n# Gather directory contents\ncontents = [os.path.join(target_dir, i) for i in os.listdir(target_dir)]\n\n# Iterate and remove each item in the appropriate manner\n[shutil.rmtree(i) if os.path.isdir(i) and not os.path.islink(i) else os.remove(i) for i in contents]\n</code></pre>\n"
},
{
"answer_id": 16340614,
"author": "Sawyer",
"author_id": 1633148,
"author_profile": "https://Stackoverflow.com/users/1633148",
"pm_score": 3,
"selected": false,
"text": "<p>I konw it's an old thread but I have found something interesting from the official site of python. Just for sharing another idea for removing of all contents in a directory. Because I have some problems of authorization when using shutil.rmtree() and I don't want to remove the directory and recreate it. The address original is <a href=\"http://docs.python.org/2/library/os.html#os.walk\" rel=\"nofollow\">http://docs.python.org/2/library/os.html#os.walk</a>. Hope that could help someone.</p>\n\n<pre><code>def emptydir(top):\n if(top == '/' or top == \"\\\\\"): return\n else:\n for root, dirs, files in os.walk(top, topdown=False):\n for name in files:\n os.remove(os.path.join(root, name))\n for name in dirs:\n os.rmdir(os.path.join(root, name))\n</code></pre>\n"
},
{
"answer_id": 17146855,
"author": "ProfHase85",
"author_id": 1945486,
"author_profile": "https://Stackoverflow.com/users/1945486",
"pm_score": 4,
"selected": false,
"text": "<p>I used to solve the problem this way:</p>\n\n<pre><code>import shutil\nimport os\n\nshutil.rmtree(dirpath)\nos.mkdir(dirpath)\n</code></pre>\n"
},
{
"answer_id": 20173900,
"author": "fmonegaglia",
"author_id": 1697732,
"author_profile": "https://Stackoverflow.com/users/1697732",
"pm_score": 4,
"selected": false,
"text": "<p>As a oneliner:</p>\n\n<pre><code>import os\n\n# Python 2.7\nmap( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) )\n\n# Python 3+\nlist( map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) ) )\n</code></pre>\n\n<p>A more robust solution accounting for files and directories as well would be (2.7):</p>\n\n<pre><code>def rm(f):\n if os.path.isdir(f): return os.rmdir(f)\n if os.path.isfile(f): return os.unlink(f)\n raise TypeError, 'must be either file or directory'\n\nmap( rm, (os.path.join( mydir,f) for f in os.listdir(mydir)) )\n</code></pre>\n"
},
{
"answer_id": 23614332,
"author": "Robin Winslow",
"author_id": 613540,
"author_profile": "https://Stackoverflow.com/users/613540",
"pm_score": 3,
"selected": false,
"text": "<p>Yet Another Solution:</p>\n\n<pre><code>import sh\nsh.rm(sh.glob('/path/to/folder/*'))\n</code></pre>\n"
},
{
"answer_id": 24844618,
"author": "Rockallite",
"author_id": 2293304,
"author_profile": "https://Stackoverflow.com/users/2293304",
"pm_score": 4,
"selected": false,
"text": "<p><em>Notes: in case someone down voted my answer, I have something to explain here.</em></p>\n\n<ol>\n<li>Everyone likes short 'n' simple answers. However, sometimes the reality is not so simple.</li>\n<li>Back to my answer. I know <code>shutil.rmtree()</code> could be used to delete a directory tree. I've used it many times in my own projects. But you must realize that <strong>the directory itself will also be deleted by <code>shutil.rmtree()</code></strong>. While this might be acceptable for some, it's not a valid answer for <strong>deleting the contents of a folder (without side effects)</strong>.</li>\n<li>I'll show you an example of the side effects. Suppose that you have a directory with <strong>customized</strong> owner and mode bits, where there are a lot of contents. Then you delete it with <code>shutil.rmtree()</code> and rebuild it with <code>os.mkdir()</code>. And you'll get an empty directory with <strong>default</strong> (inherited) owner and mode bits instead. While you might have the privilege to delete the contents and even the directory, you might not be able to set back the original owner and mode bits on the directory (e.g. you're not a superuser).</li>\n<li>Finally, <strong>be patient and read the code</strong>. It's long and ugly (in sight), but proven to be reliable and efficient (in use).</li>\n</ol>\n\n<hr>\n\n<p>Here's a long and ugly, but reliable and efficient solution.</p>\n\n<p>It resolves a few problems which are not addressed by the other answerers:</p>\n\n<ul>\n<li>It correctly handles symbolic links, including not calling <code>shutil.rmtree()</code> on a symbolic link (which will pass the <code>os.path.isdir()</code> test if it links to a directory; even the result of <code>os.walk()</code> contains symbolic linked directories as well).</li>\n<li>It handles read-only files nicely.</li>\n</ul>\n\n<p>Here's the code (the only useful function is <code>clear_dir()</code>):</p>\n\n<pre><code>import os\nimport stat\nimport shutil\n\n\n# http://stackoverflow.com/questions/1889597/deleting-directory-in-python\ndef _remove_readonly(fn, path_, excinfo):\n # Handle read-only files and directories\n if fn is os.rmdir:\n os.chmod(path_, stat.S_IWRITE)\n os.rmdir(path_)\n elif fn is os.remove:\n os.lchmod(path_, stat.S_IWRITE)\n os.remove(path_)\n\n\ndef force_remove_file_or_symlink(path_):\n try:\n os.remove(path_)\n except OSError:\n os.lchmod(path_, stat.S_IWRITE)\n os.remove(path_)\n\n\n# Code from shutil.rmtree()\ndef is_regular_dir(path_):\n try:\n mode = os.lstat(path_).st_mode\n except os.error:\n mode = 0\n return stat.S_ISDIR(mode)\n\n\ndef clear_dir(path_):\n if is_regular_dir(path_):\n # Given path is a directory, clear its content\n for name in os.listdir(path_):\n fullpath = os.path.join(path_, name)\n if is_regular_dir(fullpath):\n shutil.rmtree(fullpath, onerror=_remove_readonly)\n else:\n force_remove_file_or_symlink(fullpath)\n else:\n # Given path is a file or a symlink.\n # Raise an exception here to avoid accidentally clearing the content\n # of a symbolic linked directory.\n raise OSError(\"Cannot call clear_dir() on a symbolic link\")\n</code></pre>\n"
},
{
"answer_id": 37926786,
"author": "B. Filer",
"author_id": 5914737,
"author_profile": "https://Stackoverflow.com/users/5914737",
"pm_score": -1,
"selected": false,
"text": "<p>This should do the trick just using the OS module to list and then remove!</p>\n\n<pre><code>import os\nDIR = os.list('Folder')\nfor i in range(len(DIR)):\n os.remove('Folder'+chr(92)+i)\n</code></pre>\n\n<p>Worked for me, any problems let me know! </p>\n"
},
{
"answer_id": 41343815,
"author": "fmonegaglia",
"author_id": 1697732,
"author_profile": "https://Stackoverflow.com/users/1697732",
"pm_score": 1,
"selected": false,
"text": "<p>Answer for a limited, specific situation:\nassuming you want to delete the files while maintainig the subfolders tree, you could use a recursive algorithm:</p>\n\n<pre><code>import os\n\ndef recursively_remove_files(f):\n if os.path.isfile(f):\n os.unlink(f)\n elif os.path.isdir(f):\n for fi in os.listdir(f):\n recursively_remove_files(os.path.join(f, fi))\n\nrecursively_remove_files(my_directory)\n</code></pre>\n\n<p>Maybe slightly off-topic, but I think many would find it useful</p>\n"
},
{
"answer_id": 42932517,
"author": "physlexic",
"author_id": 7654548,
"author_profile": "https://Stackoverflow.com/users/7654548",
"pm_score": -1,
"selected": false,
"text": "<p>I resolved the issue with <code>rmtree</code> <code>makedirs</code> by adding <code>time.sleep()</code> between:</p>\n\n<pre><code>if os.path.isdir(folder_location):\n shutil.rmtree(folder_location)\n\ntime.sleep(.5)\n\nos.makedirs(folder_location, 0o777)\n</code></pre>\n"
},
{
"answer_id": 50813297,
"author": "silverbullettt",
"author_id": 1277994,
"author_profile": "https://Stackoverflow.com/users/1277994",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using a *nix system, why not leverage the system command?</p>\n\n<pre><code>import os\npath = 'folder/to/clean'\nos.system('rm -rf %s/*' % path)\n</code></pre>\n"
},
{
"answer_id": 54501104,
"author": "amrezzd",
"author_id": 8460132,
"author_profile": "https://Stackoverflow.com/users/8460132",
"pm_score": 1,
"selected": false,
"text": "<p>Use the method bellow to remove the contents of a directory, not the directory itself:</p>\n\n<pre><code>import os\nimport shutil\n\ndef remove_contents(path):\n for c in os.listdir(path):\n full_path = os.path.join(path, c)\n if os.path.isfile(full_path):\n os.remove(full_path)\n else:\n shutil.rmtree(full_path)\n</code></pre>\n"
},
{
"answer_id": 54889532,
"author": "Kevin Patel",
"author_id": 6920365,
"author_profile": "https://Stackoverflow.com/users/6920365",
"pm_score": 4,
"selected": false,
"text": "<p>To delete all the files inside the directory as well as its sub-directories, without removing the folders themselves, simply do this:</p>\n<pre><code>import os\nmypath = "my_folder" #Enter your path here\nfor root, dirs, files in os.walk(mypath, topdown=False):\n for file in files:\n os.remove(os.path.join(root, file))\n\n # Add this block to remove folders\n for dir in dirs:\n os.rmdir(os.path.join(root, dir))\n\n# Add this line to remove the root folder at the end\nos.rmdir(mypath)\n</code></pre>\n"
},
{
"answer_id": 56151260,
"author": "Husky",
"author_id": 152809,
"author_profile": "https://Stackoverflow.com/users/152809",
"pm_score": 6,
"selected": false,
"text": "<p>I'm surprised nobody has mentioned the awesome <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"noreferrer\"><code>pathlib</code></a> to do this job.</p>\n<p>If you only want to remove files in a directory it can be a oneliner</p>\n<pre><code>from pathlib import Path\n\n[f.unlink() for f in Path("/path/to/folder").glob("*") if f.is_file()] \n</code></pre>\n<p>To also recursively remove directories you can write something like this:</p>\n<pre><code>from pathlib import Path\nfrom shutil import rmtree\n\nfor path in Path("/path/to/folder").glob("**/*"):\n if path.is_file():\n path.unlink()\n elif path.is_dir():\n rmtree(path)\n</code></pre>\n"
},
{
"answer_id": 57216839,
"author": "Manrique",
"author_id": 8947739,
"author_profile": "https://Stackoverflow.com/users/8947739",
"pm_score": 2,
"selected": false,
"text": "<p>Pretty intuitive way of doing it:</p>\n\n<pre><code>import shutil, os\n\n\ndef remove_folder_contents(path):\n shutil.rmtree(path)\n os.makedirs(path)\n\n\nremove_folder_contents('/path/to/folder')\n</code></pre>\n"
},
{
"answer_id": 57278153,
"author": "PyBoss",
"author_id": 10530575,
"author_profile": "https://Stackoverflow.com/users/10530575",
"pm_score": -1,
"selected": false,
"text": "<p>the easiest way to delete all files in a folder/remove all files</p>\n\n<pre><code>import os\nfiles = os.listdir(yourFilePath)\nfor f in files:\n os.remove(yourFilePath + f)\n</code></pre>\n"
},
{
"answer_id": 58699534,
"author": "Kush Modi",
"author_id": 11418523,
"author_profile": "https://Stackoverflow.com/users/11418523",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I think this code is working. It will not delete the folder and you can use this code to delete files having the particular extension. </p>\n\n<pre><code>import os\nimport glob\n\nfiles = glob.glob(r'path/*')\nfor items in files:\n os.remove(items)\n</code></pre>\n"
},
{
"answer_id": 59694006,
"author": "NicoBar",
"author_id": 9937135,
"author_profile": "https://Stackoverflow.com/users/9937135",
"pm_score": 3,
"selected": false,
"text": "<p>I had to remove files from 3 separate folders inside a single parent directory:</p>\n\n<pre><code>directory\n folderA\n file1\n folderB\n file2\n folderC\n file3\n</code></pre>\n\n<p>This simple code did the trick for me: (I'm on Unix)</p>\n\n<pre><code>import os\nimport glob\n\nfolders = glob.glob('./path/to/parentdir/*')\nfor fo in folders:\n file = glob.glob(f'{fo}/*')\n for f in file:\n os.remove(f)\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 67509624,
"author": "andrec",
"author_id": 10652661,
"author_profile": "https://Stackoverflow.com/users/10652661",
"pm_score": 4,
"selected": false,
"text": "<p>To delete all files inside a folder a I use:</p>\n<pre><code>import os\nfor i in os.listdir():\n os.remove(i)\n</code></pre>\n"
},
{
"answer_id": 73777103,
"author": "dazzafact",
"author_id": 1163485,
"author_profile": "https://Stackoverflow.com/users/1163485",
"pm_score": 0,
"selected": false,
"text": "<p>use this function</p>\n<pre><code>import glob\n\ndef truncate(path):\n files = glob.glob(path+'/*.*')\n for f in files:\n os.remove(f)\n\ntruncate('/my/path')\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
How can I delete the contents of a local folder in Python?
The current project is for Windows, but I would like to see \*nix also.
|
```
import os, shutil
folder = '/path/to/folder'
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))
```
|
185,937 |
<p>I ran into an interesting (and very frustrating) issue with the <code>equals()</code> method today which caused what I thought to be a well tested class to crash and cause a bug that took me a very long time to track down. </p>
<p>Just for completeness, I wasn't using an IDE or debugger - just good old fashioned text editor and System.out's. Time was very limited and it was a school project.</p>
<p>Anyhow - </p>
<p>I was developing a basic shopping cart which could contain an <em><code>ArrayList</code> of <code>Book</code> objects</em>. In order to implement the <code>addBook()</code>, <code>removeBook()</code>, and <code>hasBook()</code> methods of the Cart, I wanted to check if the <code>Book</code> already existed in the <code>Cart</code>. So off I go -</p>
<pre><code>public boolean equals(Book b) {
... // More code here - null checks
if (b.getID() == this.getID()) return true;
else return false;
}
</code></pre>
<p>All works fine in testing. I create 6 objects and fill them with data. Do many adds, removes, has() operations on the <code>Cart</code> and everything works fine. I read that you can <em>either have <code>equals(TYPE var)</code> or <code>equals(Object o) { (CAST) var }</code></em> but assumed that since it was working, it didn't matter too much.</p>
<p>Then I ran into a problem - I needed to create a <code>Book</code> object with <em>only</em> the <code>ID</code> in it from within the Book class. No other data would be entered into it. Basically the following:</p>
<pre><code>public boolean hasBook(int i) {
Book b = new Book(i);
return hasBook(b);
}
public boolean hasBook(Book b) {
// .. more code here
return this.books.contains(b);
}
</code></pre>
<p>All of a sudden, the <code>equals(Book b)</code> method no longer works. This took a VERY long time to track down without a good debugger and assuming the <code>Cart</code> class was properly tested and correct. After swaapping the <code>equals()</code> method to the following:</p>
<pre><code>public boolean equals(Object o) {
Book b = (Book) o;
... // The rest goes here
}
</code></pre>
<p>Everything began to work again. Is there a reason the method decided not to take the Book parameter even though it clearly <b> was </b> a <code>Book</code> object? The only difference seemed to be it was instantiated from within the same class, and only filled with one data member. I'm very very confused. Please, shed some light?</p>
|
[
{
"answer_id": 185942,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 9,
"selected": true,
"text": "<p>In Java, the <code>equals()</code> method that is inherited from <code>Object</code> is:</p>\n\n<pre><code>public boolean equals(Object other);\n</code></pre>\n\n<p>In other words, the parameter must be of type <code>Object</code>. This is called <em>overriding</em>; your method <code>public boolean equals(Book other)</code> does what is called <em>overloading</em> to the <code>equals()</code> method.</p>\n\n<p>The <code>ArrayList</code> uses overridden <code>equals()</code> methods to compare contents (e.g. for its <code>contains()</code> and <code>equals()</code> methods), <strong>not</strong> overloaded ones. In most of your code, calling the one that didn't properly override <code>Object</code>'s equals was fine, but not compatible with <code>ArrayList</code>.</p>\n\n<p>So, not overriding the method correctly can cause problems.</p>\n\n<p>I override equals the following everytime:</p>\n\n<pre><code>@Override\npublic boolean equals(Object other){\n if (other == null) return false;\n if (other == this) return true;\n if (!(other instanceof MyClass)) return false;\n MyClass otherMyClass = (MyClass)other;\n ...test other properties here...\n}\n</code></pre>\n\n<p>The use of the <code>@Override</code> annotation can help a ton with silly mistakes.</p>\n\n<p>Use it whenever you think you are overriding a super class' or interface's method. That way, if you do it the wrong way, you will get a compile error.</p>\n"
},
{
"answer_id": 186409,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Slightly off-topic to your question, but it's probably worth mentioning anyway:</p>\n\n<p><a href=\"http://commons.apache.org/lang\" rel=\"noreferrer\">Commons Lang</a> has got some excellent methods you can use in overriding equals and hashcode. Check out <a href=\"http://commons.apache.org/lang/api-release/org/apache/commons/lang/builder/EqualsBuilder.html#reflectionEquals(java.lang.Object,%20java.lang.Object)\" rel=\"noreferrer\">EqualsBuilder.reflectionEquals(...)</a> and <a href=\"http://commons.apache.org/lang/api-release/org/apache/commons/lang/builder/HashCodeBuilder.html#reflectionHashCode(java.lang.Object)\" rel=\"noreferrer\">HashCodeBuilder.reflectionHashCode(...)</a>. Saved me plenty of headache in the past - although of course if you just want to do \"equals\" on ID it may not fit your circumstances.</p>\n\n<p>I also agree that you should use the <code>@Override</code> annotation whenever you're overriding equals (or any other method).</p>\n"
},
{
"answer_id": 6217211,
"author": "Fred",
"author_id": 423226,
"author_profile": "https://Stackoverflow.com/users/423226",
"pm_score": 7,
"selected": false,
"text": "<p>If you use eclipse just go to the top menu </p>\n\n<blockquote>\n <p>Source --> Generate equals() and\n hashCode()</p>\n</blockquote>\n"
},
{
"answer_id": 26423986,
"author": "borjab",
"author_id": 16206,
"author_profile": "https://Stackoverflow.com/users/16206",
"pm_score": 3,
"selected": false,
"text": "<p>Another fast solution that saves boilerplate code is <a href=\"http://projectlombok.org/features/EqualsAndHashCode.html\" rel=\"noreferrer\">Lombok EqualsAndHashCode annotation</a>. It is easy, elegant and customizable. And <strong>does not depends on the IDE</strong>. For example;</p>\n\n<pre><code>import lombok.EqualsAndHashCode;\n\n@EqualsAndHashCode(of={\"errorNumber\",\"messageCode\"}) // Will only use this fields to generate equals.\npublic class ErrorMessage{\n\n private long errorNumber;\n private int numberOfParameters;\n private Level loggingLevel;\n private String messageCode;\n</code></pre>\n\n<p>See the <a href=\"http://projectlombok.org/api/lombok/EqualsAndHashCode.html\" rel=\"noreferrer\">options</a> avaliable to customize which fields to use in the equals. Lombok is avalaible in <a href=\"http://mvnrepository.com/artifact/org.projectlombok/lombok\" rel=\"noreferrer\">maven</a>. Just add it with <em>provided</em> scope:</p>\n\n<pre><code><dependency>\n <groupId>org.projectlombok</groupId>\n <artifactId>lombok</artifactId>\n <version>1.14.8</version>\n <scope>provided</scope>\n</dependency>\n</code></pre>\n"
},
{
"answer_id": 28237208,
"author": "Nikel8000",
"author_id": 4511678,
"author_profile": "https://Stackoverflow.com/users/4511678",
"pm_score": 0,
"selected": false,
"text": "<p>the <code>instanceOf</code> statement is often used in implementation of equals.</p>\n\n<p>This is a popular pitfall !</p>\n\n<p>The problem is that using <code>instanceOf</code> violates the rule of symmetry:</p>\n\n<p><code>(object1.equals(object2) == true)</code> <strong>if and only if</strong> <code>(object2.equals(object1))</code></p>\n\n<p>if the first equals is true, and object2 is an instance of a subclass of\nthe class where obj1 belongs to, then the second equals will return false!</p>\n\n<p>if the regarded class where ob1 belongs to is declared as final, then this\nproblem can not arise, but in general, you should test as follows:</p>\n\n<p><code>this.getClass() != otherObject.getClass();</code> if not, return false, otherwise test\nthe fields to compare for equality!</p>\n"
},
{
"answer_id": 32152777,
"author": "David Hackro",
"author_id": 3741698,
"author_profile": "https://Stackoverflow.com/users/3741698",
"pm_score": 1,
"selected": false,
"text": "<p>in Android Studio is\nalt + insert ---> equals and hashCode</p>\n\n<p>Example:</p>\n\n<pre><code> @Override\npublic boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Proveedor proveedor = (Proveedor) o;\n\n return getId() == proveedor.getId();\n\n}\n\n@Override\npublic int hashCode() {\n return getId();\n}\n</code></pre>\n"
},
{
"answer_id": 32182121,
"author": "vootla561",
"author_id": 2831046,
"author_profile": "https://Stackoverflow.com/users/2831046",
"pm_score": -1,
"selected": false,
"text": "<p>recordId is property of the object</p>\n\n<pre><code>@Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n Nai_record other = (Nai_record) obj;\n if (recordId == null) {\n if (other.recordId != null)\n return false;\n } else if (!recordId.equals(other.recordId))\n return false;\n return true;\n }\n</code></pre>\n"
},
{
"answer_id": 32487857,
"author": "bcsb1001",
"author_id": 3529323,
"author_profile": "https://Stackoverflow.com/users/3529323",
"pm_score": 1,
"selected": false,
"text": "<p>Consider:</p>\n\n<pre><code>Object obj = new Book();\nobj.equals(\"hi\");\n// Oh noes! What happens now? Can't call it with a String that isn't a Book...\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10583/"
] |
I ran into an interesting (and very frustrating) issue with the `equals()` method today which caused what I thought to be a well tested class to crash and cause a bug that took me a very long time to track down.
Just for completeness, I wasn't using an IDE or debugger - just good old fashioned text editor and System.out's. Time was very limited and it was a school project.
Anyhow -
I was developing a basic shopping cart which could contain an *`ArrayList` of `Book` objects*. In order to implement the `addBook()`, `removeBook()`, and `hasBook()` methods of the Cart, I wanted to check if the `Book` already existed in the `Cart`. So off I go -
```
public boolean equals(Book b) {
... // More code here - null checks
if (b.getID() == this.getID()) return true;
else return false;
}
```
All works fine in testing. I create 6 objects and fill them with data. Do many adds, removes, has() operations on the `Cart` and everything works fine. I read that you can *either have `equals(TYPE var)` or `equals(Object o) { (CAST) var }`* but assumed that since it was working, it didn't matter too much.
Then I ran into a problem - I needed to create a `Book` object with *only* the `ID` in it from within the Book class. No other data would be entered into it. Basically the following:
```
public boolean hasBook(int i) {
Book b = new Book(i);
return hasBook(b);
}
public boolean hasBook(Book b) {
// .. more code here
return this.books.contains(b);
}
```
All of a sudden, the `equals(Book b)` method no longer works. This took a VERY long time to track down without a good debugger and assuming the `Cart` class was properly tested and correct. After swaapping the `equals()` method to the following:
```
public boolean equals(Object o) {
Book b = (Book) o;
... // The rest goes here
}
```
Everything began to work again. Is there a reason the method decided not to take the Book parameter even though it clearly **was** a `Book` object? The only difference seemed to be it was instantiated from within the same class, and only filled with one data member. I'm very very confused. Please, shed some light?
|
In Java, the `equals()` method that is inherited from `Object` is:
```
public boolean equals(Object other);
```
In other words, the parameter must be of type `Object`. This is called *overriding*; your method `public boolean equals(Book other)` does what is called *overloading* to the `equals()` method.
The `ArrayList` uses overridden `equals()` methods to compare contents (e.g. for its `contains()` and `equals()` methods), **not** overloaded ones. In most of your code, calling the one that didn't properly override `Object`'s equals was fine, but not compatible with `ArrayList`.
So, not overriding the method correctly can cause problems.
I override equals the following everytime:
```
@Override
public boolean equals(Object other){
if (other == null) return false;
if (other == this) return true;
if (!(other instanceof MyClass)) return false;
MyClass otherMyClass = (MyClass)other;
...test other properties here...
}
```
The use of the `@Override` annotation can help a ton with silly mistakes.
Use it whenever you think you are overriding a super class' or interface's method. That way, if you do it the wrong way, you will get a compile error.
|
185,947 |
<p>As a programming exercise, I've written a Ruby snippet that creates a class, instantiates two objects from that class, monkeypatches one object, and relies on method_missing to monkeypatch the other one.</p>
<p>Here's the deal. This works as intended:</p>
<pre><code>class Monkey
def chatter
puts "I am a chattering monkey!"
end
def method_missing(m)
puts "No #{m}, so I'll make one..."
def screech
puts "This is the new screech."
end
end
end
m1 = Monkey.new
m2 = Monkey.new
m1.chatter
m2.chatter
def m1.screech
puts "Aaaaaargh!"
end
m1.screech
m2.screech
m2.screech
m1.screech
m2.screech
</code></pre>
<p>You'll notice that I have a parameter for method_missing. I did this because I was hoping to use define_method to dynamically create missing methods with the appropriate name. However, it doesn't work. In fact, even using define_method with a static name like so:</p>
<pre><code>def method_missing(m)
puts "No #{m}, so I'll make one..."
define_method(:screech) do
puts "This is the new screech."
end
end
</code></pre>
<p>Ends with the following result: </p>
<pre><code>ArgumentError: wrong number of arguments (2 for 1)
method method_missing in untitled document at line 9
method method_missing in untitled document at line 9
at top level in untitled document at line 26
Program exited.
</code></pre>
<p>What makes the error message more bewildering is that I only have one argument for <code>method_missing</code>...</p>
|
[
{
"answer_id": 185969,
"author": "Avdi",
"author_id": 20487,
"author_profile": "https://Stackoverflow.com/users/20487",
"pm_score": 8,
"selected": true,
"text": "<p><code>define_method</code> is a (private) method of the object <em>Class</em>. You are calling it from an <em>instance</em>. There is no instance method called <code>define_method</code>, so it recurses to your <code>method_missing</code>, this time with <code>:define_method</code> (the name of the missing method), and <code>:screech</code> (the sole argument you passed to <code>define_method</code>).</p>\n\n<p>Try this instead (to define the new method on all Monkey objects):</p>\n\n<pre><code>def method_missing(m)\n puts \"No #{m}, so I'll make one...\"\n self.class.send(:define_method, :screech) do\n puts \"This is the new screech.\"\n end\nend\n</code></pre>\n\n<p>Or this (to define it only on the object it is called upon, using the object's \"eigenclass\"):</p>\n\n<pre><code>def method_missing(m)\n puts \"No #{m}, so I'll make one...\"\n class << self\n define_method(:screech) do\n puts \"This is the new screech.\"\n end\n end\nend\n</code></pre>\n"
},
{
"answer_id": 242106,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>self.class.define_method(:screech) doesn't work,because define_method is private method\nyou can do that</p>\n\n<pre><code>class << self\n public :define_method\nend\ndef method_missing(m)\nputs \"No #{m}, so I'll make one...\"\nMonkey.define_method(:screech) do\n puts \"This is the new screech.\"\nend\n</code></pre>\n"
},
{
"answer_id": 3581388,
"author": "Andrew",
"author_id": 432558,
"author_profile": "https://Stackoverflow.com/users/432558",
"pm_score": 2,
"selected": false,
"text": "<pre><code>def method_missing(m)\n self.class.class_exec do\n define_method(:screech) {puts \"This is the new screech.\"}\n end \nend\n</code></pre>\n\n<p>screech method will be available for all Monkey objects.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21493/"
] |
As a programming exercise, I've written a Ruby snippet that creates a class, instantiates two objects from that class, monkeypatches one object, and relies on method\_missing to monkeypatch the other one.
Here's the deal. This works as intended:
```
class Monkey
def chatter
puts "I am a chattering monkey!"
end
def method_missing(m)
puts "No #{m}, so I'll make one..."
def screech
puts "This is the new screech."
end
end
end
m1 = Monkey.new
m2 = Monkey.new
m1.chatter
m2.chatter
def m1.screech
puts "Aaaaaargh!"
end
m1.screech
m2.screech
m2.screech
m1.screech
m2.screech
```
You'll notice that I have a parameter for method\_missing. I did this because I was hoping to use define\_method to dynamically create missing methods with the appropriate name. However, it doesn't work. In fact, even using define\_method with a static name like so:
```
def method_missing(m)
puts "No #{m}, so I'll make one..."
define_method(:screech) do
puts "This is the new screech."
end
end
```
Ends with the following result:
```
ArgumentError: wrong number of arguments (2 for 1)
method method_missing in untitled document at line 9
method method_missing in untitled document at line 9
at top level in untitled document at line 26
Program exited.
```
What makes the error message more bewildering is that I only have one argument for `method_missing`...
|
`define_method` is a (private) method of the object *Class*. You are calling it from an *instance*. There is no instance method called `define_method`, so it recurses to your `method_missing`, this time with `:define_method` (the name of the missing method), and `:screech` (the sole argument you passed to `define_method`).
Try this instead (to define the new method on all Monkey objects):
```
def method_missing(m)
puts "No #{m}, so I'll make one..."
self.class.send(:define_method, :screech) do
puts "This is the new screech."
end
end
```
Or this (to define it only on the object it is called upon, using the object's "eigenclass"):
```
def method_missing(m)
puts "No #{m}, so I'll make one..."
class << self
define_method(:screech) do
puts "This is the new screech."
end
end
end
```
|
185,965 |
<p>What is the best way to create a custom title for pages in a Rails app without using a plug-in?</p>
|
[
{
"answer_id": 185973,
"author": "Avdi",
"author_id": 20487,
"author_profile": "https://Stackoverflow.com/users/20487",
"pm_score": 4,
"selected": false,
"text": "<p>Look into <code>content_for</code>: <a href=\"http://railscasts.com/episodes/8\" rel=\"noreferrer\">http://railscasts.com/episodes/8</a></p>\n"
},
{
"answer_id": 185978,
"author": "Alan",
"author_id": 17205,
"author_profile": "https://Stackoverflow.com/users/17205",
"pm_score": 3,
"selected": false,
"text": "<p>Without further details on the use-case or requirements that you're trying to satisfy, I can think of several alternatives:</p>\n\n<p>1) Switch the title in one of your layout pages and consume a helper method stored in <code>application_helper.rb</code></p>\n\n<pre><code><title><%= custom_title %></title>\n</code></pre>\n\n<p>This approach will give you a unique title for each layout page.</p>\n\n<p>2) Railscasts suggests using a partial to load what shows up between the HEAD tags</p>\n\n<p>3) Use javascript/ajax calls to manipulate the DOM if you need to change the title after the load event.</p>\n\n<p>Maybe you don't really want to change the content tagged by the <code>title</code> element. Perhaps you really need a breadcrumb of some sort, so that your users always know where they are with respect to your site's navigation hierarchy. While I've done fine with how the goldberg plugin, I'm sure there are other ways of pulling off the same functionality.</p>\n"
},
{
"answer_id": 185980,
"author": "Aupajo",
"author_id": 10407,
"author_profile": "https://Stackoverflow.com/users/10407",
"pm_score": 6,
"selected": false,
"text": "<p>Best practice is to use content_for.</p>\n\n<p>First, add a couple of helper methods (ie. stick in app/helpers/application_helper.rb):</p>\n\n<pre><code>def page_title(separator = \" – \")\n [content_for(:title), 'My Cool Site'].compact.join(separator)\nend\n\ndef page_heading(title)\n content_for(:title){ title }\n content_tag(:h1, title)\nend\n</code></pre>\n\n<p>Then in your layout view you can simply use:</p>\n\n<pre><code><title><%= page_title %></title>\n</code></pre>\n\n<p>...and in the view itself:</p>\n\n<pre><code><%= page_heading \"Awesome\" %>\n</code></pre>\n\n<p>This way has the advantage of allowing you to shuffle where you stick the h1 tag for your title, and keeps your controller nice and free of pesky @title variables.</p>\n"
},
{
"answer_id": 186227,
"author": "JasonOng",
"author_id": 6048,
"author_profile": "https://Stackoverflow.com/users/6048",
"pm_score": 2,
"selected": false,
"text": "<p>You can also set it in a before_filter in your controller.</p>\n\n<pre><code># foo_controller.rb\n\nclass FooController < ApplicationController\n\n before_filter :set_title\n\n private\n\n def set_title\n @page_title = \"Foo Page\"\n end\n\nend\n\n# application.html.erb\n\n<h1><%= page_title %></h1>\n</code></pre>\n\n<p>You can then set conditions in the <strong>set_title</strong> method to set a different titles for different actions in the controller. It's nice to be able to see all the relevant page titles within your controller.</p>\n"
},
{
"answer_id": 186508,
"author": "Christoph Schiessl",
"author_id": 20467,
"author_profile": "https://Stackoverflow.com/users/20467",
"pm_score": 9,
"selected": true,
"text": "<p>In your views do something like this:</p>\n\n<pre><code><% content_for :title, \"Title for specific page\" %>\n<!-- or -->\n<h1><%= content_for(:title, \"Title for specific page\") %></h1>\n</code></pre>\n\n<p>The following goes in the layout file:</p>\n\n<pre><code><head>\n <title><%= yield(:title) %></title>\n <!-- Additional header tags here -->\n</head>\n<body>\n <!-- If all pages contain a headline tag, it's preferable to put that in the layout file too -->\n <h1><%= yield(:title) %></h1>\n</body>\n</code></pre>\n\n<p>It's also possible to encapsulate the <code>content_for</code> and <code>yield(:title)</code> statements in helper methods (as others have already suggested). However, in simple cases such as this one I like to put the necessary code directly into the specific views without custom helpers.</p>\n"
},
{
"answer_id": 188593,
"author": "IDBD",
"author_id": 7403,
"author_profile": "https://Stackoverflow.com/users/7403",
"pm_score": -1,
"selected": false,
"text": "<p>I would like to add my pretty simple variant.</p>\n\n<p>In the ApplicationController define this method:</p>\n\n<pre><code> def get_title\n @action_title_name || case controller_name\n when 'djs'\n 'Djs'\n when 'photos'\n 'Photos'\n when 'events'\n 'Various events'\n when 'static'\n 'Info'\n when 'club'\n 'My club'\n when 'news'\n 'News'\n when 'welcome'\n 'Welcome!'\n else\n 'Other'\n end\n end\n</code></pre>\n\n<p>After that you can call get_title from your layout's title tag. You can define more specific title for your page by defining @action_title_name variable in your actions.</p>\n"
},
{
"answer_id": 1481279,
"author": "opsb",
"author_id": 162337,
"author_profile": "https://Stackoverflow.com/users/162337",
"pm_score": 7,
"selected": false,
"text": "<p>Here's a simple option that I like to use</p>\n\n<p>In your layout</p>\n\n<pre><code><head>\n <title><%= @title %></title>\n</head>\n</code></pre>\n\n<p>And at the top of your page template (first line)</p>\n\n<pre><code><% @title=\"Home\" %>\n</code></pre>\n\n<p>Because of the way the layout and page templates are parsed the @title=\"Home\" is evaluated before the layout is rendered.</p>\n"
},
{
"answer_id": 3796454,
"author": "sent-hil",
"author_id": 236655,
"author_profile": "https://Stackoverflow.com/users/236655",
"pm_score": 2,
"selected": false,
"text": "<p>I use nifty_generator's \"nifty_layout\" which provides with a title variable which I can call then on the page using:</p>\n\n<p><code><% title \"Title of page\" %></code></p>\n\n<p>I can also user <code><% title \"Title of page\", false %></code> to have the title just show in browser title and not in the page itself.</p>\n"
},
{
"answer_id": 5132468,
"author": "Henrik N",
"author_id": 6962,
"author_profile": "https://Stackoverflow.com/users/6962",
"pm_score": 0,
"selected": false,
"text": "<p>I use <del>this plugin</del> these Rails helpers I wrote: <a href=\"http://web.archive.org/web/20130117090719/http://henrik.nyh.se/2007/11/my-rails-title-helpers/\" rel=\"nofollow\">http://web.archive.org/web/20130117090719/http://henrik.nyh.se/2007/11/my-rails-title-helpers/</a></p>\n"
},
{
"answer_id": 14721083,
"author": "FouZ",
"author_id": 300141,
"author_profile": "https://Stackoverflow.com/users/300141",
"pm_score": -1,
"selected": false,
"text": "<p>The best/clean way to do this :</p>\n\n<pre><code><title><%= @page_title or 'Page Title' %></title>\n</code></pre>\n"
},
{
"answer_id": 16637619,
"author": "boulder_ruby",
"author_id": 1276506,
"author_profile": "https://Stackoverflow.com/users/1276506",
"pm_score": 5,
"selected": false,
"text": "<p>An improvement on <em>@opsb</em> and a more complete form of <em>@FouZ</em>'s:</p>\n\n<p>In <code>application.html.erb</code>:</p>\n\n<pre><code><title><%= @title || \"Default Page Title\" %></title>\n</code></pre>\n\n<p>In the view erb file or its controller:</p>\n\n<pre><code><% @title = \"Unique Page Title\" %>\n</code></pre>\n"
},
{
"answer_id": 38158543,
"author": "Kofi Asare",
"author_id": 6541069,
"author_profile": "https://Stackoverflow.com/users/6541069",
"pm_score": 2,
"selected": false,
"text": "<p>approach for page titling using content_for method and a partial</p>\n\n<p>1 . partial name : _page_title.html.erb</p>\n\n<pre><code><%content_for :page_title do %>\n <%=title%>\n<%end%>\n</code></pre>\n\n<p>2 . Usage in application.html.erb inside title tag</p>\n\n<pre><code> <title><%=yield :page_title %></title>\n</code></pre>\n\n<p>3 . Usage in respective *.html.erb excluding application.html.erb\n Just stick this in any .html.erb and supply title of the page</p>\n\n<pre><code> e.g : inside index.html.erb\n\n <%=render '_page_title', title: 'title_of_page'%>\n</code></pre>\n"
},
{
"answer_id": 41844097,
"author": "Mukesh Kumar Gupta",
"author_id": 2713696,
"author_profile": "https://Stackoverflow.com/users/2713696",
"pm_score": 1,
"selected": false,
"text": "<p>In short, I can write this down as follow</p>\n\n<pre><code><%content_for :page_title do %><%= t :page_title, \"Name of Your Page\" %> <% end %>\n</code></pre>\n"
},
{
"answer_id": 48245616,
"author": "barlop",
"author_id": 385907,
"author_profile": "https://Stackoverflow.com/users/385907",
"pm_score": 1,
"selected": false,
"text": "<p>I like opsb's method, but this method works too.</p>\n\n<pre><code><% provide(:title,\"ttttttttttttttttttZ\") %>\n<html>\n <head><title><%= yield(:title) %></title></head>\n <body></body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 63978530,
"author": "stevec",
"author_id": 5783745,
"author_profile": "https://Stackoverflow.com/users/5783745",
"pm_score": 3,
"selected": false,
"text": "<p>This simple approach sets a default title, but also let you override it whenever you please.</p>\n<p>In <code>app/views/layouts/application.html.erb</code>:</p>\n<pre><code><title><%= yield(:title) || 'my default title' %></title>\n</code></pre>\n<p>And to override that default, place this in any view you like</p>\n<pre><code><% content_for :title, "some new title" %>\n</code></pre>\n"
},
{
"answer_id": 69686162,
"author": "Emric Månsson",
"author_id": 5851595,
"author_profile": "https://Stackoverflow.com/users/5851595",
"pm_score": 1,
"selected": false,
"text": "<p>I wanted to ensure that translations was always provided for the current page.</p>\n<p>This is what I came up with in <code>app/views/layouts/application.html.erb</code>:</p>\n<pre><code> <title>\n <%= translate("#{controller_name}.#{action_name}.site_title", raise: true) %>\n </title>\n</code></pre>\n<p>This will always look for a translation for the current view and raise an error if none is found.</p>\n<p>If you instead wanted a default you could do:</p>\n<pre><code> <title>\n <%= translate("#{controller_name}.#{action_name}.site_title", \n default: translate(".site_title")) %>\n </title>\n</code></pre>\n"
},
{
"answer_id": 73371607,
"author": "Matthew",
"author_id": 145725,
"author_profile": "https://Stackoverflow.com/users/145725",
"pm_score": 1,
"selected": false,
"text": "<p>There's already several good answers but here's how I eventually solved this in Rails 7 using a combination of several answers. This solution let's me:</p>\n<ul>\n<li>Provide the entire title for full control<br />\ne.g. "My awesome custom title"</li>\n<li>Provide just a page title and it automatically appends the site title<br />\ne.g. "Items - My App"</li>\n<li>Provide nothing and just the site title is displayed<br />\ne.g. "My App"</li>\n<li>Localise all of the above</li>\n</ul>\n<h2>Set up</h2>\n<h4>Localisation</h4>\n<pre><code># config/locales/en.yml\nen:\n layouts:\n application:\n site_title: "My App"\n</code></pre>\n<h4>Logic in template</h4>\n<pre><code># app/views/layouts/application.html.erb\n<title>\n <%= yield(:title).presence ||\n [yield(:page_title).presence, t(".site_title")].compact.join(" - ") %>\n</title>\n</code></pre>\n<h4>Logic in helper</h4>\n<p>Note the switch from <code>yield</code> to <code>content_for</code></p>\n<pre><code># app/views/layouts/application.html.erb\n<title><%= show_title %></title>\n\n# app/helpers/application_helper.rb\nmodule ApplicationHelper\n def show_title\n content_for(:title).presence ||\n [content_for(:page_title).presence, t(".site_title")].compact.join(" - ")\n end\nend\n</code></pre>\n<h2>Usage</h2>\n<h4>Fully custom title</h4>\n<pre><code># app/views/static_pages/welcome.html.erb\n<% content_for :title, "My awesome custom title" %>\n\n# or localised...\n# <% content_for :title, t(".custom_title") %>\n\n# Outputs:\n# <title>My awesome custom title</title>\n</code></pre>\n<h4>Page title (with site automatically appended)</h4>\n<pre><code># app/views/products/index.html.erb\n<% content_for :page_title, "Items" %>\n\n# or localised...\n# <% content_for :page_title, t("Products.model_name.human") %>\n\n# Outputs:\n# <title>Items - My App</title>\n</code></pre>\n<h4>Default page title</h4>\n<pre><code># No "content_for" specified\n\n# Outputs:\n# <title>My App</title>\n</code></pre>\n<h2>Notes on the logic</h2>\n<ul>\n<li><code>.presence</code> is needed to turn empty strings (like <code>yield(:title)</code> might be) into nils</li>\n<li>If <code>yield(:title).presence</code> is nil, the <code>||</code> tells Ruby to evaluate the other side of the expression</li>\n<li>On the other side, we start with an array of the page title and the site title</li>\n<li><code>.compact</code> removes nils so if the page title is blank we don't end up with " - My App"</li>\n<li>`.join(" - ") joins the items separated by a hyphen if there's more than one, returns the only item unmodified if there's only one and returns an empty string if the array is empty</li>\n</ul>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] |
What is the best way to create a custom title for pages in a Rails app without using a plug-in?
|
In your views do something like this:
```
<% content_for :title, "Title for specific page" %>
<!-- or -->
<h1><%= content_for(:title, "Title for specific page") %></h1>
```
The following goes in the layout file:
```
<head>
<title><%= yield(:title) %></title>
<!-- Additional header tags here -->
</head>
<body>
<!-- If all pages contain a headline tag, it's preferable to put that in the layout file too -->
<h1><%= yield(:title) %></h1>
</body>
```
It's also possible to encapsulate the `content_for` and `yield(:title)` statements in helper methods (as others have already suggested). However, in simple cases such as this one I like to put the necessary code directly into the specific views without custom helpers.
|
185,966 |
<pre><code><div id="myDiv">
<a>...</a>
<a>...</a>
<a>...</a>
<a>...</a>
<a>...</a>
<a>...</a>
</div>
</code></pre>
<p>If you wanted to select the 2nd, 3rd and 4th <code>a</code> tags in the above example, how would you do that? The only thing I can think of is:</p>
<pre><code>$("#myDiv a:eq(1), #myDiv a:eq(2), #myDiv a:eq(3)")
</code></pre>
<p>But that doesn't look to be very efficient or pretty. I guess you could also select ALL the <code>a</code>s and then do run <code>.each</code> over them, but that could get very inefficient if there were a lot more <code>a</code>s.</p>
|
[
{
"answer_id": 185977,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": false,
"text": "<p>Using the <a href=\"http://docs.jquery.com/Traversing/slice\" rel=\"nofollow noreferrer\">.slice()</a> function does exactly what I need.</p>\n"
},
{
"answer_id": 186018,
"author": "Alexander Prokofyev",
"author_id": 11256,
"author_profile": "https://Stackoverflow.com/users/11256",
"pm_score": 8,
"selected": true,
"text": "<p>jQuery <a href=\"http://docs.jquery.com/Traversing/slice\" rel=\"noreferrer\">slice()</a> function taking indexes of the first and the last needed elements selects a subset of the matched elements. Note what it doesn't include last element itself. </p>\n\n<p>In your particular case you should use</p>\n\n<pre><code>$(\"#myDiv a\").slice(1, 4)\n</code></pre>\n"
},
{
"answer_id": 186034,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "<p>You should be able to do this by extracting a slice of the array thus. It's the line</p>\n\n<pre><code>$(\"div[id='myDiv'] > a\").slice(1,4).css(\"background\",\"yellow\");\n</code></pre>\n\n<p>that you're interested in. It will affect the 2nd, 3rd and 4th elements.</p>\n\n<pre><code><html>\n <head>\n <script type=\"text/javascript\" src=\"jquery-1.2.6.pack.js\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function(){\n $(\"a\").click(function(event){\n $(\"div[id='myDiv'] > a\").slice(1,4).css(\"background\",\"yellow\");\n event.preventDefault();\n });\n });\n </script>\n </head>\n <body>\n <div id=\"myDiv\">\n <a>1</a>\n <a>2</a>\n <a>3</a>\n <a>4</a>\n <a>5</a>\n <a>6</a>\n </div>\n <hr>\n <a href=\"\" >Click here</a>\n <hr>\n </body>\n</html>\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
```
<div id="myDiv">
<a>...</a>
<a>...</a>
<a>...</a>
<a>...</a>
<a>...</a>
<a>...</a>
</div>
```
If you wanted to select the 2nd, 3rd and 4th `a` tags in the above example, how would you do that? The only thing I can think of is:
```
$("#myDiv a:eq(1), #myDiv a:eq(2), #myDiv a:eq(3)")
```
But that doesn't look to be very efficient or pretty. I guess you could also select ALL the `a`s and then do run `.each` over them, but that could get very inefficient if there were a lot more `a`s.
|
jQuery [slice()](http://docs.jquery.com/Traversing/slice) function taking indexes of the first and the last needed elements selects a subset of the matched elements. Note what it doesn't include last element itself.
In your particular case you should use
```
$("#myDiv a").slice(1, 4)
```
|
185,972 |
<p>In javascript, we can do:</p>
<pre><code>["a string", 10, {x : 1}, function() {}].push("another value");
</code></pre>
<p>What is the Scala equivalent?</p>
|
[
{
"answer_id": 188235,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 6,
"selected": true,
"text": "<p>Arrays in Scala are very much homogeneous. This is because Scala is a statically typed language. If you really need pseudo-heterogeneous features, you need to use an immutable data structure that is parametrized covariantly (most immutable data structures are). <code>List</code> is the canonical example there, but <a href=\"http://www.codecommit.com/blog/misc/implementing-persistent-vectors-in-scala/final/Vector.scala\" rel=\"noreferrer\"><code>Vector</code></a> is also an option. Then you can do something like this:</p>\n\n<pre><code>Vector(\"a string\", 10, Map(\"x\" -> 1), ()=>()) + \"another value\"\n</code></pre>\n\n<p>The result will be of type <code>Vector[Any]</code>. Not very useful in terms of static typing, but everything will be in there as promised.</p>\n\n<p>Incidentally, the \"literal syntax\" for <em>arrays</em> in Scala is as follows:</p>\n\n<pre><code>Array(1, 2, 3, 4) // => Array[Int] containing [1, 2, 3, 4]\n</code></pre>\n\n<p><strong>See also</strong>: <a href=\"http://www.codecommit.com/blog/scala/implementing-persistent-vectors-in-scala/\" rel=\"noreferrer\">More info on persistent vectors</a></p>\n"
},
{
"answer_id": 205729,
"author": "ePharaoh",
"author_id": 28166,
"author_profile": "https://Stackoverflow.com/users/28166",
"pm_score": 2,
"selected": false,
"text": "<p>Scala might get the ability for a \"heterogeneous\" list soon:\n<a href=\"http://jnordenberg.blogspot.com/2008/09/hlist-in-scala-revisited-or-scala.html\" rel=\"nofollow noreferrer\">HList in Scala</a></p>\n"
},
{
"answer_id": 6091792,
"author": "soc",
"author_id": 297776,
"author_profile": "https://Stackoverflow.com/users/297776",
"pm_score": 4,
"selected": false,
"text": "<p>Scala will choose the most specific Array element type which can hold all values, in this case it needs the most general type <code>Any</code> which is a supertype of every other type:</p>\n\n<pre><code>Array(\"a string\", 10, new { val x = 1 }, () => ()) :+ \"another value\"\n</code></pre>\n\n<p>The resulting array will be of type <code>Array[Any]</code>.</p>\n"
},
{
"answer_id": 13468813,
"author": "akauppi",
"author_id": 14455,
"author_profile": "https://Stackoverflow.com/users/14455",
"pm_score": 2,
"selected": false,
"text": "<p>Personally, I would probably use tuples, as herom mentions in a comment.</p>\n\n<pre><code>scala> (\"a string\", 10, (1), () => {})\nres1: (java.lang.String, Int, Int, () => Unit) = (a string,10,1,<function0>)\n</code></pre>\n\n<p>But you cannot append to such structures easily.</p>\n\n<p>The HList mentioned by ePharaoh is \"made for this\" but I would probably stay clear of it myself. It's heavy on type programming and therefore may carry surprising loads with it (i.e. creating a lot of classes when compiled). Just be careful. A HList of the above (needs MetaScala library) would be (not proven since I don't use MetaScala):</p>\n\n<pre><code>scala> \"a string\" :: 10 :: (1) :: () => {} :: HNil\n</code></pre>\n\n<p>You can append etc. (well, at least prepend) to such a list, and it will know the types. Prepending creates a new type that has the old type as the tail.</p>\n\n<p>Then there's one approach not mentioned yet. Classes (especially case classes) are very light on Scala and you can make them as one-liners:</p>\n\n<pre><code>scala> case class MyThing( str: String, int: Int, x: Int, f: () => Unit )\ndefined class MyThing\n\nscala> MyThing( \"a string\", 10, 1, ()=>{} )\nres2: MyThing = MyThing(a string,10,1,<function0>)\n</code></pre>\n\n<p>Of course, this will not handle appending either.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/185972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20689/"
] |
In javascript, we can do:
```
["a string", 10, {x : 1}, function() {}].push("another value");
```
What is the Scala equivalent?
|
Arrays in Scala are very much homogeneous. This is because Scala is a statically typed language. If you really need pseudo-heterogeneous features, you need to use an immutable data structure that is parametrized covariantly (most immutable data structures are). `List` is the canonical example there, but [`Vector`](http://www.codecommit.com/blog/misc/implementing-persistent-vectors-in-scala/final/Vector.scala) is also an option. Then you can do something like this:
```
Vector("a string", 10, Map("x" -> 1), ()=>()) + "another value"
```
The result will be of type `Vector[Any]`. Not very useful in terms of static typing, but everything will be in there as promised.
Incidentally, the "literal syntax" for *arrays* in Scala is as follows:
```
Array(1, 2, 3, 4) // => Array[Int] containing [1, 2, 3, 4]
```
**See also**: [More info on persistent vectors](http://www.codecommit.com/blog/scala/implementing-persistent-vectors-in-scala/)
|
186,004 |
<p>Specifically, I want to listen to when programs are run and record information such as: timestamp, executable, windows name and user.</p>
|
[
{
"answer_id": 186011,
"author": "Nick",
"author_id": 26240,
"author_profile": "https://Stackoverflow.com/users/26240",
"pm_score": 0,
"selected": false,
"text": "<p>Look into using the Perfmon API's (check MSDN for references).</p>\n"
},
{
"answer_id": 186149,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 1,
"selected": false,
"text": "<p>Alternatively, use the WMI interface to find out what's running and take appropriate action. In the VBScript code below the WMI subsystem is being queried with <code>Select * from Win32_Process</code> so as to change the process priority. Find out what other attributes are available for <code>Win32_Process</code> and you should find stuff that's heading in the direction you want to go.</p>\n\n<pre><code>Const NORMAL_PRIORITY = 32\nConst LOW_PRIORITY = 64\nConst REALTIME_PRIORITY = 128\nConst HIGH_PRIORITY = 256\nConst BELOWNORMAL_PRIORITY = 16384\nConst ABOVENORMAL_PRIORITY = 32768\n\nFunction SetPriority( sProcess, nPriority )\n Dim sComputer\n Dim oWMIService\n Dim cProcesses\n Dim oProcess\n Dim bDone\n\n bDone = False\n sComputer = \".\"\n Set oWMIService = GetObject(\"winmgmts:\\\\\" & sComputer & \"\\root\\cimv2\")\n\n Set cProcesses = oWMIService.ExecQuery (\"Select * from Win32_Process Where Name = '\" & sProcess & \"'\")\n For Each oProcess in cProcesses\n oProcess.SetPriority( nPriority )\n bDone = True \n Next\n SetPriority = bDone\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 186468,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 1,
"selected": false,
"text": "<p>The most obscene way of doing this is the Google-desktop way<br>\nNamely to have your DLL load into every process that is ever started and to log information.<br>\nIf you're interested more, install google desktop and watch its dll load into your processes. Then look in the registry to see it does it.<br>\nBe mindful that this is entering to the realm of virus like behaviour.</p>\n"
},
{
"answer_id": 186702,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 1,
"selected": false,
"text": "<p>I would use the PSAPI function <a href=\"http://msdn.microsoft.com/en-us/library/ms682629(VS.85).aspx\" rel=\"nofollow noreferrer\">EnumProcesses</a>() to periodically get a list of running processes.</p>\n"
},
{
"answer_id": 187443,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You could set up a WMI permanent event subscription to monitor process creation and log the details. I have some samples <a href=\"http://www.codeproject.com/KB/system/PermEvtSubscriptionMOF.aspx\" rel=\"nofollow noreferrer\">here</a> - one of the samples monitors notepad.exe creation and logs the events in a txt file. Permanent event subscription monitors events 'at all times', but if you want to monitor events 'for the duration of your application', you can use WMI COM API with C++ - the WQL event query is the same in both cases. The documentation is <a href=\"http://msdn.microsoft.com/en-us/library/aa393015(VS.85).aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24416/"
] |
Specifically, I want to listen to when programs are run and record information such as: timestamp, executable, windows name and user.
|
Alternatively, use the WMI interface to find out what's running and take appropriate action. In the VBScript code below the WMI subsystem is being queried with `Select * from Win32_Process` so as to change the process priority. Find out what other attributes are available for `Win32_Process` and you should find stuff that's heading in the direction you want to go.
```
Const NORMAL_PRIORITY = 32
Const LOW_PRIORITY = 64
Const REALTIME_PRIORITY = 128
Const HIGH_PRIORITY = 256
Const BELOWNORMAL_PRIORITY = 16384
Const ABOVENORMAL_PRIORITY = 32768
Function SetPriority( sProcess, nPriority )
Dim sComputer
Dim oWMIService
Dim cProcesses
Dim oProcess
Dim bDone
bDone = False
sComputer = "."
Set oWMIService = GetObject("winmgmts:\\" & sComputer & "\root\cimv2")
Set cProcesses = oWMIService.ExecQuery ("Select * from Win32_Process Where Name = '" & sProcess & "'")
For Each oProcess in cProcesses
oProcess.SetPriority( nPriority )
bDone = True
Next
SetPriority = bDone
End Function
```
|
186,015 |
<p>I have had to do this several times, usually when trying to find in what files a variable or a function is used.</p>
<p>I remember using xargs with grep in the past to do this, but I am wondering if there are any easier ways.</p>
|
[
{
"answer_id": 186020,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 6,
"selected": true,
"text": "<pre><code>grep -r REGEX .\n</code></pre>\n\n<p>Replace <code>.</code> with whatever directory you want to search from.</p>\n"
},
{
"answer_id": 186027,
"author": "CaptainPicard",
"author_id": 15203,
"author_profile": "https://Stackoverflow.com/users/15203",
"pm_score": 2,
"selected": false,
"text": "<p>grep -r if you're using GNU grep, which comes with most Linux distros.</p>\n\n<p>On most UNIXes it's not installed by default so try this instead:</p>\n\n<p>find . -type f | xargs grep regex</p>\n"
},
{
"answer_id": 186043,
"author": "Darren Greaves",
"author_id": 151,
"author_profile": "https://Stackoverflow.com/users/151",
"pm_score": 2,
"selected": false,
"text": "<p>If you use the zsh shell you can use </p>\n\n<pre><code>grep REGEX **/*\n</code></pre>\n\n<p>or</p>\n\n<pre><code>grep REGEX **/*.java\n</code></pre>\n\n<p>This can run out of steam if there are too many matching files.</p>\n\n<p>The canonical way though is to use find with exec.</p>\n\n<pre><code>find . -name '*.java' -exec grep REGEX {} \\;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>find . -type f -exec grep REGEX {} \\;\n</code></pre>\n\n<p>The 'type f' bit just means type of file and will match all files.</p>\n"
},
{
"answer_id": 186687,
"author": "rjray",
"author_id": 6421,
"author_profile": "https://Stackoverflow.com/users/6421",
"pm_score": 3,
"selected": false,
"text": "<p>This is one of the cases for which I've started using <strong>ack</strong> (<a href=\"http://petdance.com/ack/\" rel=\"noreferrer\">http://petdance.com/ack/</a>) in lieu of <strong>grep</strong>. From the site, you can get instructions to install it as a Perl CPAN component, or you can get a self-contained version that can be installed without dealing with dependencies.</p>\n\n<p>Besides the fact that it defaults to recursive searching, it allows you to use Perl-strength regular expressions, use regex's to choose files to search, etc. It has an impressive list of options. I recommend visiting the site and checking it out. I've found it extremely easy to use, and there are tips for integrating it with vi(m), emacs, and even TextMate if you use that.</p>\n"
},
{
"answer_id": 187322,
"author": "Scott",
"author_id": 7399,
"author_profile": "https://Stackoverflow.com/users/7399",
"pm_score": 2,
"selected": false,
"text": "<p>I suggest changing the answer to: </p>\n\n<p><code>grep REGEX -r .</code></p>\n\n<p>The -r switch doesn't indicate regular expression. It tells grep to recurse into the directory provided.</p>\n"
},
{
"answer_id": 187355,
"author": "Gabriel Gilini",
"author_id": 25853,
"author_profile": "https://Stackoverflow.com/users/25853",
"pm_score": 3,
"selected": false,
"text": "<p>If you're looking for a string match, use </p>\n\n<pre><code>fgrep -r pattern .\n</code></pre>\n\n<p>which is faster than using grep.\nMore about the subject here: <a href=\"http://www.mkssoftware.com/docs/man1/grep.1.asp\" rel=\"noreferrer\">http://www.mkssoftware.com/docs/man1/grep.1.asp</a></p>\n"
},
{
"answer_id": 731731,
"author": "Chas. Owens",
"author_id": 78259,
"author_profile": "https://Stackoverflow.com/users/78259",
"pm_score": 4,
"selected": false,
"text": "<p>The portable method* of doing this is</p>\n\n<pre><code>find . -type f -print0 | xargs -0 grep pattern\n</code></pre>\n\n<p><code>-print0</code> tells find to use ASCII nuls as the separator and <code>-0</code> tells xargs the same thing. If you don't use them you will get errors on files and directories that contain spaces in their names.</p>\n\n<p>* as opposed to grep -r, grep -R, or grep --recursive which only work on some machines.</p>\n"
},
{
"answer_id": 15712293,
"author": "trickster",
"author_id": 2225882,
"author_profile": "https://Stackoverflow.com/users/2225882",
"pm_score": 1,
"selected": false,
"text": "<p>This is a great way to find the exact expression recursively with one or more file types:</p>\n\n<p><code>find . \\\\( -name '\\''*.java'\\'' -o -name '\\''*.xml'\\'' \\\\) | xargs egrep</code>\n(internal single quotes)</p>\n\n<p>Where </p>\n\n<p><code>-name '\\''*.<filetype>'\\'' -o</code>\n(again single quotes here)</p>\n\n<p>is repeated in the parenthesis ( ) for how many more filetypes you want to add to your recursive search</p>\n\n<p>an alias looks like this in bash</p>\n\n<p><code>alias fnd='find . \\\\( -name '\\''*.java'\\'' -o -name '\\''*.xml'\\'' \\\\) | xargs egrep'</code></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25910/"
] |
I have had to do this several times, usually when trying to find in what files a variable or a function is used.
I remember using xargs with grep in the past to do this, but I am wondering if there are any easier ways.
|
```
grep -r REGEX .
```
Replace `.` with whatever directory you want to search from.
|
186,024 |
<pre><code>(function()
{
//codehere
}
)();
</code></pre>
<p>What is special about this kind of syntax?
What does ()(); imply?</p>
|
[
{
"answer_id": 186030,
"author": "Geoff",
"author_id": 10427,
"author_profile": "https://Stackoverflow.com/users/10427",
"pm_score": 5,
"selected": false,
"text": "<p>The creates an anonymous function, closure and all, and the final () tells it to execute itself.</p>\n\n<p>It is basically the same as:</p>\n\n<pre><code>function name (){...}\nname();\n</code></pre>\n\n<p>So basically there is nothing special about this code, it just a 'shortcut' to creating a method and invoking it without having to name it. </p>\n\n<p>This also implies that the function is a one off, or an internal function on an object, and is most useful when you need to the features of a closure.</p>\n"
},
{
"answer_id": 186033,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 2,
"selected": false,
"text": "<p>That is a self executing anonymous function. The () at the end is actually calling the function.</p>\n\n<p>A good book (I have read) that explains some usages of these types of syntax in Javascript is <a href=\"https://rads.stackoverflow.com/amzn/click/com/1847194141\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Object Oriented Javascript</a>.</p>\n"
},
{
"answer_id": 186041,
"author": "Sugendran",
"author_id": 22466,
"author_profile": "https://Stackoverflow.com/users/22466",
"pm_score": 0,
"selected": false,
"text": "<p>The stuff in the first set of brackets evaluates to a function. The second set of brackets then execute this function. So if you have something that want to run automagically onload, this how you'd cause it to load and execute.</p>\n"
},
{
"answer_id": 186186,
"author": "artificialidiot",
"author_id": 7988,
"author_profile": "https://Stackoverflow.com/users/7988",
"pm_score": 2,
"selected": false,
"text": "<p>This usage is basically equivalent of a inner block in C. It prevents the variables defined <em>inside</em> the block to be visible outside. So it is a handy way of constructing a one off classes <em>with</em> private objects. Just don't forget <code>return this;</code> if you use it to build an object.</p>\n\n<pre><code>var Myobject=(function(){\n var privatevalue=0;\n function privatefunction()\n {\n }\n this.publicvalue=1;\n this.publicfunction=function()\n {\n privatevalue=1; //no worries about the execution context\n }\nreturn this;})(); //I tend to forget returning the instance\n //if I don't write like this\n</code></pre>\n"
},
{
"answer_id": 187042,
"author": "Leo",
"author_id": 20689,
"author_profile": "https://Stackoverflow.com/users/20689",
"pm_score": 2,
"selected": false,
"text": "<p>It's an anonymous function being called.</p>\n\n<p>The purpose of that is to create a new scope from which local variables don't bleed out. For example:</p>\n\n<pre><code>var test = 1;\n(function() {\n var test = 2;\n})();\ntest == 1 // true\n</code></pre>\n\n<p>One important note about this syntax is that you should get into the habit of terminating statements with a semi-colon, if you don't already. This is because Javascript allows line feeds between a function name and its parentheses when you call it.</p>\n\n<p>The snippet below will cause an error:</p>\n\n<pre><code>var aVariable = 1\nvar myVariable = aVariable\n\n(function() {/*...*/})()\n</code></pre>\n\n<p>Here's what it's actually doing:</p>\n\n<pre><code>var aVariable = 1;\nvar myVariable = aVariable(function() {/*...*/})\nmyVariable();\n</code></pre>\n\n<p>Another way of creating a new block scope is to use the following syntax:</p>\n\n<pre><code>new function() {/*...*/}\n</code></pre>\n\n<p>The difference is that the former technique does not affect where the keyword \"this\" points to, whereas the second does.</p>\n\n<p>Javascript 1.8 also has a let statement that accomplishes the same thing, but needless to say, it's not supported by most browsers.</p>\n"
},
{
"answer_id": 187315,
"author": "James",
"author_id": 21677,
"author_profile": "https://Stackoverflow.com/users/21677",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://books.google.co.uk/books?id=GgJN2CC_2s4C&pg=PA29&lpg=PA29&dq=John+resig+self+executing+anonymous+function&source=web&ots=7w-ceWchMH&sig=oLWUghev2PlbhBU0DXyw2i8fzM8&hl=en&sa=X&oi=book_result&resnum=1&ct=result#v=onepage&q&f=false\" rel=\"nofollow noreferrer\">John Resig explains self-executing anonymous functions here</a>.</p>\n"
},
{
"answer_id": 215075,
"author": "Kent Brewster",
"author_id": 1151280,
"author_profile": "https://Stackoverflow.com/users/1151280",
"pm_score": 1,
"selected": false,
"text": "<p>See also Douglas Crockford's excellent \"JavaScript: The Good Parts,\" available from O'Reilly, here:</p>\n\n<p><a href=\"http://oreilly.com/catalog/9780596517748/\" rel=\"nofollow noreferrer\"><a href=\"http://oreilly.com/catalog/9780596517748/\" rel=\"nofollow noreferrer\">http://oreilly.com/catalog/9780596517748/</a></a></p>\n\n<p>... and on video at the YUIblog, here:</p>\n\n<p><a href=\"http://yuiblog.com/blog/2007/06/08/video-crockford-goodstuff/\" rel=\"nofollow noreferrer\"><a href=\"http://yuiblog.com/blog/2007/06/08/video-crockford-goodstuff/\" rel=\"nofollow noreferrer\">http://yuiblog.com/blog/2007/06/08/video-crockford-goodstuff/</a></a></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21572/"
] |
```
(function()
{
//codehere
}
)();
```
What is special about this kind of syntax?
What does ()(); imply?
|
The creates an anonymous function, closure and all, and the final () tells it to execute itself.
It is basically the same as:
```
function name (){...}
name();
```
So basically there is nothing special about this code, it just a 'shortcut' to creating a method and invoking it without having to name it.
This also implies that the function is a one off, or an internal function on an object, and is most useful when you need to the features of a closure.
|
186,035 |
<p>I have a simple "accordion" type page containing a list of H3 headers and DIV content boxes (each H3 is followed by a DIV). On this page I start with all DIVs hidden. When a H3 is clicked the DIV directly below (after) is revealed with jQuery's <a href="http://jquery.com/api/#slideDown" rel="nofollow noreferrer">"slideDown"</a> function while all other DIVs are hidden with the <a href="http://jquery.com/api/#slideUp" rel="nofollow noreferrer">"slideUp"</a> function.</p>
<p>The "slideUp" function inserts the following inline style into the specified DIVs:</p>
<pre><code>style="display: none;"
</code></pre>
<p>I am wondering if there is any way for me to show all the DIVs expanded when a user prints the page (as I do when a user has JavaScript disabled).</p>
<p>I am thinking it is impossible because the inline style will always take precedence over any other style declaration.</p>
<p>Is there another solution?</p>
<p><strong>Solution</strong></p>
<p><a href="https://stackoverflow.com/questions/186035/is-it-possible-to-print-a-div-that-is-hidden-by-jquerys-slideup-function#186189">Sugendran's solution</a> is great and works in the browsers (FF2, IE7 and IE6) I've tested so far. I wasn't aware there was any way to override inline styles which I'm pretty sure is something I've looked up before so this is great to find out. I also see there is <a href="https://stackoverflow.com/questions/104485/is-there-a-way-to-force-a-style-to-a-div-element-which-already-has-a-style-attr#104499">this answer here</a> regarding this. I wish search wasn't so difficult to navigate here :-).</p>
<p><a href="https://stackoverflow.com/questions/186035/is-it-possible-to-print-a-div-that-is-hidden-by-jquerys-slideup-function#186276">Lee Theobald's solution</a> would be great but the "slideUp" function adds the style="display:none;" bit. </p>
<p><a href="https://stackoverflow.com/questions/186035/is-it-possible-to-print-a-div-that-is-hidden-by-jquerys-slideup-function#186036">My solution</a> works fine, but is overkill when the !important declaration works.</p>
|
[
{
"answer_id": 186036,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 0,
"selected": false,
"text": "<p>Yes.</p>\n\n<p>On load add a class (e.g. \"hideme\") to all relevant DIVs like so:</p>\n\n<pre><code>$('div#accordion> div').addClass('hideme');\n</code></pre>\n\n<p><em>NB: This means that the accordion degrades fine when JavaScript is disabled.</em></p>\n\n<p>In this way you can have your regular stylesheet specify the \"hideme\" class like this:</p>\n\n<pre><code>.hideme { display: none; }\n</code></pre>\n\n<p>While your print stylesheet can specify the \"hideme\" class like this:</p>\n\n<pre><code>div.hideme { display: block; }\n</code></pre>\n\n<p>Next, in the 'click' function you add to each H3, after sliding up the DIVs, add the \"hideme\" class and then remove the \"style\" attribute from each DIV that was slided up.</p>\n\n<p>The overall jQuery for this looks like this:</p>\n\n<pre><code><script type=\"text/javascript\">\n //<![CDATA[\n $(function() {\n $('#accordion> div').addClass('hideme');\n\n $('#accordion> h3').click(function() {\n $(this).next('div:hidden').slideDown('fast').siblings('div:visible').slideUp('fast', function(){ $('#accordion> div:hidden').addClass('hideme').removeAttr('style'); });\n\n });\n });\n //]]>\n</script>\n</code></pre>\n\n<p>Note the need to include the function callback in the slideUp function so that the style and class changes occur after the DIV has slided up and jQuery has added \"style=display:none;\"</p>\n"
},
{
"answer_id": 186189,
"author": "Sugendran",
"author_id": 22466,
"author_profile": "https://Stackoverflow.com/users/22466",
"pm_score": 5,
"selected": true,
"text": "<p>You can use the !important clause in CSS. This will override the inline style.</p>\n\n<p>So if you setup a print media stylesheet - you can do something like</p>\n\n<pre><code>div.accordian { display:block !important; }\n</code></pre>\n"
},
{
"answer_id": 186276,
"author": "Lee Theobald",
"author_id": 1900,
"author_profile": "https://Stackoverflow.com/users/1900",
"pm_score": 2,
"selected": false,
"text": "<p>I'd personally do this in a different way. Instead of the JQuery adding the inline style, why not get it to add a class instead?</p>\n\n<pre><code><div class=\"closed\">...</div>\n</code></pre>\n\n<p>Then you can have two stylesheets: One for the screen, one for print:</p>\n\n<pre><code><link href=\"screen.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen,projection\"/>\n<link href=\"print.css\" rel=\"stylesheet\" type=\"text/css\" media=\"print\"/>\n</code></pre>\n\n<p>In your screen.css you'd define closed...</p>\n\n<pre><code>div.closed { display: none; }\n</code></pre>\n\n<p>But in your print.css you wouldn't (or you'd leave out the display:none). This way when it comes to printing all divs will be expanded but on screen, they'd be closed.</p>\n"
},
{
"answer_id": 332817,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>{ display:block !important; } works in FF, but I read somewhere that it wouldn't work with ie6. Is there no javascript event for printing? I remember looking extensively for one before and couldn't find one, it seems insane that this doesn't exist, js seems to know when anything else happens inside the browser, but is blind to printing for some reason :(</p>\n\n<p>brent\n@\n<a href=\"http://www.mimoymima.com/resources/081129_jquery-intro.php\" rel=\"nofollow noreferrer\" title=\"Learning jQuery, beginner tutorial\">mimoYmima.com</a> </p>\n"
},
{
"answer_id": 8229137,
"author": "rordaz",
"author_id": 1060061,
"author_profile": "https://Stackoverflow.com/users/1060061",
"pm_score": 2,
"selected": false,
"text": "<p>Making 'display as block' all the elements inside the accordion will cover all the divs inside.</p>\n\n<p><code>#accordion > *{ display:block !important; }</code></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] |
I have a simple "accordion" type page containing a list of H3 headers and DIV content boxes (each H3 is followed by a DIV). On this page I start with all DIVs hidden. When a H3 is clicked the DIV directly below (after) is revealed with jQuery's ["slideDown"](http://jquery.com/api/#slideDown) function while all other DIVs are hidden with the ["slideUp"](http://jquery.com/api/#slideUp) function.
The "slideUp" function inserts the following inline style into the specified DIVs:
```
style="display: none;"
```
I am wondering if there is any way for me to show all the DIVs expanded when a user prints the page (as I do when a user has JavaScript disabled).
I am thinking it is impossible because the inline style will always take precedence over any other style declaration.
Is there another solution?
**Solution**
[Sugendran's solution](https://stackoverflow.com/questions/186035/is-it-possible-to-print-a-div-that-is-hidden-by-jquerys-slideup-function#186189) is great and works in the browsers (FF2, IE7 and IE6) I've tested so far. I wasn't aware there was any way to override inline styles which I'm pretty sure is something I've looked up before so this is great to find out. I also see there is [this answer here](https://stackoverflow.com/questions/104485/is-there-a-way-to-force-a-style-to-a-div-element-which-already-has-a-style-attr#104499) regarding this. I wish search wasn't so difficult to navigate here :-).
[Lee Theobald's solution](https://stackoverflow.com/questions/186035/is-it-possible-to-print-a-div-that-is-hidden-by-jquerys-slideup-function#186276) would be great but the "slideUp" function adds the style="display:none;" bit.
[My solution](https://stackoverflow.com/questions/186035/is-it-possible-to-print-a-div-that-is-hidden-by-jquerys-slideup-function#186036) works fine, but is overkill when the !important declaration works.
|
You can use the !important clause in CSS. This will override the inline style.
So if you setup a print media stylesheet - you can do something like
```
div.accordian { display:block !important; }
```
|
186,044 |
<p>I was developing a web page, where I was laying out a board for a Chess-like game, along with a couple of piece trays. It's all done using HTML (with jQuery for dynamic updating as the game is played). Somewhere I'd got the notion that using absolute positioning of elements within a page was considered a bad practice, and that it was preferable to use relative positioning.</p>
<p>After struggling with relative positioning for too long, I realized that absolute positioning of the board elements would be much, much easier to get right... and it was.</p>
<p>Is anyone aware of a reason that relative positioning is preferable over absolute? Are there any guidelines or rules of thumb that you apply when deciding which approach to take?</p>
|
[
{
"answer_id": 186058,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 8,
"selected": true,
"text": "<p>For a chess like game such as you are developing, there is nothing inherently wrong with using absolute positioning. As you said, relative positioning and normal flow layout make this sort of task quite difficult. </p>\n\n<p>Of course, if you were developing a more standard website, such as a site providing some public service, absolute positioning overrides the default flow layout of browsers and so will reduce accessibility for many users. In this case I would avoid it.</p>\n\n<p>Having said that, a lesser known benefit of absolute positioning is that it allows localized absolute positioning <em>within</em> the nearest \"positioned\" parent element.</p>\n\n<p><em>Note:</em> A \"positioned\" element can be any of the following: relative, fixed, absolute, or sticky.</p>\n\n<p>To explain:</p>\n\n<pre><code><div id=\"parentDIV\" style=\"position:relative\">\n <div id=\"childDIV\" style=\"position:absolute;left:20px;top:20px;\">\n I'm absolutely positioned within parentDIV.\n </div>\n</div>\n</code></pre>\n\n<p>Here, <code>childDIV</code> is actually positioned 20px from the left and 20px from the top of <code>parentDIV</code>, <em>NOT</em> the overall document. This gives a nice precise control over nested elements on a page, without sacrificing the overall page flow-layout.</p>\n\n<p>So to answer your question (relative positioning being preferred over absolute): I don't believe there is a correct answer, it depends on what you are needing to build. However in general positioning (absolute or relative) versus default flow layout, my approach is as described above.</p>\n"
},
{
"answer_id": 186060,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 2,
"selected": false,
"text": "<p>Relative positioning is nice if you can pull a totally fluid layout because it will look reasonable on a large range of screen resolutions.</p>\n\n<p>That being said, it's quite often to find (especially when trying for cross-browser compatability with older versions), that totally fluid layouts are hard to get right. Falling back on absolute positioning shouldn't be frowned upon, most mortal web developers do it all the time.</p>\n"
},
{
"answer_id": 186072,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 3,
"selected": false,
"text": "<p>Look at your website in different browsers under the following conditions:</p>\n\n<ul>\n<li>Switch your OS settings to high-dpi/large fonts/high contrast (all change the size of the default browser font)</li>\n<li>Increase/decrease the default font size in the browser</li>\n<li>Override the page fonts in the browser (usually somewhere in the Accessibility options)</li>\n<li>Override/turn off the page stylesheet (granted, users shouldn't expect a chess game to work properly in this scenario :-))</li>\n</ul>\n\n<p>In general absolute position is bad when you have inline elements with non-fixed size fonts. For your scenario it might work; however, there will be a lot of edge cases where something funky will go on.</p>\n"
},
{
"answer_id": 186327,
"author": "questzen",
"author_id": 25210,
"author_profile": "https://Stackoverflow.com/users/25210",
"pm_score": 1,
"selected": false,
"text": "<p>IMO, not a bad thing at all. I have recently completed an assignment with AA standards compliance and support for FF2, IE7, IE6 (yes, a pain I know). There were certain layouts which were only achievable because of absolutely positioning! Even certain components like buttons where layering was needed (transparencies) were possible only because of absolute positioning. If someone has a better way, please refer me to that.</p>\n\n<p>Absolute positioning breaks the flow, if we know how to restrict the flow (change parent's coords to relative/absolute) it is fun. I don't know about older browsers (IE6 itself is a dinosaur) but one painful thing I found was, writing to PDF (Cute PDF) or opening with WINWORD (sue me) gives a shabby result.</p>\n"
},
{
"answer_id": 186347,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 2,
"selected": false,
"text": "<p>As long as you structure your HTML so that the elements follow a logical order that makes sense when rendered without CSS, there is no reason why using absolute positioning should be considered bad practice.</p>\n"
},
{
"answer_id": 186380,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 2,
"selected": false,
"text": "<p>There are no hard and fast rules. The different forms of positioning are all good at different things.</p>\n\n<p>The majority of work is usually best done with static positioning (it is the least fragile option), but absolute positioning is very good on occasion. Relative positioning, on the other hand, is something I've never used except for animation (on elements which are statically positioned until JavaScript gets involved), establishing a containing block for absolute positioning (so the element itself isn't moved at all), and (very very rarely) a one or two pixel nudge of an element.</p>\n"
},
{
"answer_id": 186698,
"author": "Ionuț Staicu",
"author_id": 23810,
"author_profile": "https://Stackoverflow.com/users/23810",
"pm_score": 2,
"selected": false,
"text": "<p>Some things are impossible to do without position:absolute. Other things are WAY easier to achive with absolute positioning (let say that you want a bottom-right button for \"read more\" in a fixed/min height box and you don't have enough text in that box).\nSo, my advice: just use the one that fits your needs...</p>\n"
},
{
"answer_id": 186767,
"author": "Jacco",
"author_id": 22674,
"author_profile": "https://Stackoverflow.com/users/22674",
"pm_score": 4,
"selected": false,
"text": "<p>It does not answer your question, but...</p>\n\n<p>For a chess like game board I think you can also use a table.<br>\nAfter all, it is is columns and rows you are displaying.</p>\n\n<p>Now I know that many people start shouting 'don't use tables' and 'tables are evil'. Tables are however still a valid tool for showing some types of data, especially columns / rows organised data.</p>\n"
},
{
"answer_id": 187310,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 6,
"selected": false,
"text": "<p>Keep in mind also that absolute positioning is not only used for positioning things relative to the browser window - it's also used for positioning things accurately within a containing element. When I finally understood this - after years of using CSS - it really revolutionized my ability to use CSS effectively. </p>\n\n<p>The key is that an absolutely positioned element is positioned in the context of the first ancestor element that has <code>position:relative</code> or <code>position:absolute</code>. So if you have this:</p>\n\n<pre><code>div.Container\n{\n position:relative\n width:300px;\n height:300px;\n background:yellow;\n}\n\ndiv.PositionMe\n{\n position:absolute;\n top:10px;\n right:10px;\n width:20px;\n height:20px;\n background:red\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code><div class=Container>\n...\n <div class=PositionMe>\n ...\n </div>\n...\n</div>\n</code></pre>\n\n<p>...the div <code>PositionMe</code> will be placed relative to <code>Container</code>, not to the page. </p>\n\n<p>This opens up all sorts of possibility for precise placement in particular situations, without sacrificing the overall flexibility and flow of the page. </p>\n"
},
{
"answer_id": 189933,
"author": "Bryan M.",
"author_id": 4636,
"author_profile": "https://Stackoverflow.com/users/4636",
"pm_score": 3,
"selected": false,
"text": "<p>I think the problem is that absolute positioning is easy to abuse. A coordinate system is much easier for lay people to understand than the box model. Also, programs like Dreamweaver make it trivially simple to layout a page using absolute positioning (and people don't realize what they're doing).</p>\n\n<p>However, for typical page layout, the default static positioning should be adequate and get the job done 90% of the time. It's very flexible, and by keeping everything in normal flow, elements are aware of the other elements around them, and will act according when things change. This is really good when dealing with dynamic content (which most pages are these days).</p>\n\n<p>Using absolute positioning is far more rigid and makes it difficult to write layouts that respond well to changing content. They're simply too explicit. However, it is perfect if you're in need of freely moving elements around a page (drag/drop), need to overlay elements on top of each other, or other layout techniques that would benefit from working on a coordinate system. Frankly, a chessboard sounds like a fine reason to use it.</p>\n"
},
{
"answer_id": 2347705,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 1,
"selected": false,
"text": "<p>Absolute positioning is a tool, like any tool, it can be used in good and bad ways. There is nothing wrong with it: StackOverflow probably uses it to display its alerts in the orange bar at the top of the site.</p>\n\n<p>Now, in your situation, this is not bad either. But I think it would be much easier for you not to use it.</p>\n\n<p>A chess board is a table, table cells don't need position tweaks. For events, <code>onblur</code> / <code>onfocus</code> and <code>cie</code> will do the job. Why would you even need pixels calculation?</p>\n\n<p>So don't be stressed by the quality of your practice, but maybe you could check if you really need absolute positioning.</p>\n"
},
{
"answer_id": 16026661,
"author": "Yaron U.",
"author_id": 729673,
"author_profile": "https://Stackoverflow.com/users/729673",
"pm_score": 2,
"selected": false,
"text": "<p>It seems to me like I'm the only one here that totally disagree with the assumption that absolute posititioning is not a bad practice\nExcept conditions like animation or elements that should specifically sit in an \"unusual\" place whitin their parents, absolute positioning break the structure of your HTML (which is exactly what HTML suppose to define in my opinion) because you can achieve results that differ the visuality from the structure very easily.\nMoreover, implementation of design is way harder and problematic with absolute because you need to measure every element and you have lot of place to mistake (against normal flow that is much easier and right for structure building of a website skeleton)</p>\n\n<p>And finally, regarding the chess board, I believe that the hardest possible way to create it is using position absolute!\nMaking the board with table would be much easier and right (after all this is a table)... And personally I would do it with a <code>cube</code> class that would have <code>float: left</code> (with <code>clear</code> on every ninth cube)</p>\n\n<p>Absolute positioning of 64 different square is insane!</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2193/"
] |
I was developing a web page, where I was laying out a board for a Chess-like game, along with a couple of piece trays. It's all done using HTML (with jQuery for dynamic updating as the game is played). Somewhere I'd got the notion that using absolute positioning of elements within a page was considered a bad practice, and that it was preferable to use relative positioning.
After struggling with relative positioning for too long, I realized that absolute positioning of the board elements would be much, much easier to get right... and it was.
Is anyone aware of a reason that relative positioning is preferable over absolute? Are there any guidelines or rules of thumb that you apply when deciding which approach to take?
|
For a chess like game such as you are developing, there is nothing inherently wrong with using absolute positioning. As you said, relative positioning and normal flow layout make this sort of task quite difficult.
Of course, if you were developing a more standard website, such as a site providing some public service, absolute positioning overrides the default flow layout of browsers and so will reduce accessibility for many users. In this case I would avoid it.
Having said that, a lesser known benefit of absolute positioning is that it allows localized absolute positioning *within* the nearest "positioned" parent element.
*Note:* A "positioned" element can be any of the following: relative, fixed, absolute, or sticky.
To explain:
```
<div id="parentDIV" style="position:relative">
<div id="childDIV" style="position:absolute;left:20px;top:20px;">
I'm absolutely positioned within parentDIV.
</div>
</div>
```
Here, `childDIV` is actually positioned 20px from the left and 20px from the top of `parentDIV`, *NOT* the overall document. This gives a nice precise control over nested elements on a page, without sacrificing the overall page flow-layout.
So to answer your question (relative positioning being preferred over absolute): I don't believe there is a correct answer, it depends on what you are needing to build. However in general positioning (absolute or relative) versus default flow layout, my approach is as described above.
|
186,062 |
<p>Can I create a Controller that simply returns an image asset?</p>
<p>I would like to route this logic through a controller, whenever a URL such as the following is requested:</p>
<pre><code>www.mywebsite.com/resource/image/topbanner
</code></pre>
<p>The controller will look up <code>topbanner.png</code> and send that image directly back to the client.</p>
<p>I've seen examples of this where you have to create a View - I don't want to use a View. I want to do it all with just the Controller.</p>
<p>Is this possible?</p>
|
[
{
"answer_id": 186123,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 2,
"selected": false,
"text": "<p>I see two options:</p>\n\n<p>1) Implement your own IViewEngine and set the ViewEngine property of the Controller you are using to your ImageViewEngine in your desired \"image\" method.</p>\n\n<p>2) Use a view :-). Just change the content type etc.</p>\n"
},
{
"answer_id": 186126,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 2,
"selected": false,
"text": "<p>Look at ContentResult. This returns a string, but can be used to make your own BinaryResult-like class.</p>\n"
},
{
"answer_id": 186132,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 2,
"selected": false,
"text": "<p>You could use the HttpContext.Response and directly write the content to it (WriteFile() might work for you) and then return ContentResult from your action instead of ActionResult.</p>\n\n<p>Disclaimer: I have not tried this, it's based on looking at the available APIs. :-)</p>\n"
},
{
"answer_id": 186133,
"author": "Ian Suttle",
"author_id": 19421,
"author_profile": "https://Stackoverflow.com/users/19421",
"pm_score": 3,
"selected": false,
"text": "<p><strong>UPDATE: There are better options than my original answer. This works outside of MVC quite well but it's better to stick with the built-in methods of returning image content. See up-voted answers.</strong></p>\n\n<p>You certainly can. Try out these steps:</p>\n\n<ol>\n<li>Load the image from disk in to a byte array</li>\n<li>cache the image in the case you expect more requests for the image and don't want the disk I/O (my sample doesn't cache it below)</li>\n<li>Change the mime type via the Response.ContentType</li>\n<li>Response.BinaryWrite out the image byte array</li>\n</ol>\n\n<p>Here's some sample code:</p>\n\n<pre><code>string pathToFile = @\"C:\\Documents and Settings\\some_path.jpg\";\nbyte[] imageData = File.ReadAllBytes(pathToFile);\nResponse.ContentType = \"image/jpg\";\nResponse.BinaryWrite(imageData);\n</code></pre>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 189054,
"author": "JarrettV",
"author_id": 16340,
"author_profile": "https://Stackoverflow.com/users/16340",
"pm_score": 4,
"selected": false,
"text": "<p>You can write directly to the response but then it isn't testable. It is preferred to return an ActionResult that has deferred execution. Here is my resusable StreamResult:</p>\n\n<pre><code>public class StreamResult : ViewResult\n{\n public Stream Stream { get; set; }\n public string ContentType { get; set; }\n public string ETag { get; set; }\n\n public override void ExecuteResult(ControllerContext context)\n {\n context.HttpContext.Response.ContentType = ContentType;\n if (ETag != null) context.HttpContext.Response.AddHeader(\"ETag\", ETag);\n const int size = 4096;\n byte[] bytes = new byte[size];\n int numBytes;\n while ((numBytes = Stream.Read(bytes, 0, size)) > 0)\n context.HttpContext.Response.OutputStream.Write(bytes, 0, numBytes);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 752531,
"author": "Sailing Judo",
"author_id": 42620,
"author_profile": "https://Stackoverflow.com/users/42620",
"pm_score": 7,
"selected": false,
"text": "<p>Using the release version of MVC, here is what I do:</p>\n\n<pre><code>[AcceptVerbs(HttpVerbs.Get)]\n[OutputCache(CacheProfile = \"CustomerImages\")]\npublic FileResult Show(int customerId, string imageName)\n{\n var path = string.Concat(ConfigData.ImagesDirectory, customerId, \"\\\\\", imageName);\n return new FileStreamResult(new FileStream(path, FileMode.Open), \"image/jpeg\");\n}\n</code></pre>\n\n<p>I obviously have some application specific stuff in here regarding the path construction, but the returning of the FileStreamResult is nice and simple.</p>\n\n<p>I did some performance testing in regards to this action against your everyday call to the image (bypassing the controller) and the difference between the averages was only about 3 milliseconds (controller avg was 68ms, non-controller was 65ms). </p>\n\n<p>I had tried some of the other methods mentioned in answers here and the performance hit was much more dramatic... several of the solutions responses were as much as 6x the non-controller (other controllers avg 340ms, non-controller 65ms).</p>\n"
},
{
"answer_id": 1349318,
"author": "Brian",
"author_id": 320,
"author_profile": "https://Stackoverflow.com/users/320",
"pm_score": 10,
"selected": true,
"text": "<p>Use the base controllers File method.</p>\n\n<pre><code>public ActionResult Image(string id)\n{\n var dir = Server.MapPath(\"/Images\");\n var path = Path.Combine(dir, id + \".jpg\"); //validate the path for security or use other means to generate the path.\n return base.File(path, \"image/jpeg\");\n}\n</code></pre>\n\n<p>As a note, this seems to be fairly efficient. I did a test where I requested the image through the controller (<code>http://localhost/MyController/Image/MyImage</code>) and through the direct URL (<code>http://localhost/Images/MyImage.jpg</code>) and the results were:</p>\n\n<ul>\n<li><strong>MVC:</strong> 7.6 milliseconds per photo</li>\n<li><strong>Direct:</strong> 6.7 milliseconds per photo</li>\n</ul>\n\n<p>Note: this is the average time of a request. The average was calculated by making thousands of requests on the local machine, so the totals should not include network latency or bandwidth issues.</p>\n"
},
{
"answer_id": 1495178,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 7,
"selected": false,
"text": "<p>To expland on Dyland's response slightly:</p>\n\n<p>Three classes implement the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.fileresult.aspx\" rel=\"noreferrer\">FileResult</a> class: </p>\n\n<pre><code>System.Web.Mvc.FileResult\n System.Web.Mvc.FileContentResult\n System.Web.Mvc.FilePathResult\n System.Web.Mvc.FileStreamResult\n</code></pre>\n\n<p>They're all fairly self explanatory:</p>\n\n<ul>\n<li>For file path downloads where the file exists on disk, use <code>FilePathResult</code> - this is the easiest way and avoids you having to use Streams.</li>\n<li>For byte[] arrays (akin to Response.BinaryWrite), use <code>FileContentResult</code>.</li>\n<li>For byte[] arrays where you want the file to download (content-disposition: attachment), use <code>FileStreamResult</code> in a similar way to below, but with a <code>MemoryStream</code> and using <code>GetBuffer()</code>.</li>\n<li>For <code>Streams</code> use <code>FileStreamResult</code>. It's called a FileStreamResult but it takes a <code>Stream</code> so I'd <em>guess</em> it works with a <code>MemoryStream</code>.</li>\n</ul>\n\n<p>Below is an example of using the content-disposition technique (not tested):</p>\n\n<pre><code> [AcceptVerbs(HttpVerbs.Post)]\n public ActionResult GetFile()\n {\n // No need to dispose the stream, MVC does it for you\n string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"App_Data\", \"myimage.png\");\n FileStream stream = new FileStream(path, FileMode.Open);\n FileStreamResult result = new FileStreamResult(stream, \"image/png\");\n result.FileDownloadName = \"image.png\";\n return result;\n }\n</code></pre>\n"
},
{
"answer_id": 2288714,
"author": "Victor Gelmutdinov",
"author_id": 129812,
"author_profile": "https://Stackoverflow.com/users/129812",
"pm_score": 2,
"selected": false,
"text": "<pre><code>if (!System.IO.File.Exists(filePath))\n return SomeHelper.EmptyImageResult(); // preventing JSON GET/POST exception\nelse\n return new FilePathResult(filePath, contentType);\n</code></pre>\n\n<p><code>SomeHelper.EmptyImageResult()</code> should return <code>FileResult</code> with existing image (1x1 transparent, for example).</p>\n\n<p>This is easiest way if you have files stored on local drive.\nIf files are <code>byte[]</code> or <code>stream</code> - then use <code>FileContentResult</code> or <code>FileStreamResult</code> as Dylan suggested.</p>\n"
},
{
"answer_id": 5458073,
"author": "staromeste",
"author_id": 680094,
"author_profile": "https://Stackoverflow.com/users/680094",
"pm_score": 6,
"selected": false,
"text": "<p>This might be helpful if you'd like to modify the image before returning it:</p>\n\n<pre><code>public ActionResult GetModifiedImage()\n{\n Image image = Image.FromFile(Path.Combine(Server.MapPath(\"/Content/images\"), \"image.png\"));\n\n using (Graphics g = Graphics.FromImage(image))\n {\n // do something with the Graphics (eg. write \"Hello World!\")\n string text = \"Hello World!\";\n\n // Create font and brush.\n Font drawFont = new Font(\"Arial\", 10);\n SolidBrush drawBrush = new SolidBrush(Color.Black);\n\n // Create point for upper-left corner of drawing.\n PointF stringPoint = new PointF(0, 0);\n\n g.DrawString(text, drawFont, drawBrush, stringPoint);\n }\n\n MemoryStream ms = new MemoryStream();\n\n image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);\n\n return File(ms.ToArray(), \"image/png\");\n}\n</code></pre>\n"
},
{
"answer_id": 6288786,
"author": "Oleksandr Fentsyk",
"author_id": 760375,
"author_profile": "https://Stackoverflow.com/users/760375",
"pm_score": 4,
"selected": false,
"text": "<p>You can create your own extension and do this way.</p>\n\n<pre><code>public static class ImageResultHelper\n{\n public static string Image<T>(this HtmlHelper helper, Expression<Action<T>> action, int width, int height)\n where T : Controller\n {\n return ImageResultHelper.Image<T>(helper, action, width, height, \"\");\n }\n\n public static string Image<T>(this HtmlHelper helper, Expression<Action<T>> action, int width, int height, string alt)\n where T : Controller\n {\n var expression = action.Body as MethodCallExpression;\n string actionMethodName = string.Empty;\n if (expression != null)\n {\n actionMethodName = expression.Method.Name;\n }\n string url = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection).Action(actionMethodName, typeof(T).Name.Remove(typeof(T).Name.IndexOf(\"Controller\"))).ToString(); \n //string url = LinkBuilder.BuildUrlFromExpression<T>(helper.ViewContext.RequestContext, helper.RouteCollection, action);\n return string.Format(\"<img src=\\\"{0}\\\" width=\\\"{1}\\\" height=\\\"{2}\\\" alt=\\\"{3}\\\" />\", url, width, height, alt);\n }\n}\n\npublic class ImageResult : ActionResult\n{\n public ImageResult() { }\n\n public Image Image { get; set; }\n public ImageFormat ImageFormat { get; set; }\n\n public override void ExecuteResult(ControllerContext context)\n {\n // verify properties \n if (Image == null)\n {\n throw new ArgumentNullException(\"Image\");\n }\n if (ImageFormat == null)\n {\n throw new ArgumentNullException(\"ImageFormat\");\n }\n\n // output \n context.HttpContext.Response.Clear();\n context.HttpContext.Response.ContentType = GetMimeType(ImageFormat);\n Image.Save(context.HttpContext.Response.OutputStream, ImageFormat);\n }\n\n private static string GetMimeType(ImageFormat imageFormat)\n {\n ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();\n return codecs.First(codec => codec.FormatID == imageFormat.Guid).MimeType;\n }\n}\npublic ActionResult Index()\n {\n return new ImageResult { Image = image, ImageFormat = ImageFormat.Jpeg };\n }\n <%=Html.Image<CapchaController>(c => c.Index(), 120, 30, \"Current time\")%>\n</code></pre>\n"
},
{
"answer_id": 7961062,
"author": "JustinStolle",
"author_id": 92389,
"author_profile": "https://Stackoverflow.com/users/92389",
"pm_score": 4,
"selected": false,
"text": "<p>Why not go simple and use the tilde <code>~</code> operator?</p>\n\n<pre><code>public FileResult TopBanner() {\n return File(\"~/Content/images/topbanner.png\", \"image/png\");\n}\n</code></pre>\n"
},
{
"answer_id": 24593278,
"author": "Ajay Kelkar",
"author_id": 166461,
"author_profile": "https://Stackoverflow.com/users/166461",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Solution 1: To render an image in a view from an image URL</strong></p>\n\n<p>You can create your own extension method:</p>\n\n<pre><code>public static MvcHtmlString Image(this HtmlHelper helper,string imageUrl)\n{\n string tag = \"<img src='{0}'/>\";\n tag = string.Format(tag,imageUrl);\n return MvcHtmlString.Create(tag);\n}\n</code></pre>\n\n<p>Then use it like:</p>\n\n<pre><code>@Html.Image(@Model.ImagePath);\n</code></pre>\n\n<p><strong>Solution 2: To render image from database</strong></p>\n\n<p>Create a controller method that returns image data like below</p>\n\n<pre><code>public sealed class ImageController : Controller\n{\n public ActionResult View(string id)\n {\n var image = _images.LoadImage(id); //Pull image from the database.\n if (image == null) \n return HttpNotFound();\n return File(image.Data, image.Mime);\n }\n}\n</code></pre>\n\n<p>And use it in a view like:</p>\n\n<pre><code>@ { Html.RenderAction(\"View\",\"Image\",new {[email protected]})}\n</code></pre>\n\n<p>To use an image rendered from this actionresult in any HTML, use</p>\n\n<pre><code><img src=\"http://something.com/image/view?id={imageid}>\n</code></pre>\n"
},
{
"answer_id": 36038457,
"author": "Avinash Urs",
"author_id": 6007967,
"author_profile": "https://Stackoverflow.com/users/6007967",
"pm_score": 3,
"selected": false,
"text": "<p>you can use File to return a file like View, Content etc </p>\n\n<pre><code> public ActionResult PrintDocInfo(string Attachment)\n {\n string test = Attachment;\n if (test != string.Empty || test != \"\" || test != null)\n {\n string filename = Attachment.Split('\\\\').Last();\n string filepath = Attachment;\n byte[] filedata = System.IO.File.ReadAllBytes(Attachment);\n string contentType = MimeMapping.GetMimeMapping(Attachment);\n\n System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition\n {\n FileName = filename,\n Inline = true,\n };\n\n Response.AppendHeader(\"Content-Disposition\", cd.ToString());\n\n return File(filedata, contentType); \n }\n else { return Content(\"<h3> Patient Clinical Document Not Uploaded</h3>\"); }\n\n }\n</code></pre>\n"
},
{
"answer_id": 49744220,
"author": "hmojica",
"author_id": 3455589,
"author_profile": "https://Stackoverflow.com/users/3455589",
"pm_score": 3,
"selected": false,
"text": "<p>This worked for me.\nSince I'm storing images on a SQL Server database.</p>\n\n<pre><code> [HttpGet(\"/image/{uuid}\")]\n public IActionResult GetImageFile(string uuid) {\n ActionResult actionResult = new NotFoundResult();\n var fileImage = _db.ImageFiles.Find(uuid);\n if (fileImage != null) {\n actionResult = new FileContentResult(fileImage.Data,\n fileImage.ContentType);\n }\n return actionResult;\n }\n</code></pre>\n\n<p>In the snippet above <code>_db.ImageFiles.Find(uuid)</code> is searching for the image file record in the db (EF context). It returns a FileImage object which is just a custom class I made for the model and then uses it as FileContentResult.</p>\n\n<pre><code>public class FileImage {\n public string Uuid { get; set; }\n public byte[] Data { get; set; }\n public string ContentType { get; set; }\n}\n</code></pre>\n"
},
{
"answer_id": 57573210,
"author": "Shriram Navaratnalingam",
"author_id": 10031056,
"author_profile": "https://Stackoverflow.com/users/10031056",
"pm_score": 2,
"selected": false,
"text": "<p>I also encountered similar requirement,</p>\n\n<p>So in my case I make a request to Controller with the image folder path, which in return sends back a ImageResult object.</p>\n\n<p>Following code snippet illustrate the work:</p>\n\n<pre><code>var src = string.Format(\"/GenericGrid.mvc/DocumentPreviewImageLink?fullpath={0}&routingId={1}&siteCode={2}\", fullFilePath, metaInfo.RoutingId, da.SiteCode);\n\n if (enlarged)\n result = \"<a class='thumbnail' href='#thumb'>\" +\n \"<img src='\" + src + \"' height='66px' border='0' />\" +\n \"<span><img src='\" + src + \"' /></span>\" +\n \"</a>\";\n else\n result = \"<span><img src='\" + src + \"' height='150px' border='0' /></span>\";\n</code></pre>\n\n<p>And in the Controller from the the image path I produce the image and return it back to the caller</p>\n\n<pre><code>try\n{\n var file = new FileInfo(fullpath);\n if (!file.Exists)\n return string.Empty;\n\n\n var image = new WebImage(fullpath);\n return new ImageResult(new MemoryStream(image.GetBytes()), \"image/jpg\");\n\n\n}\ncatch(Exception ex)\n{\n return \"File Error : \"+ex.ToString();\n}\n</code></pre>\n"
},
{
"answer_id": 58392435,
"author": "Youngjae",
"author_id": 361100,
"author_profile": "https://Stackoverflow.com/users/361100",
"pm_score": 3,
"selected": false,
"text": "<p>Below code utilizes <code>System.Drawing.Bitmap</code> to load the image.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using System.Drawing;\nusing System.Drawing.Imaging;\n\npublic IActionResult Get()\n{\n string filename = "Image/test.jpg";\n var bitmap = new Bitmap(filename);\n\n var ms = new System.IO.MemoryStream();\n bitmap.Save(ms, ImageFormat.Jpeg);\n ms.Position = 0;\n return new FileStreamResult(ms, "image/jpeg");\n}\n</code></pre>\n"
},
{
"answer_id": 59436372,
"author": "mekb",
"author_id": 11585798,
"author_profile": "https://Stackoverflow.com/users/11585798",
"pm_score": 2,
"selected": false,
"text": "<p>Read the image, convert it to <code>byte[]</code>, then return a <code>File()</code> with a content type. </p>\n\n<pre><code>public ActionResult ImageResult(Image image, ImageFormat format, string contentType) {\n using (var stream = new MemoryStream())\n {\n image.Save(stream, format);\n return File(stream.ToArray(), contentType);\n }\n }\n}\n</code></pre>\n\n<p>Here are the usings:</p>\n\n<pre><code>using System.Drawing;\nusing System.Drawing.Imaging;\nusing System.IO;\nusing Microsoft.AspNetCore.Mvc;\n</code></pre>\n"
},
{
"answer_id": 63945194,
"author": "Imran",
"author_id": 5351352,
"author_profile": "https://Stackoverflow.com/users/5351352",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Yes you can return Image</strong></p>\n<pre><code>public ActionResult GetImage(string imageFileName)\n{\n var path = Path.Combine(Server.MapPath("/Images"), imageFileName + ".jpg"); \n return base.File(path, "image/jpeg");\n}\n</code></pre>\n<p><strong>(Please don't forget to mark this as answer)</strong></p>\n"
},
{
"answer_id": 71250836,
"author": "Ben",
"author_id": 959229,
"author_profile": "https://Stackoverflow.com/users/959229",
"pm_score": 1,
"selected": false,
"text": "<p>From a byte[] under Core 3.2, you can use:</p>\n<pre><code>public ActionResult Img(int? id) {\n MemoryStream ms = new MemoryStream(GetBytes(id));\n return new FileStreamResult(ms, "image/png");\n}\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23341/"
] |
Can I create a Controller that simply returns an image asset?
I would like to route this logic through a controller, whenever a URL such as the following is requested:
```
www.mywebsite.com/resource/image/topbanner
```
The controller will look up `topbanner.png` and send that image directly back to the client.
I've seen examples of this where you have to create a View - I don't want to use a View. I want to do it all with just the Controller.
Is this possible?
|
Use the base controllers File method.
```
public ActionResult Image(string id)
{
var dir = Server.MapPath("/Images");
var path = Path.Combine(dir, id + ".jpg"); //validate the path for security or use other means to generate the path.
return base.File(path, "image/jpeg");
}
```
As a note, this seems to be fairly efficient. I did a test where I requested the image through the controller (`http://localhost/MyController/Image/MyImage`) and through the direct URL (`http://localhost/Images/MyImage.jpg`) and the results were:
* **MVC:** 7.6 milliseconds per photo
* **Direct:** 6.7 milliseconds per photo
Note: this is the average time of a request. The average was calculated by making thousands of requests on the local machine, so the totals should not include network latency or bandwidth issues.
|
186,071 |
<p>I've been profiling some queries in an application I'm working on, and I came across a query that was retrieving more rows than necessary, the result set being trimmed down in the application code.</p>
<p>Changing a LEFT JOIN to an INNER JOIN trimmed the result set to just what was needed, and presumably would also be more performant (since less rows are selected). In reality, the LEFT JOIN'ed query was outperforming the INNER JOIN'ed, taking half the time to complete.</p>
<p>LEFT JOIN: (127 total rows, Query took 0.0011 sec)</p>
<p>INNER JOIN: (10 total rows, Query took 0.0024 sec)</p>
<p>(I ran the queries multiple times and those are averages).</p>
<p>Running EXPLAIN on both reveals nothing that explains the performance differences:</p>
<p>For the INNER JOIN:</p>
<pre><code>id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE contacts index NULL name 302 NULL 235 Using where
1 SIMPLE lists eq_ref PRIMARY PRIMARY 4 contacts.list_id 1
1 SIMPLE lists_to_users eq_ref PRIMARY PRIMARY 8 lists.id,const 1
1 SIMPLE tags eq_ref PRIMARY PRIMARY 4 lists_to_users.tag_id 1
1 SIMPLE users eq_ref email_2 email_2 302 contacts.email 1 Using where
</code></pre>
<p>For the LEFT JOIN:</p>
<pre><code>id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE contacts index NULL name 302 NULL 235 Using where
1 SIMPLE lists eq_ref PRIMARY PRIMARY 4 contacts.list_id 1
1 SIMPLE lists_to_users eq_ref PRIMARY PRIMARY 8 lists.id,const 1
1 SIMPLE tags eq_ref PRIMARY PRIMARY 4 lists_to_users.tag_id 1
1 SIMPLE users eq_ref email_2 email_2 302 contacts.email 1
</code></pre>
<p>And the query itself:</p>
<pre><code>SELECT `contacts`.*, `lists`.`name` AS `group`, `lists`.`id` AS `group_id`, `lists`.`shared_yn`, `tags`.`name` AS `context`, `tags`.`id` AS `context_id`, `tags`.`color` AS `context_color`, `users`.`id` AS `user_id`, `users`.`avatar`
FROM `contacts`
LEFT JOIN `lists` ON lists.id=contacts.list_id
LEFT JOIN `lists_to_users` ON lists_to_users.list_id=lists.id AND lists_to_users.user_id='1' AND lists_to_users.creator='1'
LEFT JOIN `tags` ON tags.id=lists_to_users.tag_id
INNER JOIN `users` ON users.email=contacts.email
WHERE (contacts.user_id='1')
ORDER BY `contacts`.`name` ASC
</code></pre>
<p>(The clause that I'm talking about is the last INNER JOIN on the 'users' table)</p>
<p>The query runs on a MySQL 5.1 database, if it makes a difference.</p>
<p>Does anyone has a clue on why the LEFT JOIN'ed query outperforms the INNER JOIN'ed on in this case?</p>
<p><strong>UPDATE:</strong> Due to Tomalak's suggestion that the small tables I'm using were making the INNER JOIN more complex, I'd created a test database with some mock data. The 'users' table is 5000 rows, and the contacts table is ~500,000 rows. The results are the same (also the timings haven't changed which is surprising when you consider that the tables are much bigger now).</p>
<p>I also ran ANALYZE and OPTIMIZE on the contacts table. Didn't make any discernible difference.</p>
|
[
{
"answer_id": 186120,
"author": "HAdes",
"author_id": 11989,
"author_profile": "https://Stackoverflow.com/users/11989",
"pm_score": 3,
"selected": false,
"text": "<p>It's probably due to the INNER JOIN having to check each row in both tables to see if the column values (email in your case) match. The LEFT JOIN will return all from one table regardless. If it's indexed then it will know what to do faster too.</p>\n"
},
{
"answer_id": 186183,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "<p>Table cardinality has an influence on the query optimizer. I guess small tables as you have make the inner join the more complex operation. As soon as you have more records than the DB server is willing to keep in memory, the inner join will probably begin to outperform the left join.</p>\n"
},
{
"answer_id": 186267,
"author": "Greg Dean",
"author_id": 1200558,
"author_profile": "https://Stackoverflow.com/users/1200558",
"pm_score": 2,
"selected": false,
"text": "<p>imo you are falling into the pitfall known as premature optimization. Query optimizers are insanely fickle things. My suggestion, is to move on until you can identify for sure that the a particular join is problematic.</p>\n"
},
{
"answer_id": 186519,
"author": "mike",
"author_id": 19217,
"author_profile": "https://Stackoverflow.com/users/19217",
"pm_score": -1,
"selected": false,
"text": "<p>LEFT JOIN is returning more rows than INNER JOIN because these 2 are different.<br />\nIf LEFT JOIN does not find related entry in the table it is looking for, it will return NULLs for the table.<br />\nBut if INNER JOIN does not find related entry, it will not return the <strong>whole</strong> row at all.</p>\n\n<p>But to your question, do you have query_cache enabled?\nTry running the query with </p>\n\n<pre><code>SELECT SQL_NO_CACHE `contacts`.*, ...\n</code></pre>\n\n<p>Other than that, I'd populate the tables with more data, ran </p>\n\n<pre><code>ANALYZE TABLE t1, t2;\nOPTIMIZE TABLE t1, t2;\n</code></pre>\n\n<p>And see what happens.</p>\n"
},
{
"answer_id": 188517,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 4,
"selected": false,
"text": "<p>If you think that the implementation of LEFT JOIN is INNER JOIN + more work, then this result is confusing. What if the implementation of INNER JOIN is (LEFT JOIN + filtering)? Ah, it is clear now.</p>\n\n<p>In the query plans, the only difference is this: <em>users... extra: using where</em> . This means filtering. There's an <strong>extra filtering step</strong> in the query with the inner join.</p>\n\n<hr>\n\n<p>This is a different kind of filtering than is typically used in a where clause. It is simple to create an index on A to support this filtering action.</p>\n\n<pre><code>SELECT *\nFROM A\nWHERE A.ID = 3\n</code></pre>\n\n<p>Consider this query:</p>\n\n<pre><code>SELECT *\nFROM A\n LEFT JOIN B\n ON A.ID = B.ID\nWHERE B.ID is not null\n</code></pre>\n\n<p>This query is equivalent to inner join. There is no index on B that will help that filtering action. The reason is that the where clause is stating a condition on the result of the join, instead of a condition on B.</p>\n"
},
{
"answer_id": 778911,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>SELECT `contacts`.*, `lists`.`name` AS `group`, `lists`.`id` AS `group_id`, `lists`.`shared_yn`, `tags`.`name` AS `context`, `tags`.`id` AS `context_id`, `tags`.`color` AS `context_color`, `users`.`id` AS `user_id`, `users`.`avatar` \nFROM `contacts` \nINNER JOIN `users` ON contacts.user_id='1' AND users.email=contacts.email\nLEFT JOIN `lists` ON lists.id=contacts.list_id \nLEFT JOIN `lists_to_users` ON lists_to_users.user_id='1' AND lists_to_users.creator='1' AND lists_to_users.list_id=lists.id\nLEFT JOIN `tags` ON tags.id=lists_to_users.tag_id \nORDER BY `contacts`.`name` ASC\n</code></pre>\n\n<p>That should give you an extra performance because:</p>\n\n<ul>\n<li>You put all the inner joins before any \"left\" or \"right\" join appears. This filters out some records before applying the subsequent outer joins</li>\n<li>The short-circuit of the \"AND\" operators (order of the \"AND\" matters). If the comparition between the columns and the literals is false, it won't execute the required table scan for the comparition between the tables PKs and FKs</li>\n</ul>\n\n<p>If you don't find any performance improvement, then replace all the columnset for a \"COUNT(*)\" and do your left/inner tests. This way, regardless of the query, you will retrieve only 1 single row with 1 single column (the count), so you can discard that the number of returned bytes is the cause of the slowness of your query:</p>\n\n<pre><code>SELECT COUNT(*)\nFROM `contacts` \nINNER JOIN `users` ON contacts.user_id='1' AND users.email=contacts.email\nLEFT JOIN `lists` ON lists.id=contacts.list_id \nLEFT JOIN `lists_to_users` ON lists_to_users.user_id='1' AND lists_to_users.creator='1' AND lists_to_users.list_id=lists.id\nLEFT JOIN `tags` ON tags.id=lists_to_users.tag_id \n</code></pre>\n\n<p>Good luck</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10585/"
] |
I've been profiling some queries in an application I'm working on, and I came across a query that was retrieving more rows than necessary, the result set being trimmed down in the application code.
Changing a LEFT JOIN to an INNER JOIN trimmed the result set to just what was needed, and presumably would also be more performant (since less rows are selected). In reality, the LEFT JOIN'ed query was outperforming the INNER JOIN'ed, taking half the time to complete.
LEFT JOIN: (127 total rows, Query took 0.0011 sec)
INNER JOIN: (10 total rows, Query took 0.0024 sec)
(I ran the queries multiple times and those are averages).
Running EXPLAIN on both reveals nothing that explains the performance differences:
For the INNER JOIN:
```
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE contacts index NULL name 302 NULL 235 Using where
1 SIMPLE lists eq_ref PRIMARY PRIMARY 4 contacts.list_id 1
1 SIMPLE lists_to_users eq_ref PRIMARY PRIMARY 8 lists.id,const 1
1 SIMPLE tags eq_ref PRIMARY PRIMARY 4 lists_to_users.tag_id 1
1 SIMPLE users eq_ref email_2 email_2 302 contacts.email 1 Using where
```
For the LEFT JOIN:
```
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE contacts index NULL name 302 NULL 235 Using where
1 SIMPLE lists eq_ref PRIMARY PRIMARY 4 contacts.list_id 1
1 SIMPLE lists_to_users eq_ref PRIMARY PRIMARY 8 lists.id,const 1
1 SIMPLE tags eq_ref PRIMARY PRIMARY 4 lists_to_users.tag_id 1
1 SIMPLE users eq_ref email_2 email_2 302 contacts.email 1
```
And the query itself:
```
SELECT `contacts`.*, `lists`.`name` AS `group`, `lists`.`id` AS `group_id`, `lists`.`shared_yn`, `tags`.`name` AS `context`, `tags`.`id` AS `context_id`, `tags`.`color` AS `context_color`, `users`.`id` AS `user_id`, `users`.`avatar`
FROM `contacts`
LEFT JOIN `lists` ON lists.id=contacts.list_id
LEFT JOIN `lists_to_users` ON lists_to_users.list_id=lists.id AND lists_to_users.user_id='1' AND lists_to_users.creator='1'
LEFT JOIN `tags` ON tags.id=lists_to_users.tag_id
INNER JOIN `users` ON users.email=contacts.email
WHERE (contacts.user_id='1')
ORDER BY `contacts`.`name` ASC
```
(The clause that I'm talking about is the last INNER JOIN on the 'users' table)
The query runs on a MySQL 5.1 database, if it makes a difference.
Does anyone has a clue on why the LEFT JOIN'ed query outperforms the INNER JOIN'ed on in this case?
**UPDATE:** Due to Tomalak's suggestion that the small tables I'm using were making the INNER JOIN more complex, I'd created a test database with some mock data. The 'users' table is 5000 rows, and the contacts table is ~500,000 rows. The results are the same (also the timings haven't changed which is surprising when you consider that the tables are much bigger now).
I also ran ANALYZE and OPTIMIZE on the contacts table. Didn't make any discernible difference.
|
If you think that the implementation of LEFT JOIN is INNER JOIN + more work, then this result is confusing. What if the implementation of INNER JOIN is (LEFT JOIN + filtering)? Ah, it is clear now.
In the query plans, the only difference is this: *users... extra: using where* . This means filtering. There's an **extra filtering step** in the query with the inner join.
---
This is a different kind of filtering than is typically used in a where clause. It is simple to create an index on A to support this filtering action.
```
SELECT *
FROM A
WHERE A.ID = 3
```
Consider this query:
```
SELECT *
FROM A
LEFT JOIN B
ON A.ID = B.ID
WHERE B.ID is not null
```
This query is equivalent to inner join. There is no index on B that will help that filtering action. The reason is that the where clause is stating a condition on the result of the join, instead of a condition on B.
|
186,084 |
<p>Just this - How do you add a timer to a C# console application? It would be great if you could supply some example coding.</p>
|
[
{
"answer_id": 186086,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 6,
"selected": false,
"text": "<p>Use the System.Threading.Timer class.</p>\n\n<p>System.Windows.Forms.Timer is designed primarily for use in a single thread usually the Windows Forms UI thread.</p>\n\n<p>There is also a System.Timers class added early on in the development of the .NET framework. However it is generally recommended to use the System.Threading.Timer class instead as this is just a wrapper around System.Threading.Timer anyway.</p>\n\n<p>It is also recommended to always use a static (shared in VB.NET) System.Threading.Timer if you are developing a Windows Service and require a timer to run periodically. This will avoid possibly premature garbage collection of your timer object.</p>\n\n<p>Here's an example of a timer in a console application:</p>\n\n<pre><code>using System; \nusing System.Threading; \npublic static class Program \n{ \n public static void Main() \n { \n Console.WriteLine(\"Main thread: starting a timer\"); \n Timer t = new Timer(ComputeBoundOp, 5, 0, 2000); \n Console.WriteLine(\"Main thread: Doing other work here...\");\n Thread.Sleep(10000); // Simulating other work (10 seconds)\n t.Dispose(); // Cancel the timer now\n }\n // This method's signature must match the TimerCallback delegate\n private static void ComputeBoundOp(Object state) \n { \n // This method is executed by a thread pool thread \n Console.WriteLine(\"In ComputeBoundOp: state={0}\", state); \n Thread.Sleep(1000); // Simulates other work (1 second)\n // When this method returns, the thread goes back \n // to the pool and waits for another task \n }\n}\n</code></pre>\n\n<p>From the book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0735621632\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">CLR Via C#</a> by Jeff Richter. By the way this book describes the rationale behind the 3 types of timers in Chapter 23, highly recommended.</p>\n"
},
{
"answer_id": 186114,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 5,
"selected": false,
"text": "<p>Here is the code to create a simple one second timer tick:</p>\n\n<pre><code> using System;\n using System.Threading;\n\n class TimerExample\n {\n static public void Tick(Object stateInfo)\n {\n Console.WriteLine(\"Tick: {0}\", DateTime.Now.ToString(\"h:mm:ss\"));\n }\n\n static void Main()\n {\n TimerCallback callback = new TimerCallback(Tick);\n\n Console.WriteLine(\"Creating timer: {0}\\n\", \n DateTime.Now.ToString(\"h:mm:ss\"));\n\n // create a one second timer tick\n Timer stateTimer = new Timer(callback, null, 0, 1000);\n\n // loop here forever\n for (; ; )\n {\n // add a sleep for 100 mSec to reduce CPU usage\n Thread.Sleep(100);\n }\n }\n }\n</code></pre>\n\n<p>And here is the resulting output:</p>\n\n<pre><code> c:\\temp>timer.exe\n Creating timer: 5:22:40\n\n Tick: 5:22:40\n Tick: 5:22:41\n Tick: 5:22:42\n Tick: 5:22:43\n Tick: 5:22:44\n Tick: 5:22:45\n Tick: 5:22:46\n Tick: 5:22:47\n</code></pre>\n\n<p><strong>EDIT:</strong> It is never a good idea to add hard spin loops into code as they consume CPU cycles for no gain. In this case that loop was added just to stop the application from closing, allowing the actions of the thread to be observed. But for the sake of correctness and to reduce the CPU usage a simple Sleep call was added to that loop.</p>\n"
},
{
"answer_id": 186134,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use your own timing mechanisms if you want a little more control, but possibly less accuracy and more code/complexity, but I would still recommend a timer. Use this though if you need to have control over the actual timing thread:</p>\n\n<pre><code>private void ThreadLoop(object callback)\n{\n while(true)\n {\n ((Delegate) callback).DynamicInvoke(null);\n Thread.Sleep(5000);\n }\n}\n</code></pre>\n\n<p>would be your timing thread(modify this to stop when reqiuired, and at whatever time interval you want).</p>\n\n<p>and to use/start you can do:</p>\n\n<pre><code>Thread t = new Thread(new ParameterizedThreadStart(ThreadLoop));\n\nt.Start((Action)CallBack);\n</code></pre>\n\n<p>Callback is your void parameterless method that you want called at each interval. For example:</p>\n\n<pre><code>private void CallBack()\n{\n //Do Something.\n}\n</code></pre>\n"
},
{
"answer_id": 7865126,
"author": "Khalid Al Hajami",
"author_id": 1009327,
"author_profile": "https://Stackoverflow.com/users/1009327",
"pm_score": 8,
"selected": true,
"text": "<p>That's very nice, however in order to simulate some time passing we need to run a command that takes some time and that's very clear in second example.</p>\n<p>However, the style of using a for loop to do some functionality forever takes a lot of device resources and instead we can use the Garbage Collector to do some thing like that.</p>\n<p>We can see this modification in the code from the same book CLR Via C# Third Ed.</p>\n<pre><code>using System;\nusing System.Threading;\n\npublic static class Program \n{\n private Timer _timer = null;\n public static void Main() \n {\n // Create a Timer object that knows to call our TimerCallback\n // method once every 2000 milliseconds.\n _timer = new Timer(TimerCallback, null, 0, 2000);\n // Wait for the user to hit <Enter>\n Console.ReadLine();\n }\n\n private static void TimerCallback(Object o) \n {\n // Display the date/time when this method got called.\n Console.WriteLine("In TimerCallback: " + DateTime.Now);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 14537741,
"author": "Yonatan Zetuny",
"author_id": 1064546,
"author_profile": "https://Stackoverflow.com/users/1064546",
"pm_score": 3,
"selected": false,
"text": "<p>Or using Rx, short and sweet:</p>\n\n<pre><code>static void Main()\n{\nObservable.Interval(TimeSpan.FromSeconds(10)).Subscribe(t => Console.WriteLine(\"I am called... {0}\", t));\n\nfor (; ; ) { }\n}\n</code></pre>\n"
},
{
"answer_id": 19440583,
"author": "Steven de Salas",
"author_id": 448568,
"author_profile": "https://Stackoverflow.com/users/448568",
"pm_score": 2,
"selected": false,
"text": "<p><strong>You can also create your own (if unhappy with the options available).</strong></p>\n\n<p>Creating your own <code>Timer</code> implementation is pretty basic stuff.</p>\n\n<p>This is an example for an application that needed COM object access on the same thread as the rest of my codebase.</p>\n\n<pre><code>/// <summary>\n/// Internal timer for window.setTimeout() and window.setInterval().\n/// This is to ensure that async calls always run on the same thread.\n/// </summary>\npublic class Timer : IDisposable {\n\n public void Tick()\n {\n if (Enabled && Environment.TickCount >= nextTick)\n {\n Callback.Invoke(this, null);\n nextTick = Environment.TickCount + Interval;\n }\n }\n\n private int nextTick = 0;\n\n public void Start()\n {\n this.Enabled = true;\n Interval = interval;\n }\n\n public void Stop()\n {\n this.Enabled = false;\n }\n\n public event EventHandler Callback;\n\n public bool Enabled = false;\n\n private int interval = 1000;\n\n public int Interval\n {\n get { return interval; }\n set { interval = value; nextTick = Environment.TickCount + interval; }\n }\n\n public void Dispose()\n {\n this.Callback = null;\n this.Stop();\n }\n\n}\n</code></pre>\n\n<p>You can add events as follows:</p>\n\n<pre><code>Timer timer = new Timer();\ntimer.Callback += delegate\n{\n if (once) { timer.Enabled = false; }\n Callback.execute(callbackId, args);\n};\ntimer.Enabled = true;\ntimer.Interval = ms;\ntimer.Start();\nWindow.timers.Add(Environment.TickCount, timer);\n</code></pre>\n\n<p>To make sure the timer works you need to create an endless loop as follows:</p>\n\n<pre><code>while (true) {\n // Create a new list in case a new timer\n // is added/removed during a callback.\n foreach (Timer timer in new List<Timer>(timers.Values))\n {\n timer.Tick();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 24232554,
"author": "Real Caz",
"author_id": 3478270,
"author_profile": "https://Stackoverflow.com/users/3478270",
"pm_score": 4,
"selected": false,
"text": "<p>Lets Have A little Fun</p>\n\n<pre><code>using System;\nusing System.Timers;\n\nnamespace TimerExample\n{\n class Program\n {\n static Timer timer = new Timer(1000);\n static int i = 10;\n\n static void Main(string[] args)\n { \n timer.Elapsed+=timer_Elapsed;\n timer.Start(); Console.Read();\n }\n\n private static void timer_Elapsed(object sender, ElapsedEventArgs e)\n {\n i--;\n\n Console.Clear();\n Console.WriteLine(\"=================================================\");\n Console.WriteLine(\" DEFUSE THE BOMB\");\n Console.WriteLine(\"\"); \n Console.WriteLine(\" Time Remaining: \" + i.ToString());\n Console.WriteLine(\"\"); \n Console.WriteLine(\"=================================================\");\n\n if (i == 0) \n {\n Console.Clear();\n Console.WriteLine(\"\");\n Console.WriteLine(\"==============================================\");\n Console.WriteLine(\" B O O O O O M M M M M ! ! ! !\");\n Console.WriteLine(\"\");\n Console.WriteLine(\" G A M E O V E R\");\n Console.WriteLine(\"==============================================\");\n\n timer.Close();\n timer.Dispose();\n }\n\n GC.Collect();\n }\n }\n}\n</code></pre>\n\n\n"
},
{
"answer_id": 59325239,
"author": "XvXLuka222",
"author_id": 12532096,
"author_profile": "https://Stackoverflow.com/users/12532096",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.8\" rel=\"nofollow noreferrer\">doc</a></p>\n\n<p>There you have it :)</p>\n\n<pre><code>public static void Main()\n {\n SetTimer();\n\n Console.WriteLine(\"\\nPress the Enter key to exit the application...\\n\");\n Console.WriteLine(\"The application started at {0:HH:mm:ss.fff}\", DateTime.Now);\n Console.ReadLine();\n aTimer.Stop();\n aTimer.Dispose();\n\n Console.WriteLine(\"Terminating the application...\");\n }\n\n private static void SetTimer()\n {\n // Create a timer with a two second interval.\n aTimer = new System.Timers.Timer(2000);\n // Hook up the Elapsed event for the timer. \n aTimer.Elapsed += OnTimedEvent;\n aTimer.AutoReset = true;\n aTimer.Enabled = true;\n }\n\n private static void OnTimedEvent(Object source, ElapsedEventArgs e)\n {\n Console.WriteLine(\"The Elapsed event was raised at {0:HH:mm:ss.fff}\",\n e.SignalTime);\n }\n</code></pre>\n"
},
{
"answer_id": 60019884,
"author": "Ayub",
"author_id": 579381,
"author_profile": "https://Stackoverflow.com/users/579381",
"pm_score": 2,
"selected": false,
"text": "<p>In C# 5.0+ and .NET Framework 4.5+ you can use async/await:</p>\n\n<pre><code>async void RunMethodEvery(Action method, double seconds)\n{\n while (true)\n {\n await Task.Delay(TimeSpan.FromSeconds(seconds));\n method();\n }\n }\n</code></pre>\n"
},
{
"answer_id": 62138578,
"author": "Alessio Di Salvo",
"author_id": 2327256,
"author_profile": "https://Stackoverflow.com/users/2327256",
"pm_score": 0,
"selected": false,
"text": "<p>I suggest you following Microsoft guidelines (\n<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer.interval?view=netcore-3.1\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer.interval?view=netcore-3.1</a>).</p>\n\n<p>I first tried using <code>System.Threading;</code> with</p>\n\n<pre><code>var myTimer = new Timer((e) =>\n{\n // Code\n}, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));\n\n</code></pre>\n\n<p>but it continuously stopped after ~20 minutes.</p>\n\n<p>With that, I tried the solutions setting </p>\n\n<pre><code>GC.KeepAlive(myTimer)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>for (; ; ) { }\n}\n</code></pre>\n\n<p>but they didn't work in my case.</p>\n\n<p>Following Microsoft documentation, it worked perfectly:</p>\n\n<pre><code>using System;\nusing System.Timers;\n\npublic class Example\n{\n private static Timer aTimer;\n\n public static void Main()\n {\n // Create a timer and set a two second interval.\n aTimer = new System.Timers.Timer();\n aTimer.Interval = 2000;\n\n // Hook up the Elapsed event for the timer. \n aTimer.Elapsed += OnTimedEvent;\n\n // Have the timer fire repeated events (true is the default)\n aTimer.AutoReset = true;\n\n // Start the timer\n aTimer.Enabled = true;\n\n Console.WriteLine(\"Press the Enter key to exit the program at any time... \");\n Console.ReadLine();\n }\n\n private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)\n {\n Console.WriteLine(\"The Elapsed event was raised at {0}\", e.SignalTime);\n }\n}\n// The example displays output like the following: \n// Press the Enter key to exit the program at any time... \n// The Elapsed event was raised at 5/20/2015 8:48:58 PM \n// The Elapsed event was raised at 5/20/2015 8:49:00 PM \n// The Elapsed event was raised at 5/20/2015 8:49:02 PM \n// The Elapsed event was raised at 5/20/2015 8:49:04 PM \n// The Elapsed event was raised at 5/20/2015 8:49:06 PM \n</code></pre>\n"
},
{
"answer_id": 64139996,
"author": "Bigabdoul",
"author_id": 1831949,
"author_profile": "https://Stackoverflow.com/users/1831949",
"pm_score": 1,
"selected": false,
"text": "<p>Use the PowerConsole project on Github at <a href=\"https://github.com/bigabdoul/PowerConsole\" rel=\"nofollow noreferrer\">https://github.com/bigabdoul/PowerConsole</a> or the equivalent NuGet package at <a href=\"https://www.nuget.org/packages/PowerConsole\" rel=\"nofollow noreferrer\">https://www.nuget.org/packages/PowerConsole</a>. It elegantly handles timers in a reusable fashion. Take a look at this sample code:</p>\n<pre><code>using PowerConsole;\n\nnamespace PowerConsoleTest\n{\n class Program\n {\n static readonly SmartConsole MyConsole = SmartConsole.Default;\n\n static void Main()\n {\n RunTimers();\n }\n\n public static void RunTimers()\n {\n // CAUTION: SmartConsole is not thread safe!\n // Spawn multiple timers carefully when accessing\n // simultaneously members of the SmartConsole class.\n\n MyConsole.WriteInfo("\\nWelcome to the Timers demo!\\n")\n\n // SetTimeout is called only once after the provided delay and\n // is automatically removed by the TimerManager class\n .SetTimeout(e =>\n {\n // this action is called back after 5.5 seconds; the name\n // of the timer is useful should we want to clear it\n // before this action gets executed\n e.Console.Write("\\n").WriteError("Time out occured after 5.5 seconds! " +\n "Timer has been automatically disposed.\\n");\n\n // the next statement will make the current instance of \n // SmartConsole throw an exception on the next prompt attempt\n // e.Console.CancelRequested = true;\n\n // use 5500 or any other value not multiple of 1000 to \n // reduce write collision risk with the next timer\n }, millisecondsDelay: 5500, name: "SampleTimeout")\n\n .SetInterval(e =>\n {\n if (e.Ticks == 1)\n {\n e.Console.WriteLine();\n }\n\n e.Console.Write($"\\rFirst timer tick: ", System.ConsoleColor.White)\n .WriteInfo(e.TicksToSecondsElapsed());\n\n if (e.Ticks > 4)\n {\n // we could remove the previous timeout:\n // e.Console.ClearTimeout("SampleTimeout");\n }\n\n }, millisecondsInterval: 1000, "EverySecond")\n\n // we can add as many timers as we want (or the computer's resources permit)\n .SetInterval(e =>\n {\n if (e.Ticks == 1 || e.Ticks == 3) // 1.5 or 4.5 seconds to avoid write collision\n {\n e.Console.WriteSuccess("\\nSecond timer is active...\\n");\n }\n else if (e.Ticks == 5)\n {\n e.Console.WriteWarning("\\nSecond timer is disposing...\\n");\n\n // doesn't dispose the timer\n // e.Timer.Stop();\n\n // clean up if we no longer need it\n e.DisposeTimer();\n }\n else\n {\n System.Diagnostics.Trace.WriteLine($"Second timer tick: {e.Ticks}");\n }\n }, 1500)\n .Prompt("\\nPress Enter to stop the timers: ")\n \n // makes sure that any remaining timer is disposed off\n .ClearTimers()\n\n .WriteSuccess("Timers cleared!\\n");\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 69238786,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>you can use <code>StopWatch</code> class, here's an example</p>\n<pre><code>StopWatch stopwatch = new Stopwatch();\n// creating a new stopwatch class\nstopwatch.Start();\n// starting the stopwatch\nThread.Sleep(10000);\n// waiting for 10 seconds\n\nTimeSpan timespan = stopwatch.Elapsed;\n/* creating a new timespan class and concacting it with the elapsed of the \nstopwatch class */\nstring time = String.Format("{0:00}:{1:00}:{2:00}",\ntimespan.Hours, timespan.Minutes, timespan.Seconds\n);\n\nConsole.Write($"The time right now is {time}");\n\nConsole.ReadKey();\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535708/"
] |
Just this - How do you add a timer to a C# console application? It would be great if you could supply some example coding.
|
That's very nice, however in order to simulate some time passing we need to run a command that takes some time and that's very clear in second example.
However, the style of using a for loop to do some functionality forever takes a lot of device resources and instead we can use the Garbage Collector to do some thing like that.
We can see this modification in the code from the same book CLR Via C# Third Ed.
```
using System;
using System.Threading;
public static class Program
{
private Timer _timer = null;
public static void Main()
{
// Create a Timer object that knows to call our TimerCallback
// method once every 2000 milliseconds.
_timer = new Timer(TimerCallback, null, 0, 2000);
// Wait for the user to hit <Enter>
Console.ReadLine();
}
private static void TimerCallback(Object o)
{
// Display the date/time when this method got called.
Console.WriteLine("In TimerCallback: " + DateTime.Now);
}
}
```
|
186,094 |
<p>I'm setting up a simple SQLite database to hold sensor readings. The tables will look something like this:</p>
<pre><code>sensors
- id (pk)
- name
- description
- units
sensor_readings
- id (pk)
- sensor_id (fk to sensors)
- value (actual sensor value stored here)
- time (date/time the sensor sample was taken)
</code></pre>
<p>The application will be capturing about 100,000 sensor readings per month from about 30 different sensors, and I'd like to keep all sensor readings in the DB as long as possible.</p>
<p>Most queries will be in the form</p>
<pre><code>SELECT * FROM sensor_readings WHERE sensor_id = x AND time > y AND time < z
</code></pre>
<p>This query will usually return about 100-1000 results.</p>
<p>So the question is, how big can the sensor_readings table get before the above query becomes too time consuming (more than a couple seconds on a standard PC).</p>
<p>I know that one fix might be to create a separate sensor_readings table for each sensor, but I'd like to avoid this if it is unnecessary. Are there any other ways to optimize this DB schema?</p>
|
[
{
"answer_id": 186177,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 2,
"selected": false,
"text": "<p>Are you setting indexes properly? Besides that and reading <a href=\"http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html\" rel=\"nofollow noreferrer\">http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html</a>, the only answer is 'you'll have to measure yourself' - especially since this will be heavily dependent on the hardware and on whether you're using an in-memory database or on disk, and on if you wrap inserts in transactions or not.</p>\n\n<p>That being said, I've hit noticeable delays after a couple of tens of thousands of rows, but that was absolutely non-optimized - from reading a bit I get the impression that there are people with 100's of thousands of rows with proper indexes etc. who have no problems at all.</p>\n"
},
{
"answer_id": 186337,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "<p>If you're going to be using <code>time</code> in the queries, it's worthwhile adding an index to it. That would be the only optimization I would suggest based on your information.</p>\n\n<p>100,000 insertions per month equates to about 2.3 per minute so another index won't be too onerous and it will speed up your queries. I'm assuming that's 100,000 insertions across all 30 sensors, not 100,000 for each sensor but, even if I'm mistaken, 70 insertions per minute should still be okay.</p>\n\n<p>If performance does become an issue, you have the option to offload older data to a historical table (say, <code>sensor_readings_old</code>) and only do your queries on the non-historical table (<code>sensor_readings</code>).</p>\n\n<p>Then you at least have all the data available without affecting the normal queries. If you really want to get at the older data, you can do so but you'll be aware that the queries for that may take a while longer.</p>\n"
},
{
"answer_id": 197195,
"author": "gobansaor",
"author_id": 8967,
"author_profile": "https://Stackoverflow.com/users/8967",
"pm_score": 1,
"selected": false,
"text": "<p>SQLite now supports R-tree indexes ( <a href=\"http://www.sqlite.org/rtree.html\" rel=\"nofollow noreferrer\">http://www.sqlite.org/rtree.html</a> ), ideal if you intend to do a lot of time range queries.</p>\n\n<p>Tom</p>\n"
},
{
"answer_id": 9168991,
"author": "TimothyAWiseman",
"author_id": 43818,
"author_profile": "https://Stackoverflow.com/users/43818",
"pm_score": 1,
"selected": false,
"text": "<p>I know I am coming to this late, but I thought this might be helpful for anyone that comes looking at this question later: </p>\n\n<p>SQLite tends to be relatively fast on reading as long as it is only serving a single application/user at a time. Concurrency and blocking can become issues with multiple users or applications accessing it at a single time and more robust databases like MS SQL Server tend to work better in a high concurrency environment.</p>\n\n<p>As others have said, I would definitely index the table if you are concerned about the speed of read queries. For your particular case, I would probably create one index that included both id and time.</p>\n\n<p>You may also want to pay attention to the write speed. Insertion can be fast, but commits are slow, so you probably want to batch many insertions together into one transaction before hitting commit. This is discussed here: <a href=\"http://www.sqlite.org/faq.html#q19\" rel=\"nofollow\">http://www.sqlite.org/faq.html#q19</a></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10428/"
] |
I'm setting up a simple SQLite database to hold sensor readings. The tables will look something like this:
```
sensors
- id (pk)
- name
- description
- units
sensor_readings
- id (pk)
- sensor_id (fk to sensors)
- value (actual sensor value stored here)
- time (date/time the sensor sample was taken)
```
The application will be capturing about 100,000 sensor readings per month from about 30 different sensors, and I'd like to keep all sensor readings in the DB as long as possible.
Most queries will be in the form
```
SELECT * FROM sensor_readings WHERE sensor_id = x AND time > y AND time < z
```
This query will usually return about 100-1000 results.
So the question is, how big can the sensor\_readings table get before the above query becomes too time consuming (more than a couple seconds on a standard PC).
I know that one fix might be to create a separate sensor\_readings table for each sensor, but I'd like to avoid this if it is unnecessary. Are there any other ways to optimize this DB schema?
|
Are you setting indexes properly? Besides that and reading <http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html>, the only answer is 'you'll have to measure yourself' - especially since this will be heavily dependent on the hardware and on whether you're using an in-memory database or on disk, and on if you wrap inserts in transactions or not.
That being said, I've hit noticeable delays after a couple of tens of thousands of rows, but that was absolutely non-optimized - from reading a bit I get the impression that there are people with 100's of thousands of rows with proper indexes etc. who have no problems at all.
|
186,099 |
<p>I many times have to work with directories containing hundreds of thousands of files, doing text matching, replacing and so on. If I go the standard route of, say</p>
<pre><code>grep foo *
</code></pre>
<p>I get the too many files error message, so I end up doing</p>
<pre><code>for i in *; do grep foo $i; done
</code></pre>
<p>or</p>
<pre><code>find ../path/ | xargs -I{} grep foo "{}"
</code></pre>
<p>But these are less than optimal (create a new grep process per each file).</p>
<p>This looks like more of a limitation in the size of the arguments programs can receive, because the * in the for loop works alright. But, in any case, what's the proper way to handle this?</p>
<p>PS: Don't tell me to do grep -r instead, I know about that, I'm thinking about tools that do not have a recursive option.</p>
|
[
{
"answer_id": 186139,
"author": "camh",
"author_id": 23744,
"author_profile": "https://Stackoverflow.com/users/23744",
"pm_score": 2,
"selected": false,
"text": "<p>xargs does not start a new process for each file. It bunches together the arguments. Have a look at the -n option to xargs - it controls the number of arguments passed to each execution of the sub-command.</p>\n"
},
{
"answer_id": 186167,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 0,
"selected": false,
"text": "<p>I can't see that</p>\n\n<pre><code>for i in *; do\n grep foo $i\ndone\n</code></pre>\n\n<p>would work since I thought the \"too many files\" was a shell limitation, hence it would fail for the for loop as well.</p>\n\n<p>Having said that, I always let xargs do the grunt-work of splitting the argument list into manageable bits thus:</p>\n\n<pre><code>find ../path/ | xargs grep foo\n</code></pre>\n\n<p>It won't start a process per file but per group of files.</p>\n"
},
{
"answer_id": 186171,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 3,
"selected": false,
"text": "<p>If there is a risk of filenames containing spaces, you should remember to use the -print0 flag to find together with the -0 flag to xargs:</p>\n\n<pre><code>find . -print0 | xargs -0 grep -H foo\n</code></pre>\n"
},
{
"answer_id": 189327,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 4,
"selected": true,
"text": "<p>In newer versions of findutils, find can do the work of xargs (including the glomming behavior, such that only as many grep processes as needed are used):</p>\n\n<pre><code>find ../path -exec grep foo '{}' +\n</code></pre>\n\n<p>The use of <code>+</code> rather than <code>;</code> as the last argument triggers this behavior.</p>\n"
},
{
"answer_id": 189429,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I had the same problems, but it seems that everything I came up with is already mentioned. Mostly, had two problems. Doing globs is expensive, doing ls on a million files directory takes forever (20+ minutes on one of my servers) and doing ls * on a million files directory takes forever and fails with \"argument list too long\" error. </p>\n\n<pre><code>find /some -type f -exec some command {} \\; \n</code></pre>\n\n<p>seems to help with both problems. Also, if you need to do more complex operations on these files, you might consider to script your stuff into multiple threads. Here is a python primer for scripting CLI stuff.\n<a href=\"http://www.ibm.com/developerworks/aix/library/au-pythocli/?ca=dgr-lnxw06pythonunixtool&S_TACT=105AGX59&S_CMP=GR\" rel=\"nofollow noreferrer\">http://www.ibm.com/developerworks/aix/library/au-pythocli/?ca=dgr-lnxw06pythonunixtool&S_TACT=105AGX59&S_CMP=GR</a></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
] |
I many times have to work with directories containing hundreds of thousands of files, doing text matching, replacing and so on. If I go the standard route of, say
```
grep foo *
```
I get the too many files error message, so I end up doing
```
for i in *; do grep foo $i; done
```
or
```
find ../path/ | xargs -I{} grep foo "{}"
```
But these are less than optimal (create a new grep process per each file).
This looks like more of a limitation in the size of the arguments programs can receive, because the \* in the for loop works alright. But, in any case, what's the proper way to handle this?
PS: Don't tell me to do grep -r instead, I know about that, I'm thinking about tools that do not have a recursive option.
|
In newer versions of findutils, find can do the work of xargs (including the glomming behavior, such that only as many grep processes as needed are used):
```
find ../path -exec grep foo '{}' +
```
The use of `+` rather than `;` as the last argument triggers this behavior.
|
186,106 |
<p>I am new to web programming and have been exploring issues related to web security.</p>
<p>I have a form where the user can post two types of data - lets call them "safe" and "unsafe" (from the point of view of sql).</p>
<p>Most places recommend storing both parts of the data in database after sanitizing the "unsafe" part (to make it "safe").</p>
<p>I am wondering about a different approach - to store the "safe" data in database and "unsafe" data in files (outside the database). Ofcourse this approach creates its own set of problems related to maintaining association between files and DB entries. But are there any other major issues with this approach, especially related to security?</p>
<blockquote>
<p>UPDATE: Thanks for the responses! Apologies for not being clear regarding what I am
considering "safe" so some clarification is in order. I am using Django, and the form
data that I am considering "safe" is accessed through the form's "cleaned_data"
dictionary which does all the necessary escaping.</p>
<p>For the purpose of this question, let us consider a wiki page. The title of
wiki page does not need to have any styling attached with it. So, this can be accessed
through form's "cleaned_data" dictionary which will convert the user input to
"safe" format. But since I wish to provide the users the ability to arbitrarily style
their content, I can't perhaps access the content part using "cleaned_data" dictionary.</p>
<p>Does the file approach solve the security aspects of this problem? Or are there other
security issues that I am overlooking?</p>
</blockquote>
|
[
{
"answer_id": 186110,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 0,
"selected": false,
"text": "<p>What do you consider \"safe\" and \"unsafe\"? Are you considering data with the slashes escaped to be \"safe\"? If so, please don't.</p>\n\n<p>Use bound variables with SQL placeholders. It is the only sensible way to protect against SQL injection.</p>\n"
},
{
"answer_id": 186130,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "<p>Splitting your data will not protect you from SQL injection, it'll just limit the data which can be exposed through it, but that's not the only risk of the attack. They can also delete data, add bogus data and so on.</p>\n\n<p>I see no justification to use your approach, especially given that using prepared statements (supported in many, if not all, development platforms and databases).</p>\n\n<p>That without even entering in the nightmare that your approach will end up being.</p>\n\n<p>In the end, <em>why will you use a database if you don't trust it?</em> Just use plain files if you wish, a mix is a no-no.</p>\n"
},
{
"answer_id": 186161,
"author": "Komang",
"author_id": 19463,
"author_profile": "https://Stackoverflow.com/users/19463",
"pm_score": 0,
"selected": false,
"text": "<p>SQL injection can targeted whole database not only user, and it is the matter of query (poisoning query), so for me the best way (if not the only) to avoid SQL injection attack is control your query, protect it from possibility injected with malicious characters rather than splitting the storage.</p>\n"
},
{
"answer_id": 186184,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 1,
"selected": false,
"text": "<p>You know the \"safe\" data you're talking about? It isn't. It's <em>all</em> unsafe and you should treat it as such. Not by storing it al in files, but by properly constructing your SQL statements.</p>\n\n<p>As others have mentioned, using prepared statements, or a library which which simulates them, is the way to go, e.g.</p>\n\n<pre><code>$db->Execute(\"insert into foo(x,y,z) values (?,?,?)\", array($one, $two, $three));\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am new to web programming and have been exploring issues related to web security.
I have a form where the user can post two types of data - lets call them "safe" and "unsafe" (from the point of view of sql).
Most places recommend storing both parts of the data in database after sanitizing the "unsafe" part (to make it "safe").
I am wondering about a different approach - to store the "safe" data in database and "unsafe" data in files (outside the database). Ofcourse this approach creates its own set of problems related to maintaining association between files and DB entries. But are there any other major issues with this approach, especially related to security?
>
> UPDATE: Thanks for the responses! Apologies for not being clear regarding what I am
> considering "safe" so some clarification is in order. I am using Django, and the form
> data that I am considering "safe" is accessed through the form's "cleaned\_data"
> dictionary which does all the necessary escaping.
>
>
> For the purpose of this question, let us consider a wiki page. The title of
> wiki page does not need to have any styling attached with it. So, this can be accessed
> through form's "cleaned\_data" dictionary which will convert the user input to
> "safe" format. But since I wish to provide the users the ability to arbitrarily style
> their content, I can't perhaps access the content part using "cleaned\_data" dictionary.
>
>
> Does the file approach solve the security aspects of this problem? Or are there other
> security issues that I am overlooking?
>
>
>
|
You know the "safe" data you're talking about? It isn't. It's *all* unsafe and you should treat it as such. Not by storing it al in files, but by properly constructing your SQL statements.
As others have mentioned, using prepared statements, or a library which which simulates them, is the way to go, e.g.
```
$db->Execute("insert into foo(x,y,z) values (?,?,?)", array($one, $two, $three));
```
|
186,108 |
<p>In a vxWorks Real-Time process, you can pass environment variables as one of the parameter of the <strong>main</strong> routine.</p>
<p>How do you use the environment variables in the kernel context?</p>
|
[
{
"answer_id": 186119,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 2,
"selected": false,
"text": "<p>Vxworks environment variable support is provided by the envLib.</p>\n\n<p>use <strong>putenv(\"VAR=value\")</strong> to set the value of the environment variable.</p>\n\n<p>use <strong>char* var = getenv(\"VAR\")</strong> to retrieve the value.</p>\n"
},
{
"answer_id": 186124,
"author": "LeopardSkinPillBoxHat",
"author_id": 22489,
"author_profile": "https://Stackoverflow.com/users/22489",
"pm_score": 3,
"selected": true,
"text": "<p>Call this directly from the VxWorks shell:</p>\n\n<pre><code>putenv \"<VARIABLE NAME>=<VALUE>\"\n</code></pre>\n\n<p>replace with your environment variable name and with the value you want to set it to.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
] |
In a vxWorks Real-Time process, you can pass environment variables as one of the parameter of the **main** routine.
How do you use the environment variables in the kernel context?
|
Call this directly from the VxWorks shell:
```
putenv "<VARIABLE NAME>=<VALUE>"
```
replace with your environment variable name and with the value you want to set it to.
|
186,125 |
<p>I would like to use a secure SSL login on my website! I have not used SSL before, so I am looking for some good reading. Can anyone tell me where I can find some sample code of SSL snippets or page code. (Not too technical)</p>
<ul>
<li>I do have a static IP</li>
<li>My host is set-up to handle SSL Pages. </li>
</ul>
<p>Interested in: Basic page code. / Tree structure. / Other </p>
<p>Paul </p>
|
[
{
"answer_id": 186138,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 2,
"selected": false,
"text": "<p>My first thought would be to simply call a function to redirect to the https: version of the current page when you need to be secure.</p>\n\n<p>Some code like this:</p>\n\n<pre><code>if($requireSSL && $_SERVER['SERVER_PORT'] != 443) \n{\n header(\"HTTP/1.1 301 Moved Permanently\");\n header(\"Location: https://\".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);\n exit();\n}\n</code></pre>\n\n<p><a href=\"http://www.somacon.com/p536.php\" rel=\"nofollow noreferrer\">Reference</a></p>\n"
},
{
"answer_id": 186145,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 2,
"selected": false,
"text": "<p>If you've an SSL enabled host, writing a login is not different to writing one without SSL - all the encryption happens at a lower layer of the protocol stack, so by the time your PHP sees the request, it's already decrypted. Similarly, your script outputs are encrypted by the HTTP server before onward transmission back to the user.</p>\n"
},
{
"answer_id": 187032,
"author": "Scott Reynen",
"author_id": 10837,
"author_profile": "https://Stackoverflow.com/users/10837",
"pm_score": 0,
"selected": false,
"text": "<p>SSL happens before the request ever reaches PHP. The only impact on your PHP would be in the self-facing links you're publishing, which you'd want to switch from http://... to https://... There's a $_SERVER['HTTPS'] variable you could use to trigger this change if you'll be accepting both SSL and non-SSL connections. But if you're moving everything to SSL, you'll want to move all your links once rather than having it check on each request.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I would like to use a secure SSL login on my website! I have not used SSL before, so I am looking for some good reading. Can anyone tell me where I can find some sample code of SSL snippets or page code. (Not too technical)
* I do have a static IP
* My host is set-up to handle SSL Pages.
Interested in: Basic page code. / Tree structure. / Other
Paul
|
My first thought would be to simply call a function to redirect to the https: version of the current page when you need to be secure.
Some code like this:
```
if($requireSSL && $_SERVER['SERVER_PORT'] != 443)
{
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit();
}
```
[Reference](http://www.somacon.com/p536.php)
|
186,131 |
<p>He're an interesting problem that looks for the most Pythonic solution. Suppose I have a list of mappings <code>{'id': id, 'url': url}</code>. Some <code>id</code>s in the list are duplicate, and I want to create a new list, with all the duplicates removed. I came up with the following function:</p>
<pre><code>def unique_mapping(map):
d = {}
for res in map:
d[res['id']] = res['url']
return [{'id': id, 'url': d[id]} for id in d]
</code></pre>
<p>I suppose it's quite efficient. But is there a "more Pythonic" way ? Or perhaps a more efficient way ?</p>
|
[
{
"answer_id": 186295,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 3,
"selected": true,
"text": "<p>Your example can be rewritten slightly to construct the first dictionary using a generator expression and to remove necessity of construction of another mappings. Just reuse the old ones:</p>\n\n<pre><code>def unique_mapping(mappings):\n return dict((m['id'], m) for m in mappings).values()\n</code></pre>\n\n<p>Although this came out as a one-liner, I still think it's quite readable.</p>\n\n<p>There are two things you have to keep in mind when using your original solution and mine:</p>\n\n<ul>\n<li>the items will not always be returned in the same order they were originally</li>\n<li>the later entry will overwrite previous entries with the same id</li>\n</ul>\n\n<p>If you don't mind, then I suggest the solution above. In other case, this function preserves order and treats first-encountered ids with priority:</p>\n\n<pre><code>def unique_mapping(mappings):\n addedIds = set()\n for m in mappings:\n mId = m['id']\n if mId not in addedIds:\n addedIds.add(mId)\n yield m\n</code></pre>\n\n<p>You might need to call it with <code>list(unique_mappings(mappings))</code> if you need a list and not a generator.</p>\n"
},
{
"answer_id": 186317,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "<p>There are a couple of things you could improve.</p>\n\n<ul>\n<li><p>You're performing two loops, one over the original dict, and then again over the result dict. You could build up your results in one step instead.</p></li>\n<li><p>You could change to use a generator, to avoid constructing the whole list up-front. (Use list(unique_mapping(items)) to convert to a full list if you need it)</p></li>\n<li><p>There's no need to store the value when just checking for duplicates, you can use a set instead.</p></li>\n<li><p>You're recreating a dictionary for each element, rather than returning the original. This may actually be needed (eg. you're modifying them, and don't want to touch the original), but if not, its more efficient to use the dictionaries already created.</p></li>\n</ul>\n\n<p>Here's an implementation:</p>\n\n<pre><code>def unique_mapping(items):\n s = set()\n for res in items:\n if res['id'] not in s:\n yield res\n s.add(res['id'])\n</code></pre>\n"
},
{
"answer_id": 187041,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "<p>I think this can be made simpler still. Dictionaries don't tolerate duplicate keys. Make your list of mappings into a dictionary of mappings. This will remove duplicates.</p>\n\n<pre><code>>>> someListOfDicts= [\n {'url': 'http://a', 'id': 'a'}, \n {'url': 'http://b', 'id': 'b'}, \n {'url': 'http://c', 'id': 'a'}]\n\n>>> dict( [(x['id'],x) for x in someListOfDicts ] ).values()\n\n[{'url': 'http://c', 'id': 'a'}, {'url': 'http://b', 'id': 'b'}]\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8206/"
] |
He're an interesting problem that looks for the most Pythonic solution. Suppose I have a list of mappings `{'id': id, 'url': url}`. Some `id`s in the list are duplicate, and I want to create a new list, with all the duplicates removed. I came up with the following function:
```
def unique_mapping(map):
d = {}
for res in map:
d[res['id']] = res['url']
return [{'id': id, 'url': d[id]} for id in d]
```
I suppose it's quite efficient. But is there a "more Pythonic" way ? Or perhaps a more efficient way ?
|
Your example can be rewritten slightly to construct the first dictionary using a generator expression and to remove necessity of construction of another mappings. Just reuse the old ones:
```
def unique_mapping(mappings):
return dict((m['id'], m) for m in mappings).values()
```
Although this came out as a one-liner, I still think it's quite readable.
There are two things you have to keep in mind when using your original solution and mine:
* the items will not always be returned in the same order they were originally
* the later entry will overwrite previous entries with the same id
If you don't mind, then I suggest the solution above. In other case, this function preserves order and treats first-encountered ids with priority:
```
def unique_mapping(mappings):
addedIds = set()
for m in mappings:
mId = m['id']
if mId not in addedIds:
addedIds.add(mId)
yield m
```
You might need to call it with `list(unique_mappings(mappings))` if you need a list and not a generator.
|
186,160 |
<p>I have a table in the database that I'm retrieving using LINQ to SQL, and as a part of my processing I want to add to this list, then update the database with the new items + any changes I've made.</p>
<p>What I thought I could do was this:</p>
<pre><code>var list = (from item in db.Table
select item).ToList();
[do processing where I modify items & add to the list]
list = list.Distinct();
db.SubmitChanges();
</code></pre>
<p>What happens is that the modifications happed (ie. SQL updates) but any new items I add to the list don't get added.</p>
<p>Obviously I'm doing this wrong, what is the correct way to modify & add to a list of DB entities, then commit all the updates & inserts?</p>
|
[
{
"answer_id": 186188,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 1,
"selected": false,
"text": "<p>You have to add the new items via InsertOnSubmit.</p>\n"
},
{
"answer_id": 186221,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": true,
"text": "<p>The List is meaningless. It's just happens to hold objects that the DataContext knows about. We need to make sure that the DataContext knows about the new ones. The important thing is that they don't have to be complete when we alert the DataContext to them:</p>\n\n<pre><code>Item item;\nif (needNewOne)\n{\n item = new Item();\n db.InsertOnSubmit(item);\n}\nelse\n{\n item = list[i];\n}\n/// build new or modify existing item\n/// :\ndb.SubmitChanges();\n</code></pre>\n"
},
{
"answer_id": 186223,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 1,
"selected": false,
"text": "<p>You've got to tell LINQ to insert the new row on submit, using InsertOnSubmit:</p>\n\n<pre><code>db.InsertOnSubmit(newrow);\ndb.SubmitChanges();\n</code></pre>\n\n<p>You do not need a new DataContext, you can use the one you are using for updates.</p>\n\n<p>Same for delete DeleteOnSubmit(row). Modifications will be tracked, though.</p>\n"
},
{
"answer_id": 186283,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p>You can create an extension method for it:</p>\n\n<pre><code>static void EnsureInsertedOnSubmit<TEntity>( this Table<TEntity> table\n ,IEnumerable<TEntity> entities)\n { foreach(var entity in entities) \n { if ( table.GetModifiedMembers(entity).Length == 0 \n && table.GetOriginalEntityState(entity) == default(TEntity))\n { table.InsertOnSubmit(entity);\n }\n }\n }\n</code></pre>\n\n<p>And then you can do this:</p>\n\n<pre><code> var list = db.Table1.ToList();\n list.Add(new Item());\n db.Table1.EnsureInsertedOnSubmit(list);\n db.SubmitChanges();\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
] |
I have a table in the database that I'm retrieving using LINQ to SQL, and as a part of my processing I want to add to this list, then update the database with the new items + any changes I've made.
What I thought I could do was this:
```
var list = (from item in db.Table
select item).ToList();
[do processing where I modify items & add to the list]
list = list.Distinct();
db.SubmitChanges();
```
What happens is that the modifications happed (ie. SQL updates) but any new items I add to the list don't get added.
Obviously I'm doing this wrong, what is the correct way to modify & add to a list of DB entities, then commit all the updates & inserts?
|
The List is meaningless. It's just happens to hold objects that the DataContext knows about. We need to make sure that the DataContext knows about the new ones. The important thing is that they don't have to be complete when we alert the DataContext to them:
```
Item item;
if (needNewOne)
{
item = new Item();
db.InsertOnSubmit(item);
}
else
{
item = list[i];
}
/// build new or modify existing item
/// :
db.SubmitChanges();
```
|
186,202 |
<p>What is the most elegant way to solve this:</p>
<ul>
<li>open a file for reading, but only if it is not already opened for writing</li>
<li>open a file for writing, but only if it is not already opened for reading or writing</li>
</ul>
<p>The built-in functions work like this</p>
<pre><code>>>> path = r"c:\scr.txt"
>>> file1 = open(path, "w")
>>> print file1
<open file 'c:\scr.txt', mode 'w' at 0x019F88D8>
>>> file2 = open(path, "w")
>>> print file2
<open file 'c:\scr.txt', mode 'w' at 0x02332188>
>>> file1.write("111")
>>> file2.write("222")
>>> file1.close()
</code></pre>
<p>scr.txt now contains '111'.</p>
<pre><code>>>> file2.close()
</code></pre>
<p>scr.txt was overwritten and now contains '222' (on Windows, Python 2.4).</p>
<p>The solution should work inside the same process (like in the example above) as well as when another process has opened the file.<br>
It is preferred, if a crashing program will not keep the lock open.</p>
|
[
{
"answer_id": 186300,
"author": "kender",
"author_id": 4172,
"author_profile": "https://Stackoverflow.com/users/4172",
"pm_score": 0,
"selected": false,
"text": "<p>To make you safe when opening files within one application, you could try something like this:</p>\n\n<pre><code>import time\nclass ExclusiveFile(file):\n openFiles = {}\n fileLocks = []\n\n class FileNotExclusiveException(Exception):\n pass\n\n def __init__(self, *args):\n\n sMode = 'r'\n sFileName = args[0]\n try:\n sMode = args[1]\n except:\n pass\n while sFileName in ExclusiveFile.fileLocks:\n time.sleep(1)\n\n ExclusiveFile.fileLocks.append(sFileName)\n\n if not sFileName in ExclusiveFile.openFiles.keys() or (ExclusiveFile.openFiles[sFileName] == 'r' and sMode == 'r'):\n ExclusiveFile.openFiles[sFileName] = sMode\n try:\n file.__init__(self, sFileName, sMode)\n finally:\n ExclusiveFile.fileLocks.remove(sFileName)\n else:\n ExclusiveFile.fileLocks.remove(sFileName)\n raise self.FileNotExclusiveException(sFileName)\n\n def close(self):\n del ExclusiveFile.openFiles[self.name]\n file.close(self)\n</code></pre>\n\n<p>That way you subclass the <code>file</code> class. Now just do:</p>\n\n<pre><code>>>> f = ExclusiveFile('/tmp/a.txt', 'r')\n>>> f\n<open file '/tmp/a.txt', mode 'r' at 0xb7d7cc8c>\n>>> f1 = ExclusiveFile('/tmp/a.txt', 'r')\n>>> f1\n<open file '/tmp/a.txt', mode 'r' at 0xb7d7c814>\n>>> f2 = ExclusiveFile('/tmp/a.txt', 'w') # can't open it for writing now\nexclfile.FileNotExclusiveException: /tmp/a.txt\n</code></pre>\n\n<p>If you open it first with 'w' mode, it won't allow anymore opens, even in read mode, just as you wanted...</p>\n"
},
{
"answer_id": 186464,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 6,
"selected": true,
"text": "<p>I don't think there is a fully crossplatform way. On unix, the fcntl module will do this for you. However on windows (which I assume you are by the paths), you'll need to use the win32file module.</p>\n\n<p>Fortunately, there is a portable implementation (<a href=\"https://github.com/WoLpH/portalocker\" rel=\"noreferrer\">portalocker</a>) using the platform appropriate method at the python cookbook.</p>\n\n<p>To use it, open the file, and then call:</p>\n\n<pre><code>portalocker.lock(file, flags)\n</code></pre>\n\n<p>where flags are portalocker.LOCK_EX for exclusive write access, or LOCK_SH for shared, read access.</p>\n"
},
{
"answer_id": 188827,
"author": "gz.",
"author_id": 3665,
"author_profile": "https://Stackoverflow.com/users/3665",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a start on the win32 half of a portable implementation, that does not need a seperate locking mechanism.</p>\n\n<p>Requires the <a href=\"http://python.net/crew/mhammond/win32/\" rel=\"nofollow noreferrer\">Python for Windows Extensions</a> to get down to the win32 api, but that's pretty much mandatory for python on windows already, and can alternatively be done with <a href=\"http://www.python.org/doc/lib/module-ctypes.html\" rel=\"nofollow noreferrer\">ctypes</a>. The code could be adapted to expose more functionality if it's needed (such as allowing <code>FILE_SHARE_READ</code> rather than no sharing at all). See also the MSDN documentation for the <a href=\"http://msdn.microsoft.com/en-us/library/aa363858.aspx\" rel=\"nofollow noreferrer\"><code>CreateFile</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/aa365747.aspx\" rel=\"nofollow noreferrer\"><code>WriteFile</code></a> system calls, and the <a href=\"http://msdn.microsoft.com/en-us/library/aa363874.aspx\" rel=\"nofollow noreferrer\">article on Creating and Opening Files</a>.</p>\n\n<p>As has been mentioned, you can use the standard <a href=\"http://www.python.org/doc/lib/module-fcntl.html\" rel=\"nofollow noreferrer\">fcntl</a> module to implement the unix half of this, if required.</p>\n\n<pre><code>import winerror, pywintypes, win32file\n\nclass LockError(StandardError):\n pass\n\nclass WriteLockedFile(object):\n \"\"\"\n Using win32 api to achieve something similar to file(path, 'wb')\n Could be adapted to handle other modes as well.\n \"\"\"\n def __init__(self, path):\n try:\n self._handle = win32file.CreateFile(\n path,\n win32file.GENERIC_WRITE,\n 0,\n None,\n win32file.OPEN_ALWAYS,\n win32file.FILE_ATTRIBUTE_NORMAL,\n None)\n except pywintypes.error, e:\n if e[0] == winerror.ERROR_SHARING_VIOLATION:\n raise LockError(e[2])\n raise\n def close(self):\n self._handle.close()\n def write(self, str):\n win32file.WriteFile(self._handle, str)\n</code></pre>\n\n<p>Here's how your example from above behaves:</p>\n\n<pre><code>>>> path = \"C:\\\\scr.txt\"\n>>> file1 = WriteLockedFile(path)\n>>> file2 = WriteLockedFile(path) #doctest: +IGNORE_EXCEPTION_DETAIL\nTraceback (most recent call last):\n ...\nLockError: ...\n>>> file1.write(\"111\")\n>>> file1.close()\n>>> print file(path).read()\n111\n</code></pre>\n"
},
{
"answer_id": 195021,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>The solution should work inside the same process (like in the example above) as well as when another process has opened the file.</p>\n</blockquote>\n\n<p>If by 'another process' you mean 'whatever process' (i.e. not your program), in Linux there's no way to accomplish this relying only on system calls (<em>fcntl</em> & friends). What you want is <a href=\"http://en.wikipedia.org/wiki/File_locking\" rel=\"noreferrer\">mandatory locking</a>, and the Linux way to obtain it is a bit more involved:</p>\n\n<p>Remount the partition that contains your file with the <em>mand</em> option:</p>\n\n<pre><code># mount -o remount,mand /dev/hdXY</code></pre>\n\n<p>Set the <em>sgid</em> flag for your file:</p>\n\n<pre><code># chmod g-x,g+s yourfile</code></pre>\n\n<p>In your Python code, obtain an exclusive lock on that file:</p>\n\n<pre><code>fcntl.flock(fd, fcntl.LOCK_EX)</code></pre>\n\n<p>Now even <em>cat</em> will not be able to read the file until you release the lock. </p>\n"
},
{
"answer_id": 21444311,
"author": "parity3",
"author_id": 1454536,
"author_profile": "https://Stackoverflow.com/users/1454536",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming your Python interpreter, and the underlying os and filesystem treat os.rename as an atomic operation and it will error when the destination exists, the following method is free of race conditions. I'm using this in production on a linux machine. Requires no third party libs and is not os dependent, and aside from an extra file create, the performance hit is acceptable for many use cases. You can easily apply python's function decorator pattern or a 'with_statement' contextmanager here to abstract out the mess.</p>\n\n<p>You'll need to make sure that lock_filename does not exist before a new process/task begins.</p>\n\n<pre><code>import os,time\ndef get_tmp_file():\n filename='tmp_%s_%s'%(os.getpid(),time.time())\n open(filename).close()\n return filename\n\ndef do_exclusive_work():\n print 'exclusive work being done...'\n\nnum_tries=10\nwait_time=10\nlock_filename='filename.lock'\nacquired=False\nfor try_num in xrange(num_tries):\n tmp_filename=get_tmp_file()\n if not os.path.exists(lock_filename):\n try:\n os.rename(tmp_filename,lock_filename)\n acquired=True\n except (OSError,ValueError,IOError), e:\n pass\n if acquired:\n try:\n do_exclusive_work()\n finally:\n os.remove(lock_filename)\n break\n os.remove(tmp_filename)\n time.sleep(wait_time)\nassert acquired, 'maximum tries reached, failed to acquire lock file'\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>It has come to light that os.rename silently overwrites the destination on a non-windows OS. Thanks for pointing this out @ akrueger!</p>\n\n<p>Here is a workaround, gathered from <a href=\"https://stackoverflow.com/questions/1348026/how-do-i-create-a-file-in-python-without-overwriting-an-existing-file\">here</a>:</p>\n\n<p>Instead of using os.rename you can use:</p>\n\n<pre><code>try:\n if os.name != 'nt': # non-windows needs a create-exclusive operation\n fd = os.open(lock_filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)\n os.close(fd)\n # non-windows os.rename will overwrite lock_filename silently.\n # We leave this call in here just so the tmp file is deleted but it could be refactored so the tmp file is never even generated for a non-windows OS\n os.rename(tmp_filename,lock_filename)\n acquired=True\nexcept (OSError,ValueError,IOError), e:\n if os.name != 'nt' and not 'File exists' in str(e): raise\n</code></pre>\n\n<p>@ akrueger You're probably just fine with your directory based solution, just giving you an alternate method.</p>\n"
},
{
"answer_id": 28532580,
"author": "akrueger",
"author_id": 3693375,
"author_profile": "https://Stackoverflow.com/users/3693375",
"pm_score": 3,
"selected": false,
"text": "<p>EDIT: <strong>I solved it myself!</strong> By using <strong><em>directory existence</em></strong> & age as a locking mechanism! Locking by file is safe only on Windows (because Linux silently overwrites), but locking by directory works perfectly both on Linux and Windows. See my GIT where I created an easy to use class <strong>'lockbydir.DLock'</strong> for that:</p>\n\n<p><a href=\"https://github.com/drandreaskrueger/lockbydir\" rel=\"noreferrer\">https://github.com/drandreaskrueger/lockbydir</a></p>\n\n<p>At the bottom of the readme, you find 3 GITplayers where you can see the code examples execute live in your browser! Quite cool, isn't it? :-)</p>\n\n<p>Thanks for your attention</p>\n\n<hr>\n\n<h2>This was my original question:</h2>\n\n<p>I would like to answer to parity3 (<a href=\"https://meta.stackoverflow.com/users/1454536/parity3\">https://meta.stackoverflow.com/users/1454536/parity3</a>) but I can neither comment directly ('You must have 50 reputation to comment'), nor do I see any way to contact him/her directly. What do you suggest to me, to get through to him?</p>\n\n<p>My question:</p>\n\n<p>I have implemented something similiar to what parity3 suggested here as an answer: <a href=\"https://stackoverflow.com/a/21444311/3693375\">https://stackoverflow.com/a/21444311/3693375</a> (\"Assuming your Python interpreter, and the ...\")</p>\n\n<p>And it works brilliantly - on Windows. (I am using it to implement a locking mechanism that works across independently started processes. <a href=\"https://github.com/drandreaskrueger/lockbyfile\" rel=\"noreferrer\">https://github.com/drandreaskrueger/lockbyfile</a> )</p>\n\n<p>But other than parity3 says, it does NOT work the same on Linux:</p>\n\n<blockquote>\n <p>os.rename(src, dst)</p>\n \n <p>Rename the file or directory src to dst. ... On Unix, if dst exists \n and is a file, \n it will be replaced silently if the user has permission. \n The operation may fail on some Unix flavors if src and dst \n are on different filesystems. If successful, the renaming will \n be an atomic operation (this is a POSIX requirement). \n On Windows, if dst already exists, OSError will be raised\n (<a href=\"https://docs.python.org/2/library/os.html#os.rename\" rel=\"noreferrer\">https://docs.python.org/2/library/os.html#os.rename</a>)</p>\n</blockquote>\n\n<p>The silent replacing is the problem. On Linux.\nThe \"if dst already exists, OSError will be raised\" is great for my purposes. But only on Windows, sadly.</p>\n\n<p>I guess parity3's example still works most of the time, because of his if condition</p>\n\n<pre><code>if not os.path.exists(lock_filename):\n try:\n os.rename(tmp_filename,lock_filename)\n</code></pre>\n\n<p>But then the whole thing is not atomic anymore. </p>\n\n<p>Because the if condition might be true in two parallel processes, and then both will rename, but only one will win the renaming race. And no exception raised (in Linux).</p>\n\n<p>Any suggestions? Thanks! </p>\n\n<p>P.S.: I know this is not the proper way, but I am lacking an alternative. PLEASE don't punish me with lowering my reputation. I looked around a lot, to solve this myself. How to PM users in here? And <em>meh</em> why can't I?</p>\n"
},
{
"answer_id": 59795288,
"author": "Josh Correia",
"author_id": 7487335,
"author_profile": "https://Stackoverflow.com/users/7487335",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer to use <a href=\"https://pypi.org/project/filelock/\" rel=\"nofollow noreferrer\">filelock</a>, a cross-platform Python library which barely requires any additional code. Here's an example of how to use it:</p>\n\n<pre><code>from filelock import FileLock\n\nlockfile = r\"c:\\scr.txt\"\nlock = FileLock(lockfile + \".lock\")\nwith lock:\n file = open(path, \"w\")\n file.write(\"111\")\n file.close()\n</code></pre>\n\n<p>Any code within the <code>with lock:</code> block is thread-safe, meaning that it will be finished before another process has access to the file.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19166/"
] |
What is the most elegant way to solve this:
* open a file for reading, but only if it is not already opened for writing
* open a file for writing, but only if it is not already opened for reading or writing
The built-in functions work like this
```
>>> path = r"c:\scr.txt"
>>> file1 = open(path, "w")
>>> print file1
<open file 'c:\scr.txt', mode 'w' at 0x019F88D8>
>>> file2 = open(path, "w")
>>> print file2
<open file 'c:\scr.txt', mode 'w' at 0x02332188>
>>> file1.write("111")
>>> file2.write("222")
>>> file1.close()
```
scr.txt now contains '111'.
```
>>> file2.close()
```
scr.txt was overwritten and now contains '222' (on Windows, Python 2.4).
The solution should work inside the same process (like in the example above) as well as when another process has opened the file.
It is preferred, if a crashing program will not keep the lock open.
|
I don't think there is a fully crossplatform way. On unix, the fcntl module will do this for you. However on windows (which I assume you are by the paths), you'll need to use the win32file module.
Fortunately, there is a portable implementation ([portalocker](https://github.com/WoLpH/portalocker)) using the platform appropriate method at the python cookbook.
To use it, open the file, and then call:
```
portalocker.lock(file, flags)
```
where flags are portalocker.LOCK\_EX for exclusive write access, or LOCK\_SH for shared, read access.
|
186,208 |
<p>What Latex styles do you use and where do you find them?</p>
<p>The reason I'm asking this is that it seems that some 99.9999% of all styles on the internet are copies of each other and of a <a href="http://www.tug.org/texshowcase/ps_s_1b.pdf" rel="noreferrer">physics exam paper</a></p>
<p>However, when you try to find a style for a paper like <a href="http://www.tug.org/texshowcase/en_gb_eclipse_114.pdf" rel="noreferrer">this one</a>... Good luck, you are never going to find it.</p>
<p>Creating your own style is often not really an option, because it requires you to dig quite deep into the very advanced features of TeX/LaTeX and fighting your way against possible incompatibilities with document classes/packages/whatnot.</p>
|
[
{
"answer_id": 186306,
"author": "Michael Pliskin",
"author_id": 9777,
"author_profile": "https://Stackoverflow.com/users/9777",
"pm_score": 2,
"selected": false,
"text": "<p>Well I think <a href=\"http://ctan.org/\" rel=\"nofollow noreferrer\">CTAN</a> is the best resource for LaTeX and TeX-related stuff. Also lots of scientific organizations provide their own styles, it makes sense to try tracing who was the author/publisher of the paper you like and check their websites.</p>\n"
},
{
"answer_id": 186452,
"author": "Will Robertson",
"author_id": 4161,
"author_profile": "https://Stackoverflow.com/users/4161",
"pm_score": 4,
"selected": true,
"text": "<p>LaTeX was originally designed as a reasonably flexible system on which a few standard classes were distributed — that were themselves rather <em>in</em>flexible.</p>\n\n<p>In the current state of affairs, if you want a custom layout, you need to write a few amount of supporting code yourself. How else would it happen? It's not like HTML+CSS gives you templates to work with; you need to implement the design yourself.</p>\n\n<blockquote>\n <p>Creating your own style is often not really an option</p>\n</blockquote>\n\n<p>Ah, well, not unless you know how to program in LaTeX!</p>\n\n<p>Seriously, it all depends on knowing where to start and what to build on top of. That catalogue you give as an example would, in my opinion, be reasonably easy to do in LaTeX; it's just a bunch of boxes.</p>\n\n<p>You could write something like</p>\n\n<pre><code>\\newcommand\\catalogueEntry[4]{%\n \\parbox[t]{0.23\\linewidth}{\\textbf{#1}}%\n \\hfill\n \\parbox[t]{0.23\\linewidth}{\\includegraphics{#2}}%\n \\hfill\n \\parbox[t]{0.23\\linewidth}{\\textbf{Characteristics}\\\\ #3}%\n \\hfill\n \\parbox[t]{0.23\\linewidth}{\\textbf{Application}\\\\ #4}\n}\n</code></pre>\n\n<p>and use it as so</p>\n\n<pre><code>\\catalogueEntry{Spotlights}{spotlight.jpg}\n {Eclipse spotlights are...}\n {Narrow to medium...}\n</code></pre>\n\n<p>This is just a basic illustration of what could be knocked up quickly — much more sophistication could be used to turn this into a more flexible system.</p>\n\n<p>I see LaTeX as an extensible markup system. If you separate your markup from its presentation on the page, it's not too hard to get your information represented in whichever form you wish. But getting started is a little tricky, I have to admit; the learning curve for LaTeX programming can be rather steep.</p>\n"
},
{
"answer_id": 256624,
"author": "Jouni K. Seppänen",
"author_id": 26575,
"author_profile": "https://Stackoverflow.com/users/26575",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.ctan.org/tex-archive/macros/latex/contrib/memoir/\" rel=\"nofollow noreferrer\">Memoir</a> is a more flexible document class than the default ones, and its <a href=\"http://www.ctan.org/tex-archive/macros/latex/contrib/memoir/memman.pdf\" rel=\"nofollow noreferrer\">manual</a> is excellent. </p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445049/"
] |
What Latex styles do you use and where do you find them?
The reason I'm asking this is that it seems that some 99.9999% of all styles on the internet are copies of each other and of a [physics exam paper](http://www.tug.org/texshowcase/ps_s_1b.pdf)
However, when you try to find a style for a paper like [this one](http://www.tug.org/texshowcase/en_gb_eclipse_114.pdf)... Good luck, you are never going to find it.
Creating your own style is often not really an option, because it requires you to dig quite deep into the very advanced features of TeX/LaTeX and fighting your way against possible incompatibilities with document classes/packages/whatnot.
|
LaTeX was originally designed as a reasonably flexible system on which a few standard classes were distributed — that were themselves rather *in*flexible.
In the current state of affairs, if you want a custom layout, you need to write a few amount of supporting code yourself. How else would it happen? It's not like HTML+CSS gives you templates to work with; you need to implement the design yourself.
>
> Creating your own style is often not really an option
>
>
>
Ah, well, not unless you know how to program in LaTeX!
Seriously, it all depends on knowing where to start and what to build on top of. That catalogue you give as an example would, in my opinion, be reasonably easy to do in LaTeX; it's just a bunch of boxes.
You could write something like
```
\newcommand\catalogueEntry[4]{%
\parbox[t]{0.23\linewidth}{\textbf{#1}}%
\hfill
\parbox[t]{0.23\linewidth}{\includegraphics{#2}}%
\hfill
\parbox[t]{0.23\linewidth}{\textbf{Characteristics}\\ #3}%
\hfill
\parbox[t]{0.23\linewidth}{\textbf{Application}\\ #4}
}
```
and use it as so
```
\catalogueEntry{Spotlights}{spotlight.jpg}
{Eclipse spotlights are...}
{Narrow to medium...}
```
This is just a basic illustration of what could be knocked up quickly — much more sophistication could be used to turn this into a more flexible system.
I see LaTeX as an extensible markup system. If you separate your markup from its presentation on the page, it's not too hard to get your information represented in whichever form you wish. But getting started is a little tricky, I have to admit; the learning curve for LaTeX programming can be rather steep.
|
186,211 |
<p>I am using Windows 2003. I have mapped a web application into a virtual directory. This is built on framework 1.1 When i try to browse to the default page i get a error as </p>
<p>Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. </p>
<p>Parser Error Message: Access is denied: 'Interop.MSDASC'.</p>
<p>Source Error: </p>
<p>Line 196:
Line 197:
Line 198:
Line 199:
Line 200: </p>
<p>Source File: c:\windows\microsoft.net\framework\v1.1.4322\Config\machine.config Line: 198 </p>
<p>Assembly Load Trace: The following information can be helpful to determine why the assembly 'Interop.MSDASC' could not be loaded.</p>
|
[
{
"answer_id": 186306,
"author": "Michael Pliskin",
"author_id": 9777,
"author_profile": "https://Stackoverflow.com/users/9777",
"pm_score": 2,
"selected": false,
"text": "<p>Well I think <a href=\"http://ctan.org/\" rel=\"nofollow noreferrer\">CTAN</a> is the best resource for LaTeX and TeX-related stuff. Also lots of scientific organizations provide their own styles, it makes sense to try tracing who was the author/publisher of the paper you like and check their websites.</p>\n"
},
{
"answer_id": 186452,
"author": "Will Robertson",
"author_id": 4161,
"author_profile": "https://Stackoverflow.com/users/4161",
"pm_score": 4,
"selected": true,
"text": "<p>LaTeX was originally designed as a reasonably flexible system on which a few standard classes were distributed — that were themselves rather <em>in</em>flexible.</p>\n\n<p>In the current state of affairs, if you want a custom layout, you need to write a few amount of supporting code yourself. How else would it happen? It's not like HTML+CSS gives you templates to work with; you need to implement the design yourself.</p>\n\n<blockquote>\n <p>Creating your own style is often not really an option</p>\n</blockquote>\n\n<p>Ah, well, not unless you know how to program in LaTeX!</p>\n\n<p>Seriously, it all depends on knowing where to start and what to build on top of. That catalogue you give as an example would, in my opinion, be reasonably easy to do in LaTeX; it's just a bunch of boxes.</p>\n\n<p>You could write something like</p>\n\n<pre><code>\\newcommand\\catalogueEntry[4]{%\n \\parbox[t]{0.23\\linewidth}{\\textbf{#1}}%\n \\hfill\n \\parbox[t]{0.23\\linewidth}{\\includegraphics{#2}}%\n \\hfill\n \\parbox[t]{0.23\\linewidth}{\\textbf{Characteristics}\\\\ #3}%\n \\hfill\n \\parbox[t]{0.23\\linewidth}{\\textbf{Application}\\\\ #4}\n}\n</code></pre>\n\n<p>and use it as so</p>\n\n<pre><code>\\catalogueEntry{Spotlights}{spotlight.jpg}\n {Eclipse spotlights are...}\n {Narrow to medium...}\n</code></pre>\n\n<p>This is just a basic illustration of what could be knocked up quickly — much more sophistication could be used to turn this into a more flexible system.</p>\n\n<p>I see LaTeX as an extensible markup system. If you separate your markup from its presentation on the page, it's not too hard to get your information represented in whichever form you wish. But getting started is a little tricky, I have to admit; the learning curve for LaTeX programming can be rather steep.</p>\n"
},
{
"answer_id": 256624,
"author": "Jouni K. Seppänen",
"author_id": 26575,
"author_profile": "https://Stackoverflow.com/users/26575",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.ctan.org/tex-archive/macros/latex/contrib/memoir/\" rel=\"nofollow noreferrer\">Memoir</a> is a more flexible document class than the default ones, and its <a href=\"http://www.ctan.org/tex-archive/macros/latex/contrib/memoir/memman.pdf\" rel=\"nofollow noreferrer\">manual</a> is excellent. </p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20951/"
] |
I am using Windows 2003. I have mapped a web application into a virtual directory. This is built on framework 1.1 When i try to browse to the default page i get a error as
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: Access is denied: 'Interop.MSDASC'.
Source Error:
Line 196:
Line 197:
Line 198:
Line 199:
Line 200:
Source File: c:\windows\microsoft.net\framework\v1.1.4322\Config\machine.config Line: 198
Assembly Load Trace: The following information can be helpful to determine why the assembly 'Interop.MSDASC' could not be loaded.
|
LaTeX was originally designed as a reasonably flexible system on which a few standard classes were distributed — that were themselves rather *in*flexible.
In the current state of affairs, if you want a custom layout, you need to write a few amount of supporting code yourself. How else would it happen? It's not like HTML+CSS gives you templates to work with; you need to implement the design yourself.
>
> Creating your own style is often not really an option
>
>
>
Ah, well, not unless you know how to program in LaTeX!
Seriously, it all depends on knowing where to start and what to build on top of. That catalogue you give as an example would, in my opinion, be reasonably easy to do in LaTeX; it's just a bunch of boxes.
You could write something like
```
\newcommand\catalogueEntry[4]{%
\parbox[t]{0.23\linewidth}{\textbf{#1}}%
\hfill
\parbox[t]{0.23\linewidth}{\includegraphics{#2}}%
\hfill
\parbox[t]{0.23\linewidth}{\textbf{Characteristics}\\ #3}%
\hfill
\parbox[t]{0.23\linewidth}{\textbf{Application}\\ #4}
}
```
and use it as so
```
\catalogueEntry{Spotlights}{spotlight.jpg}
{Eclipse spotlights are...}
{Narrow to medium...}
```
This is just a basic illustration of what could be knocked up quickly — much more sophistication could be used to turn this into a more flexible system.
I see LaTeX as an extensible markup system. If you separate your markup from its presentation on the page, it's not too hard to get your information represented in whichever form you wish. But getting started is a little tricky, I have to admit; the learning curve for LaTeX programming can be rather steep.
|
186,232 |
<p>I want to use implicit linking in my project , and nmake really wants a .def file . The problem is , that this is a class , and I don't know what to write in the exports section .
Could anyone point me in the right direction ?</p>
<p>The error message is the following :</p>
<p><strong>NMAKE : U1073: don't know how to make 'DLLCLASS.def'</strong></p>
<p>P.S: I'm trying to build using Windows CE Platform Builder .</p>
|
[
{
"answer_id": 186240,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>If I recall correctly, you can use <code>__declspec(dllexport)</code> on the <em>class</em>, and VC++ will automatically create exports for all the symbols related to the class (constructors/destructor, methods, vtable, typeinfo, etc).</p>\n\n<p>Microsoft has more information on this <a href=\"http://msdn.microsoft.com/en-us/library/81h27t8c(VS.80).aspx\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 186428,
"author": "Vhaerun",
"author_id": 11234,
"author_profile": "https://Stackoverflow.com/users/11234",
"pm_score": 0,
"selected": false,
"text": "<p>The solution is the following :</p>\n\n<ul>\n<li><p>since a class is exported,you also need to add the exported methods in the .def file</p></li>\n<li><p>I didn't find out how to export a constructor , so I went with using a factory method ( static ) , which will return new instances of an object</p></li>\n<li><p>the other functions will be exported by adding normal exporting declaration in the .def file</p></li>\n</ul>\n\n<p>Hope someone will benefit from this information .</p>\n"
},
{
"answer_id": 186834,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 3,
"selected": true,
"text": "<p>You can always find the decorated name for the member function by using <a href=\"http://msdn.microsoft.com/en-us/library/c1h23y6c(VS.80).aspx\" rel=\"nofollow noreferrer\">dumpbin</a> /symbols myclass.obj</p>\n\n<p>in my case</p>\n\n<pre><code>class A {\n public:\n A( int ){}\n};\n</code></pre>\n\n<p>the <code>dumpbin</code> dump showed the symbol <code>??0A@@QAE@H@Z (public: __thiscall A::A(int))</code></p>\n\n<p>Putting this symbol in the .def file causes the linker to create the A::A(int) symbol in the export symbols.</p>\n\n<p><strong>BUT!</strong> as @paercebal states in his comment: the manual entry of decorated (mangled) names is a chore - error prone, and sadly enough, not guarenteed to be portable across compiler versions.</p>\n"
},
{
"answer_id": 2498419,
"author": "Allbite",
"author_id": 290091,
"author_profile": "https://Stackoverflow.com/users/290091",
"pm_score": 2,
"selected": false,
"text": "<p>I've found the best route to be an abstract factory.</p>\n\n<p>Start by defining a purely virtual base class. This is a class with no implementation, a purely virtual interface class. </p>\n\n<p>You can export this virtual base \"abstract interface\" class, but there's no real reason to do so. When the caller uses it, they will be using it through a pointer (PImpl, or Pointer to Implementation) so all the caller knows about is a simple memory address. A Def file, while a teensy bit more work to keep up with, provides benefits beyond what __declspec(dllexport) can attain. What benefits, you ask? We'll get to that, you just wait. </p>\n\n<p>Have your real class publicly inherit from the virtual base. Now create a factory method to construct your object and a \"<em>release</em>\"ish callable destructor to perform cleanup. Name these methods something like \"<em>ConstructMyClass</em>\" and \"<em>ReleaseMyClass</em>\". Please, please replace \"<em>MyClass</em>\" :-)</p>\n\n<p>Those factory / release methods should take only POD types if they need any paramaters (plain-old-data: integer, char, etc.). The return type should be your virtual abstract interface base class -- or rather, a pointer to it.</p>\n\n<p>IMyClass* CreateAnObjectOfTypeIMyClass();</p>\n\n<p>Perhaps it's now obvious why we need the virtual base class? Since the virtual interface class has no implementation, it's essentially all POD types (sort-of) so the \"datatype\" of the class can be understood by most callers like Visual Basic, C or vastly different C++ compilers.</p>\n\n<p>If you're sufficiently fancy, you can get around the need for a \"<em>manual release</em>\" method (sorry, had to do it). How? Manage your own resources in the class through smart-pointers and a pImpl type of architecture so when the object dies, it will clean up after itself. Doing so means your class is, in the immortal words of our saint and saviour <a href=\"http://programmer.97things.oreilly.com/wiki/index.php/Make_Interfaces_Easy_to_Use_Correctly_and_Hard_to_Use_Incorrectly\" rel=\"nofollow noreferrer\">Scott Meyers, \"<em>easy to use correctly and hard to use incorrectly</em>\"</a> by letting the caller disregard the need to clean up. Let those among us who have never forgotten to call \"<em>.close</em>\" cast the first stone.</p>\n\n<p>Maybe this architecture sounds familiar? It should, it's basically a micromachine version of COM. Well, sort-of, at least the concept for interface, factory construction and release.</p>\n\n<p>In the end you've exported the interface for your class, made (and exported) <em>Create</em> and <em>Destroy</em> methods, and now callers can invoke your <em>PleaseConstructMyClass</em> factory function to have your DLL return a fully constructed, fully implemented and fully baked object under the guise of its interface. They can call down to all the public methods of your class (at least the ones in your abstract virtual interface) and do all the fun stuff.</p>\n\n<p>When they are finished with the object which was returned by the factory function, then they can call a \"<em>ReleaseMyClass</em>\" function to ask your DLL to clean up the object's resources, or you can help them along by making your class clean up itself, making the \"<em>ReleaseMyClass</em>\" method redundant and useless.</p>\n\n<p>If anyone's interested in the specific gains & tradeoffs for using the Def file and the interface (besides my blind say-so), please pipe up and we can dig deeper.</p>\n\n<p>Don't you just love this stuff? </p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11234/"
] |
I want to use implicit linking in my project , and nmake really wants a .def file . The problem is , that this is a class , and I don't know what to write in the exports section .
Could anyone point me in the right direction ?
The error message is the following :
**NMAKE : U1073: don't know how to make 'DLLCLASS.def'**
P.S: I'm trying to build using Windows CE Platform Builder .
|
You can always find the decorated name for the member function by using [dumpbin](http://msdn.microsoft.com/en-us/library/c1h23y6c(VS.80).aspx) /symbols myclass.obj
in my case
```
class A {
public:
A( int ){}
};
```
the `dumpbin` dump showed the symbol `??0A@@QAE@H@Z (public: __thiscall A::A(int))`
Putting this symbol in the .def file causes the linker to create the A::A(int) symbol in the export symbols.
**BUT!** as @paercebal states in his comment: the manual entry of decorated (mangled) names is a chore - error prone, and sadly enough, not guarenteed to be portable across compiler versions.
|
186,307 |
<p>A project I'm working on will pull XML from a web-server and build a data store from it. The data will have certain core fields but needs to be extendable... for example I have a and later might want to have which adds extra fields.</p>
<p>In the Flex app, I don't want the central data store to be working on XML objects or simply putting the properties into Objects. I want to have strong types, e.g a Person class, which are created/populated from the XML.</p>
<p>How can this be done in a flexible way? Is Flex able to automatically build a Person from an XML if the attribute names match, or do I need to write conversion functionality for , , etc?</p>
|
[
{
"answer_id": 186991,
"author": "Raleigh Buckner",
"author_id": 1153,
"author_profile": "https://Stackoverflow.com/users/1153",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think this can be done automatically. I generally create the a class to mirror the XML structure I have and then create a static class method to create an instance of the object given an XML node. For example:</p>\n\n<pre><code>package {\n\n public class Foo{\n\n public function Foo(barparam1:String, barparam2:uint, barparam3:String, barparam4:Number){\n this._bar1 = barparam1;\n this._bar2 = barparam2;\n this._bar3 = barparam3;\n this._bar4 = barparam4;\n }\n\n protected var _bar1:String;\n protected var _bar2:uint;\n protected var _bar3:String;\n protected var _bar4:Number;\n\n public function get bar1():String{ return this._bar1; }\n public function get bar2():uint { return this._bar2; }\n public function get bar3():String { return this._bar3; }\n public function get bar4():Number { return this._bar4; }\n\n public function toString():String{\n return \"[Foo bar1:\\\"\" + this.bar1 + \"\\\", bar3:\\\"\" + this.bar3 + \"\\\", bar2:\" + this.bar2 + \", bar4:\" + this.bar4 + \"]\";\n }\n\n public static function createFromXml(xmlParam:XML):Foo{\n\n /* XML Format:\n <foo bar1=\"bar1value\" bar2=\"5\">\n <bar3>bar3 data</bar3>\n <bar4>10</bar4>\n </foo>\n */\n\n return new Foo(xmlParam.@bar1, xmlParam.@bar2, xmlParam.bar3[0], xmlParam.bar4[0]);\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 194517,
"author": "James Fassett",
"author_id": 27081,
"author_profile": "https://Stackoverflow.com/users/27081",
"pm_score": 1,
"selected": false,
"text": "<p>If you aren't tied to XML (e.g. you have an app server instead of a file server) you could consider using AMF (<a href=\"http://en.wikipedia.org/wiki/Action_Message_Format\" rel=\"nofollow noreferrer\">Action Message Format</a>) to transfer the data. There are a few projects that expose AMF to servers including Adobe's own <a href=\"http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/\" rel=\"nofollow noreferrer\">Blaze DS</a> and community open source variants such as <a href=\"http://sourceforge.net/projects/openamf/\" rel=\"nofollow noreferrer\">OpenAMF</a>, <a href=\"http://www.amfphp.org/\" rel=\"nofollow noreferrer\">AMFPHP</a>, <a href=\"http://pyamf.org/\" rel=\"nofollow noreferrer\">PyAMF</a> and so on. This will give you the ability to transfer custom objects from the server to Flex, automatic parsing of data-types and type safety. Have a look at <a href=\"http://www.jamesward.com/census/\" rel=\"nofollow noreferrer\">this comparison of data transfer options</a> to get an idea of the relative merits.</p>\n\n<p>That being said, XML can be very useful for things like app configuration data and in those instances you aren't running an app server. I agree with the other poster where I will immediately parse the xml into appropriate structures by hand. I usually store these with the post-fix VO (for Value Object) and I leave the members as public. I often do this hierarchically.</p>\n\n<pre><code>package model.vo\n{\npublic class ConfigVO\n{\n public var foo:String;\n public var bar:int;\n public var baz:Boolean;\n public var sections:Array;\n\n public function ConfigVO(xml:XML)\n {\n parseXML(xml);\n }\n\n private function parseXML(xml:XML):void\n {\n foo = xml.foo;\n bar = xml.bar;\n baz = (xml.baz == \"true\");\n\n sections = [];\n for each(var sectionXML:XML in xml.section)\n {\n sections.push(new SectionVO(sectionXML));\n }\n }\n}\n}\n\npackage model.vo\n{\npublic class SectionVO\n{\n public var title:String;\n\n public function SectionVO(xml:XML)\n {\n parseXML(xml);\n }\n\n private function parseXML(xml:XML):void\n {\n title = xml.@title;\n }\n}\n}\n</code></pre>\n\n<p>I've seen systems in the past that will bind XML element names to class definitions. These usually use some sort of introspection on the class to determine what properties to read off the xml or they will have some static class properties that map instance properties to xml tags or attributes. In my experience they are much more trouble than they are worth. It takes all of 2 seconds to add a new public property and a single line to read the data from an attribute or child tag. It is my suggestion to avoid such complex schemes but I'll give a simple example for completeness.</p>\n\n<pre><code>package model\n{\n public class XMLReader\n {\n // maps <tagname> to a class \n private static var elementClassMap:Object =\n {\n \"section\": SectionVO,\n \"person\": PersonVO\n };\n\n public var parsedElements:Array;\n\n public function XMLReader(xml:XML)\n {\n parsedElements = [];\n parseXML(xml);\n }\n\n private function parseXML(xml:XML):void\n {\n var voClass:Class;\n for each(var element:XML in xml.children())\n {\n voClass = elementClassMap[element.name().localname];\n if(voClass)\n {\n parsedElements.push(new voClass(element));\n }\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 233109,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://blog.flexexamples.com/2007/09/19/converting-xml-to-objects-using-the-flex-simplexmldecoder-class/\" rel=\"nofollow noreferrer\">converting xml to objects using the flex simplexmldecoder class</a> @flexExamples</p>\n"
},
{
"answer_id": 280732,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>A little while ago I started working on a Flex Library that will help serialize and deserialize Action Script objects to and from XML. All you have to do is create your model objects, put some annotations on the fields to let the serializer know how you want the field to be serialized (element, attribute, what name, etc) and the call the (de)serialization process.</p>\n\n<p>I think it suits your needs.</p>\n\n<p>If you want, you can check it out at <a href=\"http://code.google.com/p/flexxb/\" rel=\"nofollow noreferrer\">http://code.google.com/p/flexxb/</a>.</p>\n\n<p>Hope this will prove to be helpful.</p>\n"
},
{
"answer_id": 1119358,
"author": "Zefiro",
"author_id": 131146,
"author_profile": "https://Stackoverflow.com/users/131146",
"pm_score": 0,
"selected": false,
"text": "<p>Creating strong data types has several advantages, code completion and compile time syntax checking being the most important ones. Manual mappings can be done, but should be generated (and thus aren't really manual any more after all) to avoid being out of sync sooner or later.</p>\n\n<p>Introspection-based general conversion libraries are versatile, easy to use, and should suffice for most use-cases.</p>\n\n<p>JAXB is the standard for Java. <a href=\"http://lab.arc90.com/2009/02/actionscript_xml_binding.php\" rel=\"nofollow noreferrer\">ASXB</a> provides a lightweight implementation of this idea for the Actionscript world. It uses explicit AS objects with annotations to (un)marshal objects from and to XML.</p>\n\n<p>If you are forced to use XML on the wire, I'd suggest giving ASXB a closer look. If you're free to choose your format and have a supporting Server-side, Adobes own AMF format should be your choice, as it's directly supported in the language and has a much lower overhead during transport.</p>\n\n<p>In our current project, we wrote small code generators which takes the external API of the Java side (source introspection, to also copy the Javadoc) and generate the AS classes from it during our build process. It was thus easy to switch from AMF to XML when external requirements forced us to do so.</p>\n\n<p>PS: remember to add the compiler parameters to your flex config file to keep the annotations</p>\n"
},
{
"answer_id": 1370523,
"author": "maxmc",
"author_id": 55383,
"author_profile": "https://Stackoverflow.com/users/55383",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://splink.org/?p=14\" rel=\"nofollow noreferrer\">AsBeanGen</a> can do this. It generates value objects for DTD driven XML files.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13220/"
] |
A project I'm working on will pull XML from a web-server and build a data store from it. The data will have certain core fields but needs to be extendable... for example I have a and later might want to have which adds extra fields.
In the Flex app, I don't want the central data store to be working on XML objects or simply putting the properties into Objects. I want to have strong types, e.g a Person class, which are created/populated from the XML.
How can this be done in a flexible way? Is Flex able to automatically build a Person from an XML if the attribute names match, or do I need to write conversion functionality for , , etc?
|
I don't think this can be done automatically. I generally create the a class to mirror the XML structure I have and then create a static class method to create an instance of the object given an XML node. For example:
```
package {
public class Foo{
public function Foo(barparam1:String, barparam2:uint, barparam3:String, barparam4:Number){
this._bar1 = barparam1;
this._bar2 = barparam2;
this._bar3 = barparam3;
this._bar4 = barparam4;
}
protected var _bar1:String;
protected var _bar2:uint;
protected var _bar3:String;
protected var _bar4:Number;
public function get bar1():String{ return this._bar1; }
public function get bar2():uint { return this._bar2; }
public function get bar3():String { return this._bar3; }
public function get bar4():Number { return this._bar4; }
public function toString():String{
return "[Foo bar1:\"" + this.bar1 + "\", bar3:\"" + this.bar3 + "\", bar2:" + this.bar2 + ", bar4:" + this.bar4 + "]";
}
public static function createFromXml(xmlParam:XML):Foo{
/* XML Format:
<foo bar1="bar1value" bar2="5">
<bar3>bar3 data</bar3>
<bar4>10</bar4>
</foo>
*/
return new Foo(xmlParam.@bar1, xmlParam.@bar2, xmlParam.bar3[0], xmlParam.bar4[0]);
}
}
}
```
|
186,311 |
<p>I have a list of Date objects, and a target Date. I want to find the date in the list that's nearest to the target date, but only dates that are before the target date.</p>
<p>Example:
2008-10-1
2008-10-2
2008-10-4</p>
<p>With a target date of 2008-10-3, I want to get 2008-10-2</p>
<p>What is the best way to do it?</p>
|
[
{
"answer_id": 186318,
"author": "Sietse",
"author_id": 6400,
"author_profile": "https://Stackoverflow.com/users/6400",
"pm_score": 2,
"selected": false,
"text": "<p>I currently use the following method, but I'm not sure it's the most effective one, because this assumes an already sorted list, and (potentially) iterates over every single date in the list.</p>\n\n<pre><code>private Date getDateNearest(List<Date> dates, Date targetDate){\n for (Date date : dates) {\n if (date.compareTo(targetDate) <= 0) return date;\n }\n\n return targetDate;\n}\n</code></pre>\n"
},
{
"answer_id": 186420,
"author": "Keeg",
"author_id": 21059,
"author_profile": "https://Stackoverflow.com/users/21059",
"pm_score": 3,
"selected": false,
"text": "<pre><code>private Date getDateNearest(List<Date> dates, Date targetDate){\n return new TreeSet<Date>(dates).lower(targetDate);\n}\n</code></pre>\n\n<p>Doesn't require a pre-sorted list, TreeSort fixes that. It'll return null if it can't find one though, so you will have to modify it if that's a problem. Not sure of the efficency either :P</p>\n"
},
{
"answer_id": 186480,
"author": "Jean",
"author_id": 7898,
"author_profile": "https://Stackoverflow.com/users/7898",
"pm_score": 4,
"selected": true,
"text": "<p>Sietse de Kaper solution assumes a <em>reverse</em> sorted list, definitely not the most natural thing to have around</p>\n\n<p>The natural sort order in java is following the ascending natural ordering. (see Collection.sort <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#sort(java.util.List)\" rel=\"noreferrer\">http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#sort(java.util.List)</a> documentation)</p>\n\n<p>From your example, </p>\n\n<pre>\ntarget date = 2008-10-03 \nlist = 2008-10-01 2008-10-02 2008-10-04 \n</pre>\n\n<p>If another developper uses your method with a naive approach he would get 2008-10-01 which is not what was expected</p>\n\n<p><li>Don't make assumptions as to the ordering of the list. \n<li>If you have to for performance reasons try to follow the most natural convention (sorted ascending)\n<li>If you really have to follow another convention you really should document the hell out of it. </p>\n\n<pre><code>private Date getDateNearest(List<Date> dates, Date targetDate){\n Date returnDate = targetDate\n for (Date date : dates) {\n // if the current iteration'sdate is \"before\" the target date\n if (date.compareTo(targetDate) <= 0) {\n // if the current iteration's date is \"after\" the current return date\n if (date.compareTo(returnDate) > 0){\n returnDate=date;\n }\n }\n } \n return returnDate;\n}\n</code></pre>\n\n<p>edit - I also like the Treeset answer but I think it might be slightly slower as it is equivalent to sorting the data then looking it up => nlog(n) for sorting and then the documentation implies it is log(n) for access so that would be nlog(n)+log(n) vs n</p>\n"
},
{
"answer_id": 186481,
"author": "Daniel Hiller",
"author_id": 16193,
"author_profile": "https://Stackoverflow.com/users/16193",
"pm_score": 1,
"selected": false,
"text": "<p>Although the answer from Keeg is valid in 1.6 in 1.5 there is no method lower() (We're unfortunate to develop against 1.5 :-( )</p>\n\n<p>this one works in 1.5</p>\n\n<pre><code>import java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.TreeSet;\n\npublic class GetNearestDate {\n\n public static void main( String[] args ) throws ParseException {\n\n final SimpleDateFormat simpleDateFormat = new SimpleDateFormat( \"dd.MM.yyyy HH:mm:ss\" );\n\n List< Date > otherDates = Arrays.asList( new Date[]{\n simpleDateFormat.parse( \"01.01.2008 01:00:00\" ) ,\n simpleDateFormat.parse( \"01.01.2008 01:00:02\" ) } );\n System.out.println( simpleDateFormat.parse( \"01.01.2008 01:00:00\" ).equals(\n get( otherDates , simpleDateFormat.parse( \"01.01.2008 01:00:01\" ) ) ) );\n System.out.println( simpleDateFormat.parse( \"01.01.2008 01:00:02\" ).equals(\n get( otherDates , simpleDateFormat.parse( \"01.01.2008 01:00:03\" ) ) ) );\n System.out.println( null == get( otherDates , simpleDateFormat.parse( \"01.01.2008 01:00:00\" ) ) );\n }\n\n public static Date get( List< Date > otherDates , Date dateToApproach ) {\n final TreeSet< Date > set = new TreeSet< Date >( otherDates );\n set.add( dateToApproach );\n final ArrayList< Date > list = new ArrayList< Date >( set );\n final int indexOf = list.indexOf( dateToApproach );\n if ( indexOf == 0 )\n return null;\n return list.get( indexOf - 1 );\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 190026,
"author": "Aidos",
"author_id": 12040,
"author_profile": "https://Stackoverflow.com/users/12040",
"pm_score": 0,
"selected": false,
"text": "<p>Have you looked at the JodaTime API? I seem to recall a feature like this being available.</p>\n"
},
{
"answer_id": 38033180,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 1,
"selected": false,
"text": "<h1><code>NavigableSet::lower</code></h1>\n\n<p>The <a href=\"https://stackoverflow.com/a/186420/642706\">Answer by Keeg</a> is cleverly brief. The idea there is to make use of the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/NavigableSet.html#lower-E-\" rel=\"nofollow noreferrer\"><code>lower</code></a> method defined in the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/NavigableSet.html\" rel=\"nofollow noreferrer\"><code>NavigableSet</code></a> interface and implemented in the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html\" rel=\"nofollow noreferrer\"><code>TreeSet</code></a> class.</p>\n\n<p>But like the other answers it uses the old outmoded date-time classes bundled with the earliest versions of Java. Below is an updated version using <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html\" rel=\"nofollow noreferrer\">java.time</a> classes.</p>\n\n<p>The old question and answers are using either <code>java.util.Date</code> which is a moment on the timeline in UTC representing both a date <em>and</em> a time-of-day, or the <code>java.sql.Date</code> which awkwardly extends util.Date while pretending it does not have a time-of-day. A confusing mess.</p>\n\n<h1>java.time</h1>\n\n<p>Those troublesome old classes have been supplanted by the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html\" rel=\"nofollow noreferrer\">java.time</a> classes built into Java 8 and later. See <a href=\"http://docs.oracle.com/javase/tutorial/datetime/TOC.html\" rel=\"nofollow noreferrer\">Oracle Tutorial</a>. Much of the functionality has been back-ported to Java 6 & 7 in <a href=\"http://www.threeten.org/threetenbp/\" rel=\"nofollow noreferrer\">ThreeTen-Backport</a> and further adapted to Android in <a href=\"https://github.com/JakeWharton/ThreeTenABP\" rel=\"nofollow noreferrer\">ThreeTenABP</a>.</p>\n\n<h1><code>LocalDate</code></h1>\n\n<p>The <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html\" rel=\"nofollow noreferrer\"><code>LocalDate</code></a> class represents a date-only value without time-of-day and without time zone. While these objects store no time zone, note that time zone (<a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html\" rel=\"nofollow noreferrer\"><code>ZoneId</code></a>) is crucial in determining the current date. For any given moment the date varies around the globe by time zone.</p>\n\n<pre><code>ZoneId zoneId = ZoneId.of( \"America/Montreal\" );\nLocalDate today = LocalDate.now( zoneId ); // 2016-06-25\n</code></pre>\n\n<h1>ISO 8601</h1>\n\n<p>Tip: Pad those month and day-of-month numbers with a leading zero. This makes them comply with the <a href=\"https://en.wikipedia.org/wiki/ISO_8601\" rel=\"nofollow noreferrer\">ISO 8601</a> standard date-time formats. These formats are used by default in java.time when parsing/generating strings that represent date-time values.</p>\n\n<p>So use <code>2008-10-01</code> rather than <code>2008-10-1</code>. If padding is not feasible, parse using <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html\" rel=\"nofollow noreferrer\"><code>DateTimeFormatter</code></a>.</p>\n\n<pre><code>NavigableSet dates = new TreeSet( 3 );\ndates.add( LocalDate.parse( \"2008-10-01\" );\ndates.add( LocalDate.parse( \"2008-10-02\" );\ndates.add( LocalDate.parse( \"2008-10-04\" );\nLocalDate target = LocalDate.parse( \"2008-10-03\" );\nLocalDate hit = dates.lower( target );\n// Reminder: test for `null == hit` to see if anything found.\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6400/"
] |
I have a list of Date objects, and a target Date. I want to find the date in the list that's nearest to the target date, but only dates that are before the target date.
Example:
2008-10-1
2008-10-2
2008-10-4
With a target date of 2008-10-3, I want to get 2008-10-2
What is the best way to do it?
|
Sietse de Kaper solution assumes a *reverse* sorted list, definitely not the most natural thing to have around
The natural sort order in java is following the ascending natural ordering. (see Collection.sort <http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#sort(java.util.List)> documentation)
From your example,
```
target date = 2008-10-03
list = 2008-10-01 2008-10-02 2008-10-04
```
If another developper uses your method with a naive approach he would get 2008-10-01 which is not what was expected
- Don't make assumptions as to the ordering of the list.
- If you have to for performance reasons try to follow the most natural convention (sorted ascending)
- If you really have to follow another convention you really should document the hell out of it.
```
private Date getDateNearest(List<Date> dates, Date targetDate){
Date returnDate = targetDate
for (Date date : dates) {
// if the current iteration'sdate is "before" the target date
if (date.compareTo(targetDate) <= 0) {
// if the current iteration's date is "after" the current return date
if (date.compareTo(returnDate) > 0){
returnDate=date;
}
}
}
return returnDate;
}
```
edit - I also like the Treeset answer but I think it might be slightly slower as it is equivalent to sorting the data then looking it up => nlog(n) for sorting and then the documentation implies it is log(n) for access so that would be nlog(n)+log(n) vs n
|
186,313 |
<p>I'm using the Scriptaculous library to slap an appealing UI on an application which helps an enduser build lists. Let's say its for pizza creation.</p>
<p>To fill out an order, you drag a size of pizza from the pizza palette into the orders droppable. Once it is put in there, it gets replaced with a new div which is both draggable (because you can junk it by moving it back to the palette) and droppable (because you can add ingredients to it). </p>
<p>You can then add ingredients from your ingredients palette to any of the pizzas you have sitting in the group of orders. </p>
<p>I've successfully implemented these bits and everything works fine. The stickler: if I attempt to drag and drop the ingredient from a placed pizza, which is properly marked as draggable and which, for good measure, is z-positioned above the pizza, it instead grabs the pizza wholesale. This makes it impossible for me to undo ingredient selections, which is a key feature for this screen.</p>
<p>Any suggestions on how I can get this to do what I want? Ideally I'd like to keep the simple drag-on, drag-off UI as it is <em>worlds</em> more intuitive than what we were using previously. (A multi-stage HTML form... shudder...)</p>
|
[
{
"answer_id": 187094,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 0,
"selected": false,
"text": "<p>Try this, I think it's close to what you're trying to do. I'm using a sortable for the list on the left. You may not need to.</p>\n\n<pre><code><table border=\"1\" cellpadding=\"5\">\n<tr>\n <td valign=\"top\">\n <ul id='fList' style='border:1px solid #c0c0c0'>\n <li class='fruit'>Apples</li>\n <li class='fruit'>Grapes</li>\n <li class='fruit'>Strawberries</li>\n </ul>\n (drag items or panel)\n </td>\n <td valign=\"top\">\n <div id='fish' class='meat'>Fish</div>\n <div id='chicken' class='meat'>Chicken</div>\n (drop to left list)\n </td>\n</tr></table>\n\n\n\nSortable.create(\"fList\", {constraint:false})\nnew Draggable('fish',{revert:true})\nnew Draggable('chicken',{revert:true})\nnew Draggable('fList')\nDroppables.add('fList',{accept:'meat',onDrop:function(dragName,dropName){placeFood(dragName,dropName)}})\nDroppables.add('fList',{accept:'fruit'})\n\nfunction placeFood(dragName,dropName) {\n $(\"fList\").insert(new Element(\"li\", { id: $(dragName).id+\"_\" }))\n $($(dragName).id+\"_\").innerHTML = $(dragName).innerHTML\n Sortable.destroy(\"fList\")\n Sortable.create(\"fList\", {constraint:false})\n}\n</code></pre>\n"
},
{
"answer_id": 196688,
"author": "Patrick McKenzie",
"author_id": 15046,
"author_profile": "https://Stackoverflow.com/users/15046",
"pm_score": 3,
"selected": true,
"text": "<p>It turns out, after a few days of banging my heads into various walls, that Scriptaculous will happily nest things by default.</p>\n\n<p>The issue is when your call to <code>draggable_element</code> looks like this</p>\n\n<pre><code><% draggable_element blah blah blah blah blah blah blah%>\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code><%= draggable_element blah blah blah blah blah blah blah %>\n</code></pre>\n\n<p>D'oh!</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15046/"
] |
I'm using the Scriptaculous library to slap an appealing UI on an application which helps an enduser build lists. Let's say its for pizza creation.
To fill out an order, you drag a size of pizza from the pizza palette into the orders droppable. Once it is put in there, it gets replaced with a new div which is both draggable (because you can junk it by moving it back to the palette) and droppable (because you can add ingredients to it).
You can then add ingredients from your ingredients palette to any of the pizzas you have sitting in the group of orders.
I've successfully implemented these bits and everything works fine. The stickler: if I attempt to drag and drop the ingredient from a placed pizza, which is properly marked as draggable and which, for good measure, is z-positioned above the pizza, it instead grabs the pizza wholesale. This makes it impossible for me to undo ingredient selections, which is a key feature for this screen.
Any suggestions on how I can get this to do what I want? Ideally I'd like to keep the simple drag-on, drag-off UI as it is *worlds* more intuitive than what we were using previously. (A multi-stage HTML form... shudder...)
|
It turns out, after a few days of banging my heads into various walls, that Scriptaculous will happily nest things by default.
The issue is when your call to `draggable_element` looks like this
```
<% draggable_element blah blah blah blah blah blah blah%>
```
instead of
```
<%= draggable_element blah blah blah blah blah blah blah %>
```
D'oh!
|
186,328 |
<p>Which is generally fastest when reading/comparing row info from a DataTable?</p>
<pre><code>'assume dt as datatable'
'method 1'
dim i as int32
for i = 0 to dt.rows.count - 1
....
next
'method 2'
dim row as datarow
for each row in dt.rows
....
next
</code></pre>
<p>And if there's a difference, in what circumstances does it pay to use one over the other? </p>
<p>Thanks in advance for any guidance!</p>
|
[
{
"answer_id": 186343,
"author": "Greg Dean",
"author_id": 1200558,
"author_profile": "https://Stackoverflow.com/users/1200558",
"pm_score": 2,
"selected": false,
"text": "<p>In reality no difference. Although you technically pay a small price in the foreach method, for going through the IEnumerable interface.</p>\n"
},
{
"answer_id": 186353,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 2,
"selected": false,
"text": "<p>The second would have a slight penalty. However as for circumstances, I persoanlly would always use method 2 for clarity of code. However, I would use method 1 if I ever need to do something such as accessing a next/previous row while analyzing the current row.</p>\n"
},
{
"answer_id": 186357,
"author": "Mike",
"author_id": 1573,
"author_profile": "https://Stackoverflow.com/users/1573",
"pm_score": 1,
"selected": false,
"text": "<p>@gdean232 is right - almost no difference at all. If performance is an issue, using a a SqlDataReader instead is noticeable faster.</p>\n"
},
{
"answer_id": 186363,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 4,
"selected": true,
"text": "<p>The compiler expands For Each to a short while loop.</p>\n\n<pre><code>for each row in dt.rows\n// expands to:\nIEnumerator e = dt.rows.GetEnumerator()\nwhile e.MoveNext()\n row = e.Current\n</code></pre>\n\n<p>So you pay a small amount of overhead. But for clarities sake, I'd still stick with For Each if you're only working on one row, and you aren't modifying the data set.</p>\n"
},
{
"answer_id": 186375,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": -1,
"selected": false,
"text": "<p>The foreach implementation is actually slightly faster than the standard for implementation, because each index array access needs to be bounds checked. However, since the idiom:</p>\n\n<pre><code>for(int i =0; i < myArray.Count; ++i)\n{\n // do something with myArray[i];\n}\n</code></pre>\n\n<p>is common, the compiler looks for it as a special case and optimizes it, so it becomes faster. However, any small deviation from that format (such as int len = MyArray.Count; for(int i =0; i< len; ++i)) won't be recognized, and will use the slower code.</p>\n"
},
{
"answer_id": 186376,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 2,
"selected": false,
"text": "<p>Well, there is a difference, since GetEnumerator and MoveNext that get called in foreach-loop are virtual (calling requires going through a pointer) and thus can't be inlined. This overhead in reality is small, unless you do a <strong>lot</strong> of loops. </p>\n\n<p>In some cases though the compiler will replace foreach with a for-loop (I believe when iterating over arrays).</p>\n\n<p>I personally prefer foreach in my ASP.NET MVC code for clarity, as many have said here, but often use the for-loop too.\nJoe Duffy recently posted an interesting article about the cost of enumerating\n<a href=\"http://joeduffyblog.com/2008/09/21/the-cost-of-enumerating-in-net/\" rel=\"nofollow noreferrer\">http://joeduffyblog.com/2008/09/21/the-cost-of-enumerating-in-net/</a></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17235/"
] |
Which is generally fastest when reading/comparing row info from a DataTable?
```
'assume dt as datatable'
'method 1'
dim i as int32
for i = 0 to dt.rows.count - 1
....
next
'method 2'
dim row as datarow
for each row in dt.rows
....
next
```
And if there's a difference, in what circumstances does it pay to use one over the other?
Thanks in advance for any guidance!
|
The compiler expands For Each to a short while loop.
```
for each row in dt.rows
// expands to:
IEnumerator e = dt.rows.GetEnumerator()
while e.MoveNext()
row = e.Current
```
So you pay a small amount of overhead. But for clarities sake, I'd still stick with For Each if you're only working on one row, and you aren't modifying the data set.
|
186,338 |
<p>Everything I read about better PHP coding practices keeps saying don't use <code>require_once</code> because of speed.</p>
<p>Why is this?</p>
<p>What is the proper/better way to do the same thing as <code>require_once</code>? If it matters, I'm using PHP 5.</p>
|
[
{
"answer_id": 186346,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": false,
"text": "<p>A better way to do things is to use an object-oriented approach and use <a href=\"http://www.php.net/__autoload\" rel=\"noreferrer\">__autoload()</a>.</p>\n"
},
{
"answer_id": 186386,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 8,
"selected": true,
"text": "<p><code>require_once</code> and <code>include_once</code> both require that the system keeps a log of what's already been included/required. Every <code>*_once</code> call means checking that log. So there's definitely <em>some</em> extra work being done there but enough to detriment the speed of the whole app?</p>\n\n<p>... I really doubt it... Not unless you're on <em>really</em> old hardware or doing it a <em>lot</em>.</p>\n\n<p>If you <em>are</em> doing thousands of <code>*_once</code>, you could do the work yourself in a lighter fashion. For simple apps, just making sure you've only included it once <em>should</em> suffice but if you're still getting redefine errors, you could something like this:</p>\n\n<pre><code>if (!defined('MyIncludeName')) {\n require('MyIncludeName');\n define('MyIncludeName', 1);\n}\n</code></pre>\n\n<p>I'll personally stick with the <code>*_once</code> statements but on silly million-pass benchmark, you can see a difference between the two:</p>\n\n<pre><code> php hhvm\nif defined 0.18587779998779 0.046600103378296\nrequire_once 1.2219581604004 3.2908599376678\n</code></pre>\n\n<p>10-100× slower with <code>require_once</code> and it's curious that <code>require_once</code> is seemingly slower in <code>hhvm</code>. Again, this is only relevant to your code if you're running <code>*_once</code> thousands of times.</p>\n\n<hr>\n\n<pre><code><?php // test.php\n\n$LIMIT = 1000000;\n\n$start = microtime(true);\n\nfor ($i=0; $i<$LIMIT; $i++)\n if (!defined('include.php')) {\n require('include.php');\n define('include.php', 1);\n }\n\n$mid = microtime(true);\n\nfor ($i=0; $i<$LIMIT; $i++)\n require_once('include.php');\n\n$end = microtime(true);\n\nprintf(\"if defined\\t%s\\nrequire_once\\t%s\\n\", $mid-$start, $end-$mid);\n</code></pre>\n\n<hr>\n\n<pre><code><?php // include.php\n\n// do nothing.\n</code></pre>\n"
},
{
"answer_id": 186406,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 5,
"selected": false,
"text": "<p>Can you give us any links to these coding practices which say to avoid it? As far as I'm concerned, <strong>it's a complete non-issue</strong>. I haven't looked at the source code myself, but I'd imagine that the only difference between <code>include</code> and <code>include_once</code> is that <code>include_once</code> adds that filename to an array and checks over the array each time. It'd be easy to keep that array sorted, so searching over it should be O(log n), and even a medium-largish application would only have a couple of dozen includes.</p>\n"
},
{
"answer_id": 186433,
"author": "Ekkmanz",
"author_id": 850,
"author_profile": "https://Stackoverflow.com/users/850",
"pm_score": -1,
"selected": false,
"text": "<p>I think in PEAR documentation, there is a recommendation for require, require_once, include and include_once. I do follow that guideline. Your application would be more clear.</p>\n"
},
{
"answer_id": 186614,
"author": "Dinoboff",
"author_id": 1771,
"author_profile": "https://Stackoverflow.com/users/1771",
"pm_score": 0,
"selected": false,
"text": "<p>You test, using include, oli's alternative and __autoload(); and test it with <a href=\"http://en.wikipedia.org/wiki/Alternative_PHP_Cache#Alternative_PHP_Cache\" rel=\"nofollow noreferrer\">something like APC</a> installed.</p>\n\n<p>I doubt using constant will speed things up.</p>\n"
},
{
"answer_id": 186650,
"author": "Joe Scylla",
"author_id": 25771,
"author_profile": "https://Stackoverflow.com/users/25771",
"pm_score": -1,
"selected": false,
"text": "<p>My personal opinion is that the usage of require_once (or include_once) is bad practice because require_once checks for you if you already included that file and suppress errors of double included files resulting in fatal errors (like duplicate declaration of functions/classes/etc.).</p>\n\n<p>You should know if you need to include a file.</p>\n"
},
{
"answer_id": 187053,
"author": "Annika Backstrom",
"author_id": 7675,
"author_profile": "https://Stackoverflow.com/users/7675",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>*_once()</code> functions <a href=\"https://en.wikipedia.org/wiki/Stat_(system_call)\" rel=\"nofollow noreferrer\">stat</a> every parent directory to ensure the file you're including isn't the same as one that's already been included. That's part of the reason for the slowdown.</p>\n<p>I recommend using a tool like <a href=\"http://www.joedog.org/JoeDog/Siege\" rel=\"nofollow noreferrer\">Siege</a> for benchmarking. You can try all the suggested methodologies and compare response times.</p>\n<p>More on <code>require_once()</code> is at <a href=\"https://web.archive.org/web/20110713073725/http://www.techyouruniverse.com/software/php-performance-tip-require-versus-require_once\" rel=\"nofollow noreferrer\">Tech Your Universe</a><em><sup> <a href=\"http://www.techyouruniverse.com/software/php-performance-tip-require-versus-require_once\" rel=\"nofollow noreferrer\">url</a></sup></em>.</p>\n"
},
{
"answer_id": 187090,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, it is slightly more expensive than plain ol' require(). I think the point is if you can keep your code organized enough to not duplicate includes, don't use the *_once() functions, as it will save you some cycles.</p>\n\n<p>But using the _once() functions isn't going to kill your application. Basically, just <strong>don't use it as an excuse to not have to organize your includes</strong>. In some cases, using it is still unavoidable, and it's not a big deal.</p>\n"
},
{
"answer_id": 193664,
"author": "Steve Clay",
"author_id": 3779,
"author_profile": "https://Stackoverflow.com/users/3779",
"pm_score": 3,
"selected": false,
"text": "<p>The PEAR2 wiki (when it existed) used to list <a href=\"http://web.archive.org/web/20090219000012/http://wiki.pear.php.net/index.php/PEAR2_Standards#Introduction\" rel=\"nofollow noreferrer\">good reasons for abandoning <em>all</em> the require/include directives in favor of autoload</a>ing, at least for library code. These tie you down to rigid directory structures when alternative packaging models like <a href=\"http://www.php.net/manual/en/intro.phar.php\" rel=\"nofollow noreferrer\">phar</a> are on the horizon.</p>\n\n<p>Update: As the web archived version of the wiki is eye-gougingly ugly, I've copied the most compelling reasons below:</p>\n\n<blockquote>\n <ul>\n <li>include_path is required in order to use a (PEAR) package. This makes it difficult to bundle a PEAR package within another application with its\n own include_path, to create a single file containing needed classes,\n to move a PEAR package to a phar archive without extensive source code\n modification.</li>\n <li>when top-level require_once is mixed with conditional require_once, this can result in code that is uncacheable by opcode caches such as\n APC, which will be bundled with PHP 6.</li>\n <li>relative require_once requires that include_path already be set up to the correct value, making it impossible to use a package without\n proper include_path</li>\n </ul>\n</blockquote>\n"
},
{
"answer_id": 194959,
"author": "terson",
"author_id": 22974,
"author_profile": "https://Stackoverflow.com/users/22974",
"pm_score": 6,
"selected": false,
"text": "<p>I got curious and checked out Adam Backstrom's link to <a href=\"https://web.archive.org/web/20080808221243/http://www.techyouruniverse.com/software/php-performance-tip-require-versus-require_once\" rel=\"nofollow noreferrer\">Tech Your Universe</a>. This article describes one of the reasons that require should be used instead of require_once. However, their claims didn't hold up to my analysis. I'd be interested in seeing where I may have misanalysed the solution. I used PHP 5.2.0 for comparisons.</p>\n\n<p>I started out by creating 100 header files that used require_once to include another header file. Each of these files looked something like:</p>\n\n<pre><code><?php\n // /home/fbarnes/phpperf/hdr0.php\n require_once \"../phpperf/common_hdr.php\";\n\n?>\n</code></pre>\n\n<p>I created these using a quick Bash hack:</p>\n\n<pre><code>for i in /home/fbarnes/phpperf/hdr{00..99}.php; do\n echo \"<?php\n // $i\" > $i\n cat helper.php >> $i;\ndone\n</code></pre>\n\n<p>This way I could easily swap between using require_once and require when including the header files. I then created an app.php to load the one hundred files. This looked like:</p>\n\n<pre><code><?php\n // Load all of the php hdrs that were created previously\n for($i=0; $i < 100; $i++)\n {\n require_once \"/home/fbarnes/phpperf/hdr$i.php\";\n }\n\n // Read the /proc file system to get some simple stats\n $pid = getmypid();\n $fp = fopen(\"/proc/$pid/stat\", \"r\");\n $line = fread($fp, 2048);\n $array = split(\" \", $line);\n\n // Write out the statistics; on RedHat 4.5 with kernel 2.6.9\n // 14 is user jiffies; 15 is system jiffies\n $cntr = 0;\n foreach($array as $elem)\n {\n $cntr++;\n echo \"stat[$cntr]: $elem\\n\";\n }\n fclose($fp);\n?>\n</code></pre>\n\n<p>I contrasted the require_once headers with require headers that used a header file looking like:</p>\n\n<pre><code><?php\n // /home/fbarnes/phpperf/h/hdr0.php\n if(!defined('CommonHdr'))\n {\n require \"../phpperf/common_hdr.php\";\n define('CommonHdr', 1);\n }\n?>\n</code></pre>\n\n<p>I didn't find much difference when running this with require vs. require_once. In fact, my initial tests seemed to imply that require_once was slightly faster, but I don't necessarily believe that. I repeated the experiment with 10000 input files. Here I did see a consistent difference. I ran the test multiple times, the results are close but using require_once uses on average 30.8 user jiffies and 72.6 system jiffies; using require uses on average 39.4 user jiffies and 72.0 system jiffies. Therefore, it appears that the load is slightly lower using require_once. However, the wall clock time is slightly increased. The 10,000 require_once calls use 10.15 seconds to complete on average and 10,000 require calls use 9.84 seconds on average.</p>\n\n<p>The next step is to look into these differences. I used <a href=\"https://en.wikipedia.org/wiki/Strace\" rel=\"nofollow noreferrer\">strace</a> to analyse the system calls that are being made.</p>\n\n<p>Before opening a file from require_once the following system calls are made:</p>\n\n<pre><code>time(NULL) = 1223772434\nlstat64(\"/home\", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0\nlstat64(\"/home/fbarnes\", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0\nlstat64(\"/home/fbarnes/phpperf\", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0\nlstat64(\"/home/fbarnes/phpperf/h\", {st_mode=S_IFDIR|0755, st_size=270336, ...}) = 0\nlstat64(\"/home/fbarnes/phpperf/h/hdr0.php\", {st_mode=S_IFREG|0644, st_size=88, ...}) = 0\ntime(NULL) = 1223772434\nopen(\"/home/fbarnes/phpperf/h/hdr0.php\", O_RDONLY) = 3\n</code></pre>\n\n<p>This contrasts with require:</p>\n\n<pre><code>time(NULL) = 1223772905\nlstat64(\"/home\", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0\nlstat64(\"/home/fbarnes\", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0\nlstat64(\"/home/fbarnes/phpperf\", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0\nlstat64(\"/home/fbarnes/phpperf/h\", {st_mode=S_IFDIR|0755, st_size=270336, ...}) = 0\nlstat64(\"/home/fbarnes/phpperf/h/hdr0.php\", {st_mode=S_IFREG|0644, st_size=146, ...}) = 0\ntime(NULL) = 1223772905\nopen(\"/home/fbarnes/phpperf/h/hdr0.php\", O_RDONLY) = 3\n</code></pre>\n\n<p>Tech Your Universe implies that require_once should make more lstat64 calls. However, they both make the same number of lstat64 calls. Possibly, the difference is that I am not running APC to optimize the code above. However, next I compared the output of strace for the entire runs:</p>\n\n<pre><code>[fbarnes@myhost phpperf]$ wc -l strace_1000r.out strace_1000ro.out\n 190709 strace_1000r.out\n 210707 strace_1000ro.out\n 401416 total\n</code></pre>\n\n<p>Effectively there are approximately two more system calls per header file when using require_once. One difference is that require_once has an additional call to the time() function:</p>\n\n<pre><code>[fbarnes@myhost phpperf]$ grep -c time strace_1000r.out strace_1000ro.out\nstrace_1000r.out:20009\nstrace_1000ro.out:30008\n</code></pre>\n\n<p>The other system call is getcwd():</p>\n\n<pre><code>[fbarnes@myhost phpperf]$ grep -c getcwd strace_1000r.out strace_1000ro.out\nstrace_1000r.out:5\nstrace_1000ro.out:10004\n</code></pre>\n\n<p>This is called because I decided to relative path referenced in the hdrXXX files. If I make this an absolute reference, then the only difference is the additional time(NULL) call made in the code:</p>\n\n<pre><code>[fbarnes@myhost phpperf]$ wc -l strace_1000r.out strace_1000ro.out\n 190705 strace_1000r.out\n 200705 strace_1000ro.out\n 391410 total\n[fbarnes@myhost phpperf]$ grep -c time strace_1000r.out strace_1000ro.out\nstrace_1000r.out:20008\nstrace_1000ro.out:30008\n</code></pre>\n\n<p>This seems to imply that you could reduce the number of system calls by using absolute paths rather than relative paths. The only difference outside of that is the time(NULL) calls which appear to be used for instrumenting the code to compare what is faster.</p>\n\n<p>One other note is that the APC optimization package has an option called \"apc.include_once_override\" that claims that it reduces the number of system calls made by the require_once and include_once calls (see the <a href=\"http://us3.php.net/manual/en/apc.configuration.php\" rel=\"nofollow noreferrer\">PHP documentation</a>).</p>\n"
},
{
"answer_id": 194979,
"author": "Edward Z. Yang",
"author_id": 23845,
"author_profile": "https://Stackoverflow.com/users/23845",
"pm_score": 7,
"selected": false,
"text": "<p>This thread makes me cringe, because there's already been a \"solution posted\", and it's, for all intents and purposes, wrong. Let's enumerate:</p>\n\n<ol>\n<li><p>Defines are <strong>really</strong> expensive in PHP. You can <a href=\"http://bugs.php.net/bug.php?id=40165\" rel=\"noreferrer\">look it up</a> or test it yourself, but the only efficient way of defining a global constant in PHP is via an extension. (Class constants are actually pretty decent performance wise, but this is a moot point, because of 2)</p></li>\n<li><p>If you are using <code>require_once()</code> appropriately, that is, for inclusion of classes, you don't even need a define; just check if <code>class_exists('Classname')</code>. If the file you are including contains code, i.e. you're using it in the procedural fashion, there is absolutely no reason that <code>require_once()</code> should be necessary for you; each time you include the file you presume to be making a subroutine call.</p></li>\n</ol>\n\n<p>So for a while, a lot of people did use the <code>class_exists()</code> method for their inclusions. I don't like it because it's fugly, but they had good reason to: <code>require_once()</code> was pretty inefficient before some of the more recent versions of PHP. But that's been fixed, and it is my contention that the extra bytecode you'd have to compile for the conditional, and the extra method call, would by far overweigh any internal hashtable check.</p>\n\n<p>Now, an admission: this stuff is tough to test for, because it accounts for so little of the execution time.</p>\n\n<p>Here is the question you should be thinking about: includes, as a general rule, are expensive in PHP, because every time the interpreter hits one it has to switch back into parse mode, generate the opcodes, and then jump back. If you have a 100+ includes, this will definitely have a performance impact. The reason why using or not using require_once is such an important question is because it makes life difficult for opcode caches. An <a href=\"http://t3.dotgnu.info/blog/php/demystifying-autofilter.html\" rel=\"noreferrer\">explanation for this</a> can be found here, but what this boils down to is that:</p>\n\n<ul>\n<li><p>If during parse time, you know exactly what include files you will need for the entire life of the request, <code>require()</code> those at the very beginning and the opcode cache will handle everything else for you.</p></li>\n<li><p>If you are not running an opcode cache, you're in a hard place. Inlining all of your includes into one file (don't do this during development, only in production) can certainly help parse time, but it's a pain to do, and also, you need to know exactly what you'll be including during the request.</p></li>\n<li><p>Autoload is very convenient, but slow, for the reason that the autoload logic has to be run every time an include is done. In practice, I've found that autoloading several specialized files for one request does not cause too much of a problem, but you should not be autoloading all of the files you will need.</p></li>\n<li><p>If you have maybe 10 includes (this is a <em>very</em> back of the envelope calculation), all this wanking is not worth it: just optimize your database queries or something.</p></li>\n</ul>\n"
},
{
"answer_id": 194988,
"author": "ashchristopher",
"author_id": 22306,
"author_profile": "https://Stackoverflow.com/users/22306",
"pm_score": -1,
"selected": false,
"text": "<p>It has nothing to do with speed. It's about failing gracefully.</p>\n\n<p>If require_once() fails, your script is done. Nothing else is processed. If you use include_once() the rest of your script will try to continue to render, so your users potentially would be none-the-wiser to something that has failed in your script. </p>\n"
},
{
"answer_id": 28171417,
"author": "NeuroXc",
"author_id": 2595915,
"author_profile": "https://Stackoverflow.com/users/2595915",
"pm_score": 2,
"selected": false,
"text": "<p>Even if <code>require_once</code> and <code>include_once</code> <em>are</em> slower than <code>require</code> and <code>include</code> (or whatever alternatives might exist), we're talking about the smallest level of micro-optimization here. Your time is much better spent optimizing that poorly written loop or database query than worrying about something like <code>require_once</code>.</p>\n\n<p>Now, one could make an argument saying that <code>require_once</code> allows for poor coding practices because you don't need to pay attention to keeping your includes clean and organized, but that has nothing to do with the function <em>itself</em> and especially not its speed.</p>\n\n<p>Obviously, autoloading is better for the sake of code cleanliness and ease of maintenance, but I want to make it clear that this has nothing to do with <em>speed</em>.</p>\n"
},
{
"answer_id": 28711865,
"author": "hexalys",
"author_id": 1647538,
"author_profile": "https://Stackoverflow.com/users/1647538",
"pm_score": 3,
"selected": false,
"text": "<p>It's not using the function that is bad. It's an incorrect understanding of how and when to use it, in an overall code base. I'll just add a bit more context to that possibly misunderstood notion:</p>\n\n<p>People shouldn't think that require_once is a slow function. You have to include your code one way or another. <code>require_once()</code> vs. <code>require()</code>'s speed isn't the issue. It's about the performance hindering caveats that may results for using it blindly. If used broadly without consideration for context, it can lead to huge memory waste or wasteful code.</p>\n\n<p>What I have seen that's really bad, is when huge monolithic frameworks use <code>require_once()</code> in all the wrong ways, especially in a complex object-oriented (OO) environment.</p>\n\n<p>Take the example of using <code>require_once()</code> at the top of every class as seen in many libraries:</p>\n\n<pre><code>require_once(\"includes/usergroups.php\");\nrequire_once(\"includes/permissions.php\");\nrequire_once(\"includes/revisions.php\");\nclass User{\n // User functions\n}\n</code></pre>\n\n<p>So the <code>User</code> class is designed to use all three other classes. Fair enough!</p>\n\n<p>But now what if a visitor is browsing the site and not even logged in and the framework loads: <code>require_once(\"includes/user.php\");</code> for every single request.</p>\n\n<p>It's including 1+3 <em>unnecessary</em> classes it won't ever use during that particular request. This is how bloated frameworks end up using 40 MB per request as opposed to 5 MB or less.</p>\n\n<hr>\n\n<p>The other ways it can be misused, is when a class is re-used by many others!\nSay you have about 50 classes that use <code>helper</code> functions. To make sure <code>helpers</code> are available for those classes when they are loaded, you get:</p>\n\n<pre><code>require_once(\"includes/helpers.php\");\nclass MyClass{\n // Helper::functions(); // etc..\n}\n</code></pre>\n\n<p>There is nothing wrong here per se. However if one page request happens to include 15 similar classes. You are running <code>require_once</code> 15 times, or for a nice visual:</p>\n\n<pre><code>require_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\nrequire_once(\"includes/helpers.php\");\n</code></pre>\n\n<p>The use of require_once() technically affects performance for running that function 14 times, on top of having to parse those unnecessary lines. With just 10 other highly used classes with that similar problem, it could account for 100+ lines of such rather pointless repetitive code.</p>\n\n<p>With that, it's probably worth using <code>require(\"includes/helpers.php\");</code> at the bootstrap of your application or framework, instead. But since everything is relative, <em>it all depends</em> if the weight versus usage frequency of the <code>helpers</code> class is worth saving 15-100 lines of <code>require_once()</code>. But if the probability of not using the <code>helpers</code> file on any given request is none, then <code>require</code> should definitely be in your main class instead. Having <code>require_once</code> in each class separately becomes a waste of resources.</p>\n\n<hr>\n\n<p>The <code>require_once</code> function is useful when necessary, but it shouldn't be regarded as a monolithic solution to use everywhere for loading all classes.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314/"
] |
Everything I read about better PHP coding practices keeps saying don't use `require_once` because of speed.
Why is this?
What is the proper/better way to do the same thing as `require_once`? If it matters, I'm using PHP 5.
|
`require_once` and `include_once` both require that the system keeps a log of what's already been included/required. Every `*_once` call means checking that log. So there's definitely *some* extra work being done there but enough to detriment the speed of the whole app?
... I really doubt it... Not unless you're on *really* old hardware or doing it a *lot*.
If you *are* doing thousands of `*_once`, you could do the work yourself in a lighter fashion. For simple apps, just making sure you've only included it once *should* suffice but if you're still getting redefine errors, you could something like this:
```
if (!defined('MyIncludeName')) {
require('MyIncludeName');
define('MyIncludeName', 1);
}
```
I'll personally stick with the `*_once` statements but on silly million-pass benchmark, you can see a difference between the two:
```
php hhvm
if defined 0.18587779998779 0.046600103378296
require_once 1.2219581604004 3.2908599376678
```
10-100× slower with `require_once` and it's curious that `require_once` is seemingly slower in `hhvm`. Again, this is only relevant to your code if you're running `*_once` thousands of times.
---
```
<?php // test.php
$LIMIT = 1000000;
$start = microtime(true);
for ($i=0; $i<$LIMIT; $i++)
if (!defined('include.php')) {
require('include.php');
define('include.php', 1);
}
$mid = microtime(true);
for ($i=0; $i<$LIMIT; $i++)
require_once('include.php');
$end = microtime(true);
printf("if defined\t%s\nrequire_once\t%s\n", $mid-$start, $end-$mid);
```
---
```
<?php // include.php
// do nothing.
```
|
186,345 |
<p>I have a HTML select list with quite a few (1000+) names. I have a javascript in place which will select the first matching name if someone starts typing. This matching looks at the start of the item: </p>
<pre><code>var optionsLength = dropdownlist.options.length;
for (var n=0; n < optionsLength; n++)
{
var optionText = dropdownlist.options[n].text;
if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0)
{
dropdownlist.selectedIndex = n;
return false;
}
}
</code></pre>
<p>The customer would like to have a suggest or autofilter: typing part of a name should 'find' all names containing that part. I've seen a few Google Suggest like options, most using Ajax, but I'd like a pure javascript option, since the select list is already loaded anyway. Pointers anyone?</p>
|
[
{
"answer_id": 186393,
"author": "MDCore",
"author_id": 1896,
"author_profile": "https://Stackoverflow.com/users/1896",
"pm_score": 2,
"selected": false,
"text": "<p>Change</p>\n\n<pre><code>if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>if (optionText.indexOf(dropdownlist.keypressBuffer) > 0)\n</code></pre>\n\n<p>To find <code>dropdownlist.keypressBuffer</code> anywhere in the <code>optionText</code>.</p>\n"
},
{
"answer_id": 186551,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 2,
"selected": false,
"text": "<p>I would set up a cache to hold the <code>options</code> inside my <code>select</code>. And instead of filtering <code>options</code> in the <code>select</code>, I would clear the <code>select</code>, and re-populate it with matched <code>options</code>.</p>\n\n<p>Pseudo-code galore:</p>\n\n<pre><code>onLoad:\n set cache\n\nonKeyPress:\n clear select-element\n find option-elements in cache\n put found option-elements into select-element\n</code></pre>\n\n<p>Here's a little POC I wrote, doing filtering on <code>selects</code> from what is selected in another <code>select</code>--in effect chaining a bunch of selects together.</p>\n\n<p>Perhaps it can give you a few ideas:</p>\n\n<pre><code>function selectFilter(_maps)\n{\n var map = {};\n\n\n var i = _maps.length + 1; while (i -= 1)\n {\n map = _maps[i - 1];\n\n\n (function (_selectOne, _selectTwo, _property)\n {\n var select = document.getElementById(_selectTwo);\n var options = select.options;\n var option = {};\n var cache = [];\n var output = [];\n\n\n var i = options.length + 1; while (i -= 1)\n {\n option = options[i - 1];\n\n cache.push({\n text: option.text,\n value: option.value,\n property: option.getAttribute(_property)\n });\n }\n\n\n document.getElementById(_selectOne).onchange = function ()\n {\n var selectedProperty = this\n .options[this.selectedIndex]\n .getAttribute(_property);\n var cacheEntry = {};\n var cacheEntryProperty = undefined;\n\n\n output = [];\n\n var i = cache.length + 1; while (i -= 1)\n {\n cacheEntry = cache[i - 1];\n\n cacheEntryProperty = cacheEntry.property;\n\n if (cacheEntryProperty === selectedProperty)\n {\n output.push(\"<option value=\" + cacheEntry.value + \" \"\n _property + \"=\" + cacheEntryProperty + \">\" +\n cacheEntry.text + \"</option>\");\n }\n }\n\n select.innerHTML = output.join();\n };\n }(map.selectOne, map.selectTwo, map.property));\n }\n}\n\n\n$(function ()\n{\n selectFilter([\n {selectOne: \"select1\", selectTwo: \"select2\", property: \"entityid\"},\n {selectOne: \"select2\", selectTwo: \"select3\", property: \"value\"}\n ]);\n});\n</code></pre>\n"
},
{
"answer_id": 186587,
"author": "Bazman",
"author_id": 18521,
"author_profile": "https://Stackoverflow.com/users/18521",
"pm_score": 2,
"selected": false,
"text": "<p>The YUI libraries have a library for this sort of functionality, called <a href=\"http://developer.yahoo.com/yui/autocomplete/\" rel=\"nofollow noreferrer\">AutoComplete</a>.</p>\n\n<p>The DataSource for AutoComplete can be local javascript objects, or can be easily switched to Ajax if you change your mind.</p>\n\n<p>The YUI components are pretty customizable with a fair bit of functionality.</p>\n\n<p>Edit: I'm not sure if you can get it to work with a select box as required by the question though. Might be possible.</p>\n"
},
{
"answer_id": 3098090,
"author": "vegatron",
"author_id": 284940,
"author_profile": "https://Stackoverflow.com/users/284940",
"pm_score": 2,
"selected": true,
"text": "<p>use this filter script\n<a href=\"http://www.barelyfitz.com/projects/filterlist/\" rel=\"nofollow noreferrer\">http://www.barelyfitz.com/projects/filterlist/</a></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6399/"
] |
I have a HTML select list with quite a few (1000+) names. I have a javascript in place which will select the first matching name if someone starts typing. This matching looks at the start of the item:
```
var optionsLength = dropdownlist.options.length;
for (var n=0; n < optionsLength; n++)
{
var optionText = dropdownlist.options[n].text;
if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0)
{
dropdownlist.selectedIndex = n;
return false;
}
}
```
The customer would like to have a suggest or autofilter: typing part of a name should 'find' all names containing that part. I've seen a few Google Suggest like options, most using Ajax, but I'd like a pure javascript option, since the select list is already loaded anyway. Pointers anyone?
|
use this filter script
<http://www.barelyfitz.com/projects/filterlist/>
|
186,385 |
<p>Which is the best timer approach for a C# console batch application that has to process as follows:</p>
<ol>
<li>Connect to datasources</li>
<li>process batch until timeout occurs or processing complete. "Do something with datasources"</li>
<li>stop console app gracefully.</li>
</ol>
<p>related question: <a href="https://stackoverflow.com/questions/186084/how-do-you-add-a-timer-to-a-c-console-application">How do you add a timer to a C# console application</a></p>
|
[
{
"answer_id": 186439,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>When you say \"until timeout occurs\" do you mean \"keep processing for an hour and then stop\"? If so, I'd probably just make it very explicit - work out at the start when you want to finish, then in your processing loop, do a check for whether you've reached that time or not. It's incredibly simple, easy to test etc. In terms of testability, you may want a fake clock which would let you programmatically set the time.</p>\n\n<p>EDIT: Here's some pseudocode to try to clarify:</p>\n\n<pre><code>List<DataSource> dataSources = ConnectToDataSources();\nTimeSpan timeout = GetTimeoutFromConfiguration(); // Or have it passed in!\nDateTime endTime = DateTime.UtcNow + timeout;\n\nbool finished = false;\nwhile (DateTime.UtcNow < endTime && !finished)\n{\n // This method should do a small amount of work and then return\n // whether or not it's finished everything\n finished = ProcessDataSources(dataSources);\n}\n\n// Done - return up the stack and the console app will close.\n</code></pre>\n\n<p>That's just using the built-in clock rather than a clock interface which can be mocked, etc - but it probably makes the general appropriate simpler to understand.</p>\n"
},
{
"answer_id": 186455,
"author": "Grzenio",
"author_id": 5363,
"author_profile": "https://Stackoverflow.com/users/5363",
"pm_score": 2,
"selected": false,
"text": "<p>It depends on how accurate do you want your stopping time to be. If your tasks in the batch are reasonably quick and you don't need to be very accurate, then I would try to make it single threaded:</p>\n\n<pre><code>DateTime runUntil = DataTime.Now.Add(timeout);\nforech(Task task in tasks)\n{\n if(DateTime.Now >= runUntil)\n {\n throw new MyException(\"Timeout\");\n }\n Process(task);\n}\n</code></pre>\n\n<p>Otherwise you need to go mulithreaded, which is always more difficult, because you need to figure out how to terminate your task in the middle without causing side effects. You could use the Timer from System.Timers: <a href=\"http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.71).aspx</a> or Thread.Sleep. When the time-out event occurs you can terminate the thread that does the actual processing, clean up and end the process.</p>\n"
},
{
"answer_id": 325578,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 4,
"selected": true,
"text": "<p>Sorry for this being an entire console app... but here's a complete console app that will get you started. Again, I appologize for so much code, but everyone else seems to be giving a \"oh, all you have to do is do it\" answer :)</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Threading;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static List<RunningProcess> runningProcesses = new List<RunningProcess>();\n\n static void Main(string[] args)\n {\n Console.WriteLine(\"Starting...\");\n\n for (int i = 0; i < 100; i++)\n {\n DoSomethingOrTimeOut(30);\n }\n\n bool isSomethingRunning = false;\n\n do\n {\n foreach (RunningProcess proc in runningProcesses)\n {\n // If this process is running...\n if (proc.ProcessThread.ThreadState == ThreadState.Running)\n {\n isSomethingRunning = true;\n\n // see if it needs to timeout...\n if (DateTime.Now.Subtract(proc.StartTime).TotalSeconds > proc.TimeOutInSeconds)\n {\n proc.ProcessThread.Abort();\n }\n }\n }\n }\n while (isSomethingRunning);\n\n Console.WriteLine(\"Done!\"); \n\n Console.ReadLine();\n }\n\n static void DoSomethingOrTimeOut(int timeout)\n {\n runningProcesses.Add(new RunningProcess\n {\n StartTime = DateTime.Now,\n TimeOutInSeconds = timeout,\n ProcessThread = new Thread(new ThreadStart(delegate\n {\n // do task here...\n })),\n });\n\n runningProcesses[runningProcesses.Count - 1].ProcessThread.Start();\n }\n }\n\n class RunningProcess\n {\n public int TimeOutInSeconds { get; set; }\n\n public DateTime StartTime { get; set; }\n\n public Thread ProcessThread { get; set; }\n }\n}\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535708/"
] |
Which is the best timer approach for a C# console batch application that has to process as follows:
1. Connect to datasources
2. process batch until timeout occurs or processing complete. "Do something with datasources"
3. stop console app gracefully.
related question: [How do you add a timer to a C# console application](https://stackoverflow.com/questions/186084/how-do-you-add-a-timer-to-a-c-console-application)
|
Sorry for this being an entire console app... but here's a complete console app that will get you started. Again, I appologize for so much code, but everyone else seems to be giving a "oh, all you have to do is do it" answer :)
```
using System;
using System.Collections.Generic;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static List<RunningProcess> runningProcesses = new List<RunningProcess>();
static void Main(string[] args)
{
Console.WriteLine("Starting...");
for (int i = 0; i < 100; i++)
{
DoSomethingOrTimeOut(30);
}
bool isSomethingRunning = false;
do
{
foreach (RunningProcess proc in runningProcesses)
{
// If this process is running...
if (proc.ProcessThread.ThreadState == ThreadState.Running)
{
isSomethingRunning = true;
// see if it needs to timeout...
if (DateTime.Now.Subtract(proc.StartTime).TotalSeconds > proc.TimeOutInSeconds)
{
proc.ProcessThread.Abort();
}
}
}
}
while (isSomethingRunning);
Console.WriteLine("Done!");
Console.ReadLine();
}
static void DoSomethingOrTimeOut(int timeout)
{
runningProcesses.Add(new RunningProcess
{
StartTime = DateTime.Now,
TimeOutInSeconds = timeout,
ProcessThread = new Thread(new ThreadStart(delegate
{
// do task here...
})),
});
runningProcesses[runningProcesses.Count - 1].ProcessThread.Start();
}
}
class RunningProcess
{
public int TimeOutInSeconds { get; set; }
public DateTime StartTime { get; set; }
public Thread ProcessThread { get; set; }
}
}
```
|
186,403 |
<p>When you create a procedure (or a function) in Oracle PL/SQL, you cannot specify the maximum length of the varchar2 arguments, only the datatype. For example</p>
<pre><code>create or replace procedure testproc(arg1 in varchar2) is
begin
null;
end;
</code></pre>
<p>Do you know the maximum length of a string that you can pass as the arg1 argument to this procedure in Oracle ?</p>
|
[
{
"answer_id": 186424,
"author": "Gravstar",
"author_id": 17381,
"author_profile": "https://Stackoverflow.com/users/17381",
"pm_score": 5,
"selected": true,
"text": "<p>In PL/SQL procedure it may be up to 32KB</p>\n\n<p>Futher information here:\n<a href=\"http://it.toolbox.com/blogs/oracle-guide/learn-oracle-sql-and-plsql-datatypes-strings-10804\" rel=\"noreferrer\">http://it.toolbox.com/blogs/oracle-guide/learn-oracle-sql-and-plsql-datatypes-strings-10804</a></p>\n"
},
{
"answer_id": 186436,
"author": "Aurelio Martin Massoni",
"author_id": 20037,
"author_profile": "https://Stackoverflow.com/users/20037",
"pm_score": 3,
"selected": false,
"text": "<p>I tried with testproc( lpad( ' ', 32767, ' ' ) ) and it works.</p>\n\n<p>With 32768 bytes it fails, so it's 32K - 1 bytes</p>\n"
},
{
"answer_id": 22060657,
"author": "user272735",
"author_id": 272735,
"author_profile": "https://Stackoverflow.com/users/272735",
"pm_score": 2,
"selected": false,
"text": "<p>In PL/SQL the maximum size of <code>VARCHAR2</code> datatype is <strong>32767 bytes</strong> since 10gR2 (and probably earlier but I just checked the documentation upto that release).</p>\n\n<p>The documentation references:</p>\n\n<ul>\n<li>Oracle 12cR1: <a href=\"http://docs.oracle.com/cd/E16655_01/appdev.121/e17622/datatypes.htm#LNPLS99943\" rel=\"nofollow\">PL/SQL Language Reference\n12c Release 1</a></li>\n<li>Oracle 11gR2: <a href=\"http://docs.oracle.com/cd/E11882_01/appdev.112/e17126/datatypes.htm#LNPLS99943\" rel=\"nofollow\">PL/SQL Language Reference\n11g Release 2</a></li>\n<li>Oracle 10gR2: <a href=\"http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/datatypes.htm#sthref732\" rel=\"nofollow\">PL/SQL User's Guide and Reference\n10g Release 2</a></li>\n</ul>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20037/"
] |
When you create a procedure (or a function) in Oracle PL/SQL, you cannot specify the maximum length of the varchar2 arguments, only the datatype. For example
```
create or replace procedure testproc(arg1 in varchar2) is
begin
null;
end;
```
Do you know the maximum length of a string that you can pass as the arg1 argument to this procedure in Oracle ?
|
In PL/SQL procedure it may be up to 32KB
Futher information here:
<http://it.toolbox.com/blogs/oracle-guide/learn-oracle-sql-and-plsql-datatypes-strings-10804>
|
186,405 |
<p>This is a very basic problem that's frustrating me at the moment. Let's say within a single solution, I have two projects. Let's call the first project SimpleMath. It has one header file "Add.h" which has </p>
<pre><code>int add(int i, int j)
</code></pre>
<p>and the implementation "Add.cpp" which has</p>
<pre><code>int add(int i, int j) {
return i+j;
}
</code></pre>
<p>Now let's say in a second project I want to use the add function. However, this code:</p>
<blockquote>
<p><strong>#include "..\SimpleMath\Add.h"</strong></p>
</blockquote>
<pre><code>int main() {
add(1, 2);
}
</code></pre>
<p>results in "unresolved external symbol". How do I get the second program to "know" about the actual implementation in the .cpp file. As a side note all code is fictional this is not how I actually program.</p>
|
[
{
"answer_id": 186412,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 2,
"selected": false,
"text": "<p>You either have to make Add.cpp part of a library and include it in both projects. or you have to add Add.cpp to your second project too.</p>\n\n<p>Edit: to make SimpleMath a library go into the project settings on General and change the Configuration Type to Static Lib.</p>\n\n<p>Then go into your solution settings, click on Project Dependencies, then select your second project in the drop down list, and put a check mark next to SimpleMath. That will automatically link SimpleMath to your second project, and will also make sure that any changes to SimpleMath will be rebuilt when you rebuild your second project.</p>\n"
},
{
"answer_id": 186415,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "<p>SimpleMath would need to be defined as a library file (.LIB) in it's project properties I'm assuming that this is an unmanaged (non-.Net) C++. Then include SimpleMath.lib in the other project.</p>\n"
},
{
"answer_id": 186430,
"author": "korona",
"author_id": 25731,
"author_profile": "https://Stackoverflow.com/users/25731",
"pm_score": 3,
"selected": false,
"text": "<p>The reason for the error you're getting is that by including the header file you're telling the compiler that there is a symbol</p>\n\n<pre><code>int add (int, int)\n</code></pre>\n\n<p>That will be present during linkage, but you haven't actually included that symbol (the code for the function) in your project. A quick way to resolve the issue is to simply add Add.cpp to both projects. But the \"nice\" solution would probably be to make SimpleMath into a library instead of an application by changing the project type in the project properties.</p>\n\n<p>And by the way, you probably want some sort of mechanism in place to prevent multiple inclusion of that header file in place. I usually use <code>#pragma once</code> which should be fine if you stick with Visual C++ but that might not be entirely portable so if you want portability, go with the more traditional approach of wrapping the header file in an <code>#ifndef</code>-block, as such:</p>\n\n<pre><code>#ifndef __ADD_H\n#define __ADD_H\n\nint add (int i, int j);\n\n#endif\n</code></pre>\n\n<p>Good luck.</p>\n"
},
{
"answer_id": 1207013,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>If you're trying to link C libraries into C++ projects, you'll need to do something like </p>\n\n<pre><code>extern \"C\" {\n #include \"..\\SimpleMath\\Add.h\"\n}\n</code></pre>\n\n<p>as C and C++ use different symbol names.</p>\n"
},
{
"answer_id": 8472387,
"author": "sprite",
"author_id": 145211,
"author_profile": "https://Stackoverflow.com/users/145211",
"pm_score": 0,
"selected": false,
"text": "<p>I just had this problem <strong>within the same project</strong>... After looking closely at my code I notices that the code trying to call the function was <strong>using an interface</strong> (through a pure virtual method call = 0). However, <strong>I forgot to add the \"virtual\" word</strong> in the interface class and the implementation class. Once I added the \"virtual\" the problem was solved.</p>\n"
},
{
"answer_id": 40830367,
"author": "kungfooman",
"author_id": 1952626,
"author_profile": "https://Stackoverflow.com/users/1952626",
"pm_score": 1,
"selected": false,
"text": "<p>Just had it in the same project aswell, turns out I had two filters and named two .cpp-files <strong>the same name</strong>. So Visual Studio just overwrote one .obj while compiling the other. Resulting into missing functions in the first .obj. Lesson: never name .cpp-files the same, even in different folders/filters.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23120/"
] |
This is a very basic problem that's frustrating me at the moment. Let's say within a single solution, I have two projects. Let's call the first project SimpleMath. It has one header file "Add.h" which has
```
int add(int i, int j)
```
and the implementation "Add.cpp" which has
```
int add(int i, int j) {
return i+j;
}
```
Now let's say in a second project I want to use the add function. However, this code:
>
> **#include "..\SimpleMath\Add.h"**
>
>
>
```
int main() {
add(1, 2);
}
```
results in "unresolved external symbol". How do I get the second program to "know" about the actual implementation in the .cpp file. As a side note all code is fictional this is not how I actually program.
|
The reason for the error you're getting is that by including the header file you're telling the compiler that there is a symbol
```
int add (int, int)
```
That will be present during linkage, but you haven't actually included that symbol (the code for the function) in your project. A quick way to resolve the issue is to simply add Add.cpp to both projects. But the "nice" solution would probably be to make SimpleMath into a library instead of an application by changing the project type in the project properties.
And by the way, you probably want some sort of mechanism in place to prevent multiple inclusion of that header file in place. I usually use `#pragma once` which should be fine if you stick with Visual C++ but that might not be entirely portable so if you want portability, go with the more traditional approach of wrapping the header file in an `#ifndef`-block, as such:
```
#ifndef __ADD_H
#define __ADD_H
int add (int i, int j);
#endif
```
Good luck.
|
186,413 |
<p>I need to add a <code>xml:lang</code> attribute on the root xml node in the outbound document from BizTalk.</p>
<p>This is a fixed value, so it may be set in the schema or something.</p>
<p>This is what I want to get out:</p>
<pre><code><Catalog xml:lang="NB-NO">
...
</Catalog>
</code></pre>
<p>I've tried to define the attribute "xml:lang", but it doesn't allow me to use ":" in the schema. </p>
<p>This is the error message I get:</p>
<blockquote>
<p>Invalid 'name' attribute value
'xml:lang': The ':' character,
hexadecimal value 0x3A, at position 3
within the name, cannot be included in
a name.</p>
</blockquote>
<p>Is there another way to insert a ':' as part of the attribute name in BizTalk?</p>
<p>Can anyone tell me how to do this?</p>
<p>I'm using BizTalk 2006 and no orchestration.</p>
|
[
{
"answer_id": 186435,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "<p>Try to add the xml namespace declaration to the schema </p>\n\n<pre><code>xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" \n</code></pre>\n\n<p>Beware that this addition will be removed when the schema file is recreated.</p>\n"
},
{
"answer_id": 8806322,
"author": "DanMan",
"author_id": 428241,
"author_profile": "https://Stackoverflow.com/users/428241",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of</p>\n\n<pre><code><xs:attribute name=\"xml:lang\" />\n</code></pre>\n\n<p>try</p>\n\n<pre><code><xs:attribute ref=\"xml:lang\" />\n</code></pre>\n\n<p>instead. At least PhpStorm stopped complaining about it.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I need to add a `xml:lang` attribute on the root xml node in the outbound document from BizTalk.
This is a fixed value, so it may be set in the schema or something.
This is what I want to get out:
```
<Catalog xml:lang="NB-NO">
...
</Catalog>
```
I've tried to define the attribute "xml:lang", but it doesn't allow me to use ":" in the schema.
This is the error message I get:
>
> Invalid 'name' attribute value
> 'xml:lang': The ':' character,
> hexadecimal value 0x3A, at position 3
> within the name, cannot be included in
> a name.
>
>
>
Is there another way to insert a ':' as part of the attribute name in BizTalk?
Can anyone tell me how to do this?
I'm using BizTalk 2006 and no orchestration.
|
Try to add the xml namespace declaration to the schema
```
xmlns:xml="http://www.w3.org/XML/1998/namespace"
```
Beware that this addition will be removed when the schema file is recreated.
|
186,431 |
<p>Given a week number, e.g. <code>date -u +%W</code>, how do you calculate the days in that week starting from Monday?</p>
<p>Example rfc-3339 output for week 40:</p>
<pre><code>2008-10-06
2008-10-07
2008-10-08
2008-10-09
2008-10-10
2008-10-11
2008-10-12
</code></pre>
|
[
{
"answer_id": 186478,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 7,
"selected": true,
"text": "<p><strong>PHP</strong></p>\n\n<pre><code>$week_number = 40;\n$year = 2008;\nfor($day=1; $day<=7; $day++)\n{\n echo date('m/d/Y', strtotime($year.\"W\".$week_number.$day)).\"\\n\";\n}\n</code></pre>\n\n<p><hr>\nBelow post was because I was an idiot who didn't read the question properly, but will get the dates in a week starting from Monday, given the date, not the week number..</p>\n\n<p><strong>In PHP</strong>, adapted from <a href=\"http://ie2.php.net/manual/en/function.date.php#85258\" rel=\"noreferrer\">this post</a> on the <a href=\"http://ie2.php.net/manual/en/function.date.php\" rel=\"noreferrer\">PHP date manual page</a>:</p>\n\n<pre><code>function week_from_monday($date) {\n // Assuming $date is in format DD-MM-YYYY\n list($day, $month, $year) = explode(\"-\", $_REQUEST[\"date\"]);\n\n // Get the weekday of the given date\n $wkday = date('l',mktime('0','0','0', $month, $day, $year));\n\n switch($wkday) {\n case 'Monday': $numDaysToMon = 0; break;\n case 'Tuesday': $numDaysToMon = 1; break;\n case 'Wednesday': $numDaysToMon = 2; break;\n case 'Thursday': $numDaysToMon = 3; break;\n case 'Friday': $numDaysToMon = 4; break;\n case 'Saturday': $numDaysToMon = 5; break;\n case 'Sunday': $numDaysToMon = 6; break; \n }\n\n // Timestamp of the monday for that week\n $monday = mktime('0','0','0', $month, $day-$numDaysToMon, $year);\n\n $seconds_in_a_day = 86400;\n\n // Get date for 7 days from Monday (inclusive)\n for($i=0; $i<7; $i++)\n {\n $dates[$i] = date('Y-m-d',$monday+($seconds_in_a_day*$i));\n }\n\n return $dates;\n}\n</code></pre>\n\n<p>Output from <code>week_from_monday('07-10-2008')</code> gives:</p>\n\n<pre><code>Array\n(\n [0] => 2008-10-06\n [1] => 2008-10-07\n [2] => 2008-10-08\n [3] => 2008-10-09\n [4] => 2008-10-10\n [5] => 2008-10-11\n [6] => 2008-10-12\n)\n</code></pre>\n"
},
{
"answer_id": 186484,
"author": "Martin Liesén",
"author_id": 20715,
"author_profile": "https://Stackoverflow.com/users/20715",
"pm_score": 2,
"selected": false,
"text": "<p>This calculation varies largely depending on where you live. For example, in Europe we start the week with a Monday, in US Sunday is the first day of the week. In UK week 1 is on Jan 1, others countries start week 1 on the week containing the first Thursday of the year.</p>\n\n<p>You can find more general information at <a href=\"http://en.wikipedia.org/wiki/Week#Week_number\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Week#Week_number</a></p>\n"
},
{
"answer_id": 189047,
"author": "Shane",
"author_id": 1259,
"author_profile": "https://Stackoverflow.com/users/1259",
"pm_score": 3,
"selected": false,
"text": "<p>If you've got Zend Framework you can use the Zend_Date class to do this:</p>\n\n<pre><code>require_once 'Zend/Date.php';\n\n$date = new Zend_Date();\n$date->setYear(2008)\n ->setWeek(40)\n ->setWeekDay(1);\n\n$weekDates = array();\n\nfor ($day = 1; $day <= 7; $day++) {\n if ($day == 1) {\n // we're already at day 1\n }\n else {\n // get the next day in the week\n $date->addDay(1);\n }\n\n $weekDates[] = date('Y-m-d', $date->getTimestamp());\n}\n\necho '<pre>';\nprint_r($weekDates);\necho '</pre>';\n</code></pre>\n"
},
{
"answer_id": 534495,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>This function will give the timestamps of days of the week in which $date is found. If $date isn't given, it assumes \"now.\" If you prefer readable dates to timestamps, pass a date format into the second parameter. If you don't start your week on Monday (lucky), pass in a different day for the third parameter.</p>\n\n<pre><code>function week_dates($date = null, $format = null, $start = 'monday') {\n // is date given? if not, use current time...\n if(is_null($date)) $date = 'now';\n\n // get the timestamp of the day that started $date's week...\n $weekstart = strtotime('last '.$start, strtotime($date));\n\n // add 86400 to the timestamp for each day that follows it...\n for($i = 0; $i < 7; $i++) {\n $day = $weekstart + (86400 * $i);\n if(is_null($format)) $dates[$i] = $day;\n else $dates[$i] = date($format, $day);\n }\n\n return $dates;\n}\n</code></pre>\n\n<p>So <strong>week_dates()</strong> should return something like...</p>\n\n<pre><code>Array ( \n [0] => 1234155600 \n [1] => 1234242000 \n [2] => 1234328400 \n [3] => 1234414800 \n [4] => 1234501200\n [5] => 1234587600\n [6] => 1234674000\n)\n</code></pre>\n"
},
{
"answer_id": 639048,
"author": "Yashvit",
"author_id": 77241,
"author_profile": "https://Stackoverflow.com/users/77241",
"pm_score": 0,
"selected": false,
"text": "<p>I found a problem with this solution. \nI had to zero-pad the week number or else it was breaking.</p>\n\n<p>My solution looks like this now:</p>\n\n<pre><code>$week_number = 40;\n$year = 2008;\nfor($day=1; $day<=7; $day++)\n{\n echo date('m/d/Y', strtotime($year.\"W\".str_pad($week_number,2,'0',STR_PAD_LEFT).$day)).\"\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 1184954,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>For those looking for the days of the week given the week number (1-52) \n<strong>Starting from a sunday</strong> then here is my little work around. Takes into account checking the week is in the right range and pads the values 1-9 to keep it all working.</p>\n\n<pre><code>$week = 2; $year = 2009;\n\n$week = (($week >= 1) AND ($week <= 52))?($week-1):(1);\n\n$dayrange = array(7,1,2,3,4,5,6);\n\nfor($count=0; $count<=6; $count++) {\n $week = ($count == 1)?($week + 1): ($week);\n $week = str_pad($week,2,'0',STR_PAD_LEFT);\n echo date('d m Y', strtotime($year.\"W\".$week.($dayrange[$count]))); }\n</code></pre>\n"
},
{
"answer_id": 1974330,
"author": "Nicolas",
"author_id": 240148,
"author_profile": "https://Stackoverflow.com/users/240148",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$week_number = 40;\n$year = 2008;\n\nfor($day=1; $day<=7; $day++)\n{\n echo date('m/d/Y', strtotime($year.\"W\".$week_number.$day)).\"\\n\";\n}\n</code></pre>\n\n<p>This will fail if <code>$week_number</code> is less than 10. </p>\n\n<pre><code>//============Try this================//\n\n$week_number = 40;\n$year = 2008;\n\nif($week_number < 10){\n $week_number = \"0\".$week_number;\n}\n\nfor($day=1; $day<=7; $day++)\n{\n echo date('m/d/Y', strtotime($year.\"W\".$week_number.$day)).\"\\n\";\n}\n\n//==============================//\n</code></pre>\n"
},
{
"answer_id": 12252944,
"author": "codepuppy",
"author_id": 1148523,
"author_profile": "https://Stackoverflow.com/users/1148523",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same question only using strftime instead of date as my starting point i.e. having derived a week number from strftime using %W I wanted to know the date range for that week - Monday to Sunday (or indeed any starting day). A review of several similar posts and in particular trying out a couple of the above approaches didn't get me to the solution I wanted. Of course I may have misunderstood something but I couldn't get what I wanted.</p>\n\n<p>I would therefore like to share my solution. </p>\n\n<p>My first thought was that given the description of strftime %W is:</p>\n\n<blockquote>\n <p>week number of the current year, starting with the first Monday as\n the first day of the first week</p>\n</blockquote>\n\n<p>if I established what the first Monday of each year is I could calculate an array of date ranges with an index equal to the value of %W. Thereafter I could call the function using strftime.</p>\n\n<p>So here goes:</p>\n\n<p>The Function:</p>\n\n<pre><code><?php\n\n/*\n * function to establish scope of week given a week of the year value returned from strftime %W\n */\n\n// note strftime %W reports 1/1/YYYY as wk 00 unless 1/1/YYYY is a monday when it reports wk 01\n// note strtotime Monday [last, this, next] week - runs sun - sat\n\nfunction date_Range_For_Week($W,$Y){\n\n// where $W = %W returned from strftime\n// $Y = %Y returned from strftime\n\n // establish 1st day of 1/1/YYYY\n\n $first_Day_Of_Year = mktime(0,0,0,1,1,$Y);\n\n // establish the first monday of year after 1/1/YYYY \n\n $first_Monday_Of_Year = strtotime(\"Monday this week\",(mktime(0,0,0,1,1,$Y))); \n\n // Check for week 00 advance first monday if found\n // We could use strtotime \"Monday next week\" or add 604800 seconds to find next monday\n // I have decided to avoid any potential strtotime overhead and do the arthimetic\n\n if (strftime(\"%W\",$first_Monday_Of_Year) != \"01\"){\n $first_Monday_Of_Year += (60 * 60 * 24 * 7);\n }\n\n // create array to ranges for the year. Note 52 wks is the norm but it is possible to have 54 weeks\n // in a given yr therefore allow for this in array index\n\n $week_Start = array();\n $week_End = array(); \n\n for($i=0;$i<=53;$i++){\n\n if ($i == 0){ \n if ($first_Day_Of_Year != $first_Monday_Of_Year){\n $week_Start[$i] = $first_Day_Of_Year;\n $week_End[$i] = $first_Monday_Of_Year - (60 * 60 * 24 * 1);\n } else {\n // %W returns no week 00\n $week_Start[$i] = 0;\n $week_End[$i] = 0; \n }\n $current_Monday = $first_Monday_Of_Year;\n } else {\n $week_Start[$i] = $current_Monday;\n $week_End[$i] = $current_Monday + (60 * 60 * 24 * 6);\n // find next monday\n $current_Monday += (60 * 60 * 24 * 7);\n // test for end of year\n if (strftime(\"%W\",$current_Monday) == \"01\"){ $i = 999; };\n }\n };\n\n $result = array(\"start\" => strftime(\"%a on %d, %b, %Y\", $week_Start[$W]), \"end\" => strftime(\"%a on %d, %b, %Y\", $week_End[$W]));\n\n return $result;\n\n } \n\n?>\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>// usage example\n\n//assume we wish to find the date range of a week for a given date July 12th 2011\n\n$Y = strftime(\"%Y\",mktime(0,0,0,7,12,2011));\n$W = strftime(\"%W\",mktime(0,0,0,7,12,2011));\n\n// use dynamic array variable to check if we have range if so get result if not run function\n\n$date_Range = date_Range . \"$Y\";\n\nisset(${$date_Range}) ? null : ${$date_Range} = date_Range_For_Week($W, $Y);\n\necho \"Date sought: \" . strftime(\" was %a on %b %d, %Y, %X time zone: %Z\",mktime(0,0,0,7,12,2011)) . \"<br/>\";\necho \"start of week \" . $W . \" is \" . ${$date_Range}[\"start\"] . \"<br/>\";\necho \"end of week \" . $W . \" is \" . ${$date_Range}[\"end\"];\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>> Date sought: was Tue on Jul 12, 2011, 00:00:00 time zone: GMT Daylight\n> Time start of week 28 is Mon on 11, Jul, 2011 end of week 28 is Sun on\n> 17, Jul, 2011\n</code></pre>\n\n<p>I have tested this over several years including 2018 which is the next year when 1/1/2018 = Monday. Thus far seems to deliver the correct date range.</p>\n\n<p>So I hope that this helps.</p>\n\n<p>Regards</p>\n"
},
{
"answer_id": 17065451,
"author": "vascowhite",
"author_id": 212940,
"author_profile": "https://Stackoverflow.com/users/212940",
"pm_score": 3,
"selected": false,
"text": "<p>Since this question and the accepted answer were posted the <a href=\"http://php.net/datetime\" rel=\"noreferrer\">DateTime</a> classes make this much simpler to do:-</p>\n\n<pre><code>function daysInWeek($weekNum)\n{\n $result = array();\n $datetime = new DateTime('00:00:00');\n $datetime->setISODate((int)$datetime->format('o'), $weekNum, 1);\n $interval = new DateInterval('P1D');\n $week = new DatePeriod($datetime, $interval, 6);\n\n foreach($week as $day){\n $result[] = $day->format('D d m Y H:i:s');\n }\n return $result;\n}\n\nvar_dump(daysInWeek(24));\n</code></pre>\n\n<p>This has the added advantage of taking care of leap years etc..</p>\n\n<p><a href=\"http://3v4l.org/HqSEv\" rel=\"noreferrer\">See it working</a>. Including the difficult weeks 1 and 53.</p>\n"
},
{
"answer_id": 21475362,
"author": "joan16v",
"author_id": 1398876,
"author_profile": "https://Stackoverflow.com/users/1398876",
"pm_score": 0,
"selected": false,
"text": "<p>Another solution:</p>\n\n<pre><code>//$date Date in week\n//$start Week start (out)\n//$end Week end (out)\n\nfunction week_bounds($date, &$start, &$end) {\n $date = strtotime($date);\n $start = $date;\n while( date('w', $start)>1 ) {\n $start -= 86400;\n }\n $end = date('Y-m-d', $start + (6*86400) );\n $start = date('Y-m-d', $start);\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>week_bounds(\"2014/02/10\", $start, $end);\necho $start.\"<br>\".$end;\n</code></pre>\n\n<p>Out:</p>\n\n<pre><code>2014-02-10\n2014-02-16\n</code></pre>\n"
},
{
"answer_id": 21878886,
"author": "Dhananjay",
"author_id": 3327738,
"author_profile": "https://Stackoverflow.com/users/3327738",
"pm_score": -1,
"selected": false,
"text": "<pre><code> <?php\n $iWeeksAgo = 5;// need weeks ago\n $sWeekDayStartOn = 0;// 0 - Sunday, 1 - Monday, 2 - Tuesday\n $aWeeksDetails = getWeekDetails($iWeeksAgo, $sWeekDayStartOn);\n\n print_r($aWeeksDetails);\n die('end of line of getWeekDetails ');\n\n function getWeekDetails($iWeeksAgo, $sWeekDayStartOn){\n $date = new DateTime();\n $sCurrentDate = $date->format('W, Y-m-d, w');\n #echo 'Current Date (Week of the year, YYYY-MM-DD, day of week ): ' . $sCurrentDate . \"\\n\";\n\n $iWeekOfTheYear = $date->format('W');// Week of the Year i.e. 19-Feb-2014 = 08\n $iDayOfWeek = $date->format('w');// day of week for the current month i.e. 19-Feb-2014 = 4\n $iDayOfMonth = $date->format('d'); // date of the month i.e. 19-Feb-2014 = 19\n\n $iNoDaysAdd = 6;// number of days adding to get last date of the week i.e. 19-Feb-2014 + 6 days = 25-Feb-2014\n\n $date->sub(new DateInterval(\"P{$iDayOfWeek}D\"));// getting start date of the week\n $sStartDateOfWeek = $date->format('Y-m-d');// getting start date of the week\n\n $date->add(new DateInterval(\"P{$iNoDaysAdd}D\"));// getting end date of the week\n $sEndDateOfWeek = $date->format('Y-m-d');// getting end date of the week\n\n $iWeekOfTheYearWeek = (string) $date->format('YW');//week of the year\n $iWeekOfTheYearWeekWithPeriod = (string) $date->format('Y-W');//week of the year with year\n\n //To check uncomment\n #echo \"Start Date / End Date of Current week($iWeekOfTheYearWeek), week with - ($iWeekOfTheYearWeekWithPeriod) : \" . $sStartDateOfWeek . ',' . $sEndDateOfWeek . \"\\n\";\n\n $iDaysAgo = ($iWeeksAgo*7) + $iNoDaysAdd + $sWeekDayStartOn;// getting 4 weeks ago i.e. no. of days to substract\n\n $date->sub(new DateInterval(\"P{$iDaysAgo}D\"));// getting 4 weeks ago i.e. no. of days to substract\n $sStartDateOfWeekAgo = $date->format('Y-m-d');// getting 4 weeks ago start date i.e. 19-Jan-2014\n\n $date->add(new DateInterval(\"P{$iNoDaysAdd}D\")); // getting 4 weeks ago end date i.e. 25-Jan-2014\n $sEndDateOfWeekAgo = $date->format('Y-m-d');// getting 4 weeks ago start date i.e. 25-Jan-2014\n\n $iProccessedWeekAgoOfTheYear = (string) $date->format('YW');//ago week of the year\n $iProccessedWeekOfTheYearWeekAgo = (string) $date->format('YW');//ago week of the year with year\n $iProccessedWeekOfTheYearWeekWithPeriodAgo = (string) $date->format('Y-W');//ago week of the year with year\n\n //To check uncomment\n #echo \"Start Date / End Date of week($iProccessedWeekOfTheYearWeekAgo), week with - ($iProccessedWeekOfTheYearWeekWithPeriodAgo) ago: \" . $sStartDateOfWeekAgo . ',' . $sEndDateOfWeekAgo . \"\\n\";\n\n $aWeeksDetails = array ('weeksago' => $iWeeksAgo, 'currentweek' => $iWeekOfTheYear, 'currentdate' => $sCurrentDate, 'startdateofcurrentweek' => $sStartDateOfWeek, 'enddateofcurrentweek' => $sEndDateOfWeek,\n 'weekagoyearweek' => $iProccessedWeekAgoOfTheYear, 'startdateofagoweek' => $sStartDateOfWeekAgo, 'enddateofagoweek' => $sEndDateOfWeekAgo);\n\n return $aWeeksDetails;\n }\n?> \n</code></pre>\n"
},
{
"answer_id": 34639314,
"author": "Miton Leon",
"author_id": 3087281,
"author_profile": "https://Stackoverflow.com/users/3087281",
"pm_score": 1,
"selected": false,
"text": "<p>Another code hehe:</p>\n\n<pre><code>public function getAllowedDays($year, $week) {\n $weekDaysArray = array();\n $dto = new \\DateTime();\n $dto->setISODate($year, $week);\n\n for($i = 0; $i < 7; $i++) {\n array_push($weekDaysArray, $dto->format('Y-m-d'));\n $dto->modify(\"+1 days\");\n }\n\n return $weekDaysArray;\n}\n</code></pre>\n"
},
{
"answer_id": 40639239,
"author": "Peter Breuls",
"author_id": 7169107,
"author_profile": "https://Stackoverflow.com/users/7169107",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$year = 2016; //enter the year\n$wk_number = 46; //enter the weak nr\n\n$start = new DateTime($year.'-01-01 00:00:00');\n$end = new DateTime($year.'-12-31 00:00:00');\n\n$start_date = $start->format('Y-m-d H:i:s');\n\n$output[0]= $start; \n$end = $end->format('U'); \n$x = 1;\n\n//create array full of data objects\nfor($i=0;;$i++){\n if($i == intval(date('z',$end)) || $i === 365){\n break;\n }\n $a = new DateTime($start_date);\n $b = $a->modify('+1 day');\n $output[$x]= $a; \n $start_date = $b->format('Y-m-d H:i:s');\n $x++;\n} \n\n//create a object to use\nfor($i=0;$i<count($output);$i++){\n if(intval ($output[$i]->format('W')) === $wk_number){\n $output_[$output[$i]->format('N')] = $output[$i];\n }\n}\n\n$dayNumberOfWeek = 1; //enter the desired day in 1 = Mon -> 7 = Sun\n\necho '<pre>';\nprint_r($output_[$dayNumberOfWeek]->format('Y-m-d'));\necho '</pre>';\n</code></pre>\n\n<p>use as date() object from php\n<a href=\"http://php.net/manual/en/function.date.php\" rel=\"nofollow noreferrer\">date php</a> </p>\n"
},
{
"answer_id": 66026764,
"author": "oleviolin",
"author_id": 5591121,
"author_profile": "https://Stackoverflow.com/users/5591121",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Period based on week numbers and days</strong></p>\n<p>Some countries (like Scandinavian countries and Germany) use week numbers, as a practical way of booking holidays, meetings etc. This function can based on week number start day and period length in days deliver a text message regarding the period.</p>\n<pre><code>function MakePeriod($year,$Week,$StartDay,$NumberOfDays, $lan='DK'){\n //Please note that start dates in january of week 53 must be entered as "the year before"\n switch($lan){\n case "NO":\n $WeekDays=['mandag','tirsdag','onsdag','torsdag','fredag','lørdag','søndag'];\n $the=" den ";\n $weekName="Uke ";\n $dateformat="j/n Y";\n break; \n case "DK":\n $WeekDays=['mandag','tirsdag','onsdag','torsdag','fredag','lørdag','søndag'];\n $the=" den ";\n $weekName="Uge ";\n $dateformat="j/n Y";\n break;\n case "SV":\n $WeekDays=['måndag','tisdag','onsdag','torsdag','fredag','lördag','söndag'];\n $the=" den ";\n $weekName="Vecka ";\n $dateformat="j/n Y";\n break;\n case "GE":\n $WeekDays=['Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag','Sonntag'];\n $the=" die ";\n $weekName="Woche ";\n $dateformat="j/n Y";\n break;\n case "EN":\n case "US": \n $WeekDays=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];\n $the=" the ";\n $weekName="Week ";\n $dateformat="n/j/Y";\n break; \n } \n $EndDay= (($StartDay-1+$NumberOfDays) % 7)+1;\n $ExtraDays= $NumberOfDays % 7;\n $FirstWeek=$Week;\n $LastWeek=$Week; \n $NumberOfWeeks=floor($NumberOfDays / 7) ;\n $LastWeek=$Week+$NumberOfWeeks;\n\n if($StartDay+$ExtraDays>7){\n $LastWeek++;\n } \n\n if($FirstWeek<10) $FirstWeek='0'.$FirstWeek;\n if($LastWeek<10) $LastWeek='0'.$LastWeek;\n\n \n $date1 = date( $dateformat, strtotime($year."W".$FirstWeek.$StartDay) ); // First day of week\n\n $date2 = date( $dateformat, strtotime($year."W".$LastWeek.$EndDay) ); // Last day of week\n\n if($LastWeek>53){\n $LastWeek=$LastWeek-53;\n $year++;\n if($LastWeek<10) $LastWeek='0'.$LastWeek;\n $date2 = date( $dateformat, strtotime($year."W".$LastWeek.$EndDay) );\n }\n $EndDayName=$WeekDays[$EndDay-1];\n $StartDayName=$WeekDays[$StartDay-1];\n $retval= " $weekName $Week $StartDayName $the $date1 - $EndDayName $the $date2 ";\n return $retval; \n \n}\n</code></pre>\n<p>Test:</p>\n<pre><code>$Year=2021;\n$Week=22; \n$StartDay=4; \n$NumberOfDays=3;\n$Period=MakePeriod($Year,$Week,$StartDay,$NumberOfDays,"DK");\necho $Period;\n</code></pre>\n<p>Uge 22 torsdag den 3/6 2021 - søndag den 6/6 2021</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4534/"
] |
Given a week number, e.g. `date -u +%W`, how do you calculate the days in that week starting from Monday?
Example rfc-3339 output for week 40:
```
2008-10-06
2008-10-07
2008-10-08
2008-10-09
2008-10-10
2008-10-11
2008-10-12
```
|
**PHP**
```
$week_number = 40;
$year = 2008;
for($day=1; $day<=7; $day++)
{
echo date('m/d/Y', strtotime($year."W".$week_number.$day))."\n";
}
```
---
Below post was because I was an idiot who didn't read the question properly, but will get the dates in a week starting from Monday, given the date, not the week number..
**In PHP**, adapted from [this post](http://ie2.php.net/manual/en/function.date.php#85258) on the [PHP date manual page](http://ie2.php.net/manual/en/function.date.php):
```
function week_from_monday($date) {
// Assuming $date is in format DD-MM-YYYY
list($day, $month, $year) = explode("-", $_REQUEST["date"]);
// Get the weekday of the given date
$wkday = date('l',mktime('0','0','0', $month, $day, $year));
switch($wkday) {
case 'Monday': $numDaysToMon = 0; break;
case 'Tuesday': $numDaysToMon = 1; break;
case 'Wednesday': $numDaysToMon = 2; break;
case 'Thursday': $numDaysToMon = 3; break;
case 'Friday': $numDaysToMon = 4; break;
case 'Saturday': $numDaysToMon = 5; break;
case 'Sunday': $numDaysToMon = 6; break;
}
// Timestamp of the monday for that week
$monday = mktime('0','0','0', $month, $day-$numDaysToMon, $year);
$seconds_in_a_day = 86400;
// Get date for 7 days from Monday (inclusive)
for($i=0; $i<7; $i++)
{
$dates[$i] = date('Y-m-d',$monday+($seconds_in_a_day*$i));
}
return $dates;
}
```
Output from `week_from_monday('07-10-2008')` gives:
```
Array
(
[0] => 2008-10-06
[1] => 2008-10-07
[2] => 2008-10-08
[3] => 2008-10-09
[4] => 2008-10-10
[5] => 2008-10-11
[6] => 2008-10-12
)
```
|
186,443 |
<p>At the moment I pull data from remote MS SQL Server databases using custom-built JDBC connectors. This works fine but doesn't feel like the way to do it.</p>
<p>I feel I should be able to put a JDBC connection string into tnsnames on the server and have it "just work". I've looked around a little for this functionality but it doesn't seem to be there.</p>
<p>In this way I could connect to pretty much any database just using a database link.</p>
<p>Have I missed something?</p>
<hr>
<p>It looks like the two options are Generic Connectivity and Oracle Gateways but I'm surprised that's all there is. Generic Connectivity comes with the database license and Oracle Gateways is an add-on. For Generic Connectivity, if you're running on Linux (like me) you need to get hold of an ODBC driver as it isn't bundled with the database.</p>
<p>However... with Oracle being such keen Java fans, and with a JVM built-in to the database I'd have thought a JDBC-based linking technology would have been a no-brainer. It seems a natural extension to have a JDBC connection string in TNSNAMES and everything would "just work".</p>
<p>Anyone any ideas why this isn't available?</p>
|
[
{
"answer_id": 186811,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"http://www.oracle.com/pls/db102/search?remark=quick_search&word=Generic+Connectivity&tab_id=&format=ranked\" rel=\"nofollow noreferrer\">Generic Connectivity</a> is what you are after, it will let you setup a remote database link against MS SQL Server, so you can do queries like</p>\n\n<pre><code>select * from mytable@my_ms_sql_server;\n</code></pre>\n\n<p>I've only used it in Oracle 9i against mysql, and found, that in our cases, it didn't work very well, as it ended up using up MASSIVE amounts of ram, we still use it, but now just use it for syncing to a local table rather than doing 'live' queries against it. BUT, it might be completely different against MS SQL Server, and in 10g/11g</p>\n"
},
{
"answer_id": 187637,
"author": "DCookie",
"author_id": 8670,
"author_profile": "https://Stackoverflow.com/users/8670",
"pm_score": 2,
"selected": false,
"text": "<p>Another product to look at is Oracle Gateways.</p>\n\n<p>Have a look at:</p>\n\n<p><a href=\"http://www.oracle.com/technology/documentation/gateways10g.html\" rel=\"nofollow noreferrer\">http://www.oracle.com/technology/documentation/gateways10g.html</a></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4003/"
] |
At the moment I pull data from remote MS SQL Server databases using custom-built JDBC connectors. This works fine but doesn't feel like the way to do it.
I feel I should be able to put a JDBC connection string into tnsnames on the server and have it "just work". I've looked around a little for this functionality but it doesn't seem to be there.
In this way I could connect to pretty much any database just using a database link.
Have I missed something?
---
It looks like the two options are Generic Connectivity and Oracle Gateways but I'm surprised that's all there is. Generic Connectivity comes with the database license and Oracle Gateways is an add-on. For Generic Connectivity, if you're running on Linux (like me) you need to get hold of an ODBC driver as it isn't bundled with the database.
However... with Oracle being such keen Java fans, and with a JVM built-in to the database I'd have thought a JDBC-based linking technology would have been a no-brainer. It seems a natural extension to have a JDBC connection string in TNSNAMES and everything would "just work".
Anyone any ideas why this isn't available?
|
[Generic Connectivity](http://www.oracle.com/pls/db102/search?remark=quick_search&word=Generic+Connectivity&tab_id=&format=ranked) is what you are after, it will let you setup a remote database link against MS SQL Server, so you can do queries like
```
select * from mytable@my_ms_sql_server;
```
I've only used it in Oracle 9i against mysql, and found, that in our cases, it didn't work very well, as it ended up using up MASSIVE amounts of ram, we still use it, but now just use it for syncing to a local table rather than doing 'live' queries against it. BUT, it might be completely different against MS SQL Server, and in 10g/11g
|
186,467 |
<p>We have a web application that passes parameters in the url along the lines of this:</p>
<pre><code>www.example.com/ViewCustomer?customer=3945
</code></pre>
<p>Reasonably often, we will see attempts to access just:</p>
<pre><code>www.example.com/ViewCustomer
</code></pre>
<p>Or system logs this as invalid and sends back a "An error has occurred, contact support with trace number XXX" type page.</p>
<p>Our logs include the session information so it is actually someone logged in with a valid session which means they have successfully signed in with a username and password.</p>
<p>It could be they just typed that into the address bar, but it seems to occur too often for that. Another alternative is that we have a bug in our code, but we've investigated and sometimes there is only one spot and it is clearly ok. We've never had a user complain about something not working and resulting in this. Everything is under SSL.</p>
<p>Has anyone else experienced this? Do some browsers send these sorts of dodgy requests occasionally?</p>
<p>Edit: Our logs show this:</p>
<pre><code> user-agent = Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)
</code></pre>
|
[
{
"answer_id": 186474,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>Do your logs include the referrer information? If there's any information present then it could help to pinpoint the error. If there isn't, that might indicate an \"editing the URL\" attempt. (I don't know how much SSL would change any of this, admittedly.)</p>\n\n<p>Browsers do sometimes <a href=\"http://en.wikipedia.org/wiki/Link_prefetching\" rel=\"nofollow noreferrer\">prefetch links</a> but I don't know whether they'd get rid of the parameter - and it seems unlikely that they'd do this for HTTPS.</p>\n\n<p>Do you have a pattern as to which browsers are being used for these requests?</p>\n"
},
{
"answer_id": 186681,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 0,
"selected": false,
"text": "<p>Check your logs for the agent string and see if these requests are made by a search engine spider.</p>\n"
},
{
"answer_id": 186706,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I know that I sometimes remove the parameter just to check what is there. I'm sure I'm not the only one. </p>\n"
},
{
"answer_id": 220942,
"author": "cnu",
"author_id": 1448,
"author_profile": "https://Stackoverflow.com/users/1448",
"pm_score": 0,
"selected": false,
"text": "<p>Some rogue crawlers change the user-agent to a browser's user agent and crawl pages. This may also be a such a case. </p>\n\n<p>Also most crawlers do try to substitute some other values to the query params to fetch pages which weren't linked.</p>\n"
},
{
"answer_id": 551489,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I have seen this with the web application we are supporting - a stray GET request out of the blue for an already logged in user, wrecking the server-side state and resulting in an error on the subsequent legitimate POST request. </p>\n\n<p>Since in our case the URLs use URL-rewriting attaching sessionid to the URL such GETs would also sometimes have old sessionid.</p>\n\n<p>In the specific log file that lead to nailing this issue these stray requests had the agent string different (though valid) from the rest in the same session.</p>\n\n<p>I am convinced that rather than the browser itself it's some plugin/extension. There is a possibility that a proxy does it or even malware. </p>\n\n<p>We overcame this particular problem by forbidding GET requests to the URI in question.</p>\n\n<p>However, now I am dealing with a similar problem where a POST request appears out of nowhere where it shouldn't and the only difference is in the \"accept\" header.</p>\n"
},
{
"answer_id": 2308033,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 2,
"selected": true,
"text": "<p>I now think this was actually a tomcat bug <a href=\"https://issues.apache.org/bugzilla/show_bug.cgi?id=37794\" rel=\"nofollow noreferrer\">getParameter() fails on POST with transfer-encoding: chunked</a>.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14663/"
] |
We have a web application that passes parameters in the url along the lines of this:
```
www.example.com/ViewCustomer?customer=3945
```
Reasonably often, we will see attempts to access just:
```
www.example.com/ViewCustomer
```
Or system logs this as invalid and sends back a "An error has occurred, contact support with trace number XXX" type page.
Our logs include the session information so it is actually someone logged in with a valid session which means they have successfully signed in with a username and password.
It could be they just typed that into the address bar, but it seems to occur too often for that. Another alternative is that we have a bug in our code, but we've investigated and sometimes there is only one spot and it is clearly ok. We've never had a user complain about something not working and resulting in this. Everything is under SSL.
Has anyone else experienced this? Do some browsers send these sorts of dodgy requests occasionally?
Edit: Our logs show this:
```
user-agent = Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)
```
|
I now think this was actually a tomcat bug [getParameter() fails on POST with transfer-encoding: chunked](https://issues.apache.org/bugzilla/show_bug.cgi?id=37794).
|
186,472 |
<p>I've seen some Python programmers use the following style fairly consistently (we'll call it style 1):</p>
<pre><code>import some_module
# Use some_module.some_identifier in various places.
</code></pre>
<p>For support of this style, you can cite the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow noreferrer">"explicit is better than implicit"</a> maxim. I've seen other programmers use this style (style 2):</p>
<pre><code>from some_module import some_identifier
# Use some_identifier in various places.
</code></pre>
<p>The primary benefit that I see in style 2 is maintainability -- especially with <a href="http://en.wikipedia.org/wiki/Duck_typing" rel="nofollow noreferrer">duck typing</a> ideals I may want to swap some_module for some_other_module. I also feel style 2 wins points with the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow noreferrer">"readability counts"</a> maxim. Although I tend to disagree, one can always argue that search-and-replace is just as good an option when using the first style.</p>
<p><strong>Addendum:</strong> It was noted that you could use <code>as</code> to solve the switch from <code>some_module</code> to <code>some_other_module</code> in style 1. I forgot to mention that it is also common to decide to implement <code>some_identifier</code> in your <em>current</em> module, which makes creation of an equivalent <code>some_module</code> container slightly awkward.</p>
|
[
{
"answer_id": 186483,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>With the existence of the following syntax:</p>\n\n<pre><code>import some_other_module as some_module\n</code></pre>\n\n<p>the maintainability argument of style 2 is no longer relevant.</p>\n\n<p>I tend to use style 1. Normally, I find that I explicitly reference the imported package name only a few times in a typical Python program. Everything else is methods on the object, which of course don't need to reference the imported package.</p>\n"
},
{
"answer_id": 186485,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "<p>I usually use a threshold to decide this. If I want to use a lot of things within <code>some_module</code>, I'll use:</p>\n\n<pre><code>import some_module as sm\nx = sm.whatever\n</code></pre>\n\n<p>If there's only one or two things I need:</p>\n\n<pre><code>from some_module import whatever\nx = whatever\n</code></pre>\n\n<p>That's assuming I don't need a <code>whatever</code> from <code>some_other_module</code>, of course.</p>\n\n<p>I tend to use the <code>as</code> clause on the imports so that I can reduce my typing <strong>and</strong> substitue another module quite easily in the future.</p>\n"
},
{
"answer_id": 186486,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 0,
"selected": false,
"text": "<p>I believe in newer versions of Python (2.5+? must check my facts...) you can even do:</p>\n\n<pre><code>import some_other_module as some_module\n</code></pre>\n\n<p>So you could still go with style 1 and swap in a different module later on.</p>\n\n<p>I think it generally maps to how much you want to clutter up your namespace. Will you just be using one or two names in the module? Or all of them (<code>from x import *</code> is not allways bad, just generally)?</p>\n"
},
{
"answer_id": 186541,
"author": "PierreBdR",
"author_id": 7136,
"author_profile": "https://Stackoverflow.com/users/7136",
"pm_score": 1,
"selected": false,
"text": "<p>I find that the notation</p>\n\n<pre><code>from some_module import some_symbol\n</code></pre>\n\n<p>works best in most cases. Also, in case of name clash for the symbol, you can use:</p>\n\n<pre><code>from some_module import some_symbol as other_symbol\n</code></pre>\n\n<p>As the question states, it avoids rewriting the module name all the time, each time with a risk of mistyping it. I use the syntax:</p>\n\n<pre><code>import module [as other_module]\n</code></pre>\n\n<p>Only in two cases:</p>\n\n<ol>\n<li>I use too many of the module functions/objects to import them all</li>\n<li>The module defines some symbol that may change during execution</li>\n</ol>\n"
},
{
"answer_id": 186636,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer to <code>import X</code> and then use <code>X.a</code> as much as possible.</p>\n\n<p>My exception centers on the deeply nested modules in a big framework like Django. Their module names tend to get lengthy, and their examples all say <code>from django.conf import settings</code> to save you typing <code>django.conf.settings.DEBUG</code> everywhere.</p>\n\n<p>If the module name is deeply nested, then the exception is to use <code>from X.Y.Z import a</code>.</p>\n"
},
{
"answer_id": 186644,
"author": "kender",
"author_id": 4172,
"author_profile": "https://Stackoverflow.com/users/4172",
"pm_score": 0,
"selected": false,
"text": "<p>I personally try not to mess too much with my namespace, so in most situations I just do </p>\n\n<pre><code>import module \n</code></pre>\n\n<p>or \n import module as mod</p>\n\n<p>Only real diffrence is when I have a module with a single class that's used a lot. If I had sublclassed a <code>list</code> type to add some funcionality there, I'd use</p>\n\n<pre><code>from SuperImprovedListOverloadedWithFeatures import NewLIst\nnl = NewList()\n</code></pre>\n\n<p>etc.</p>\n"
},
{
"answer_id": 186813,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 4,
"selected": true,
"text": "<p>There are uses for both cases, so I don't think this is an either-or issue.\nI'd consider using from module <code>import x,y,z</code> when:</p>\n\n<ul>\n<li><p>There are a fairly small number of things to import</p></li>\n<li><p>The purpose of the functions imported is obvious when divorced from the module name. If the names are fairly generic, they may clash with others and tell you little. eg. seeing <code>remove</code> tells you little, but <code>os.remove</code> will probably hint that you're dealing with files.</p></li>\n<li><p>The names don't clash. Similar to the above, but more important. <strong>Never</strong> do something like:</p>\n\n<pre><code> from os import open\n</code></pre></li>\n</ul>\n\n<p><code>import module [as renamed_module]</code> has the advantage that it gives a bit more context about what is being called when you use it. It has the disadvantage that this is a bit more cluttered when the module isn't really giving more information, and is slightly less performant (2 lookups instead of 1).</p>\n\n<p>It also has advantages when testing however (eg. replacing os.open with a mock object, without having to change every module), and should be used when using mutable modules, e.g.</p>\n\n<pre><code>import config\nconfig.dburl = 'sqlite:///test.db'\n</code></pre>\n\n<p>If in doubt, I'd always go with the <code>import module</code> style.</p>\n"
},
{
"answer_id": 187352,
"author": "giltay",
"author_id": 21106,
"author_profile": "https://Stackoverflow.com/users/21106",
"pm_score": 0,
"selected": false,
"text": "<p>I tend to use only a few members of each module, so there's a lot of</p>\n\n<pre><code>from john import cleese\nfrom terry import jones, gilliam\n</code></pre>\n\n<p>in my code. I'll import whole modules (such as <code>os</code> or <code>wx</code>) if I expect to be using most of the module and the module name is short. I'll also import whole modules if there is a name conflict or I want to remind the reader what that function is associated with.</p>\n\n<pre><code>import michael\nimport sarah\n\nimport wave\n\ngov_speech = wave.open(sarah.palin.speechfile)\nparrot_sketch = wave.open(michael.palin.justresting)\n</code></pre>\n\n<p>(I could use <code>from wave import open as wave_open</code>, but I figure that <code>wave.open</code> will be more familiar to the reader.</p>\n"
},
{
"answer_id": 6386083,
"author": "Potr Czachur",
"author_id": 215414,
"author_profile": "https://Stackoverflow.com/users/215414",
"pm_score": 0,
"selected": false,
"text": "<p>You may be interested in Stack Overflow question <em><a href=\"https://stackoverflow.com/questions/6386061\">Why does 'import x;x.y' behave different from 'from x import y', and the first one fails when package x.<strong>init</strong> is not completed?</a></em>.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] |
I've seen some Python programmers use the following style fairly consistently (we'll call it style 1):
```
import some_module
# Use some_module.some_identifier in various places.
```
For support of this style, you can cite the ["explicit is better than implicit"](http://www.python.org/dev/peps/pep-0020/) maxim. I've seen other programmers use this style (style 2):
```
from some_module import some_identifier
# Use some_identifier in various places.
```
The primary benefit that I see in style 2 is maintainability -- especially with [duck typing](http://en.wikipedia.org/wiki/Duck_typing) ideals I may want to swap some\_module for some\_other\_module. I also feel style 2 wins points with the ["readability counts"](http://www.python.org/dev/peps/pep-0020/) maxim. Although I tend to disagree, one can always argue that search-and-replace is just as good an option when using the first style.
**Addendum:** It was noted that you could use `as` to solve the switch from `some_module` to `some_other_module` in style 1. I forgot to mention that it is also common to decide to implement `some_identifier` in your *current* module, which makes creation of an equivalent `some_module` container slightly awkward.
|
There are uses for both cases, so I don't think this is an either-or issue.
I'd consider using from module `import x,y,z` when:
* There are a fairly small number of things to import
* The purpose of the functions imported is obvious when divorced from the module name. If the names are fairly generic, they may clash with others and tell you little. eg. seeing `remove` tells you little, but `os.remove` will probably hint that you're dealing with files.
* The names don't clash. Similar to the above, but more important. **Never** do something like:
```
from os import open
```
`import module [as renamed_module]` has the advantage that it gives a bit more context about what is being called when you use it. It has the disadvantage that this is a bit more cluttered when the module isn't really giving more information, and is slightly less performant (2 lookups instead of 1).
It also has advantages when testing however (eg. replacing os.open with a mock object, without having to change every module), and should be used when using mutable modules, e.g.
```
import config
config.dburl = 'sqlite:///test.db'
```
If in doubt, I'd always go with the `import module` style.
|
186,475 |
<p>I would like to use databinding when displaying data in a TextBox. I'm basically doing like:</p>
<pre><code> public void ShowRandomObject(IRandomObject randomObject) {
Binding binding = new Binding {Source = randomObject, Path = new PropertyPath("Name")};
txtName.SetBinding(TextBox.TextProperty, binding);
}
</code></pre>
<p>I can't seem to find a way to unset the binding. I will be calling this method with a lot of different objects but the TextBox will remain the same. Is there a way to remove the previous binding or is this done automatically when I set the new binding?</p>
|
[
{
"answer_id": 186479,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 7,
"selected": true,
"text": "<p>When available</p>\n\n<pre><code>BindingOperations.ClearBinding(txtName, TextBox.TextProperty)\n</code></pre>\n\n<p>For older SilverLight versions, but not reliable as stated in comments:</p>\n\n<pre><code>txtName.SetBinding(TextBox.TextProperty, null);\n</code></pre>\n\n<p>C# 6.0 features enabled</p>\n\n<pre><code>this.btnFinish.ClearBinding(ButtonBase.CommandProperty);\n</code></pre>\n"
},
{
"answer_id": 186877,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 4,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code>this.ClearValue(TextBox.TextProperty);\n</code></pre>\n\n<p>It's much cleaner I think ;)</p>\n"
},
{
"answer_id": 187902,
"author": "Ed Ball",
"author_id": 23818,
"author_profile": "https://Stackoverflow.com/users/23818",
"pm_score": 7,
"selected": false,
"text": "<p>Alternately:</p>\n\n<pre><code>BindingOperations.ClearBinding(txtName, TextBox.TextProperty)\n</code></pre>\n"
},
{
"answer_id": 2973142,
"author": "Bodekaer",
"author_id": 309331,
"author_profile": "https://Stackoverflow.com/users/309331",
"pm_score": 0,
"selected": false,
"text": "<p>How about just</p>\n\n<pre><code>txtName.Text = txtName.Text;\n</code></pre>\n\n<p>You would have to set the value after clearing it anyways. \nThis works in SL4 at least.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143/"
] |
I would like to use databinding when displaying data in a TextBox. I'm basically doing like:
```
public void ShowRandomObject(IRandomObject randomObject) {
Binding binding = new Binding {Source = randomObject, Path = new PropertyPath("Name")};
txtName.SetBinding(TextBox.TextProperty, binding);
}
```
I can't seem to find a way to unset the binding. I will be calling this method with a lot of different objects but the TextBox will remain the same. Is there a way to remove the previous binding or is this done automatically when I set the new binding?
|
When available
```
BindingOperations.ClearBinding(txtName, TextBox.TextProperty)
```
For older SilverLight versions, but not reliable as stated in comments:
```
txtName.SetBinding(TextBox.TextProperty, null);
```
C# 6.0 features enabled
```
this.btnFinish.ClearBinding(ButtonBase.CommandProperty);
```
|
186,477 |
<p>I have a function which parses one string into two strings. In C# I would declare it like this:</p>
<pre><code>void ParseQuery(string toParse, out string search, out string sort)
{
...
}
</code></pre>
<p>and I'd call it like this:</p>
<pre><code>string searchOutput, sortOutput;
ParseQuery(userInput, out searchOutput, out sortOutput);
</code></pre>
<p>The current project has to be done in C++/CLI. I've tried</p>
<pre><code>using System::Runtime::InteropServices;
...
void ParseQuery(String ^ toParse, [Out] String^ search, [Out] String^ sort)
{
...
}
</code></pre>
<p>but if I call it like this:</p>
<pre><code>String ^ searchOutput, ^ sortOutput;
ParseQuery(userInput, [Out] searchOutput, [Out] sortOutput);
</code></pre>
<p>I get a compiler error, and if I call it like this:</p>
<pre><code>String ^ searchOutput, ^ sortOutput;
ParseQuery(userInput, searchOutput, sortOutput);
</code></pre>
<p>then I get an error at runtime. How should I declare and call my function?</p>
|
[
{
"answer_id": 186504,
"author": "Greg Dean",
"author_id": 1200558,
"author_profile": "https://Stackoverflow.com/users/1200558",
"pm_score": -1,
"selected": false,
"text": "<p>It's not supported. The closest you can get is ref</p>\n\n<p>Granted you can fake it, but you lose a compile time check.</p>\n"
},
{
"answer_id": 187577,
"author": "Bert Huijben",
"author_id": 2094,
"author_profile": "https://Stackoverflow.com/users/2094",
"pm_score": 8,
"selected": true,
"text": "<p>C++/CLI itself doesn't support a real 'out' argument, but you can mark a reference as an out argument to make other languages see it as a real out argument.</p>\n\n<p>You can do this for reference types as:</p>\n\n<pre><code>void ReturnString([Out] String^% value)\n{\n value = \"Returned via out parameter\";\n}\n\n// Called as\nString^ result;\nReturnString(result);\n</code></pre>\n\n<p>And for value types as:</p>\n\n<pre><code>void ReturnInt([Out] int% value)\n{\n value = 32;\n}\n\n// Called as\nint result;\nReturnInt(result);\n</code></pre>\n\n<p>The % makes it a 'ref' parameter and the OutAttribute marks that it is only used for output values.</p>\n"
},
{
"answer_id": 2908659,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Using Visual Studio 2008, this works and solved a major problem at my job. Thanks!</p>\n\n<pre><code>// header\n// Use namespace for Out-attribute.\nusing namespace System::Runtime::InteropServices; \nnamespace VHT_QMCLInterface {\n public ref class Client\n {\n public:\n Client();\n void ReturnInteger( int a, int b, [Out]int %c);\n void ReturnString( int a, int b, [Out]String^ %c);\n }\n}\n\n// cpp\nnamespace VHT_QMCLInterface {\n\n Client::Client()\n {\n\n }\n\n void Client::ReturnInteger( int a, int b, [Out]int %c)\n {\n c = a + b;\n }\n void Client::ReturnString( int a, int b, [Out]String^ %c)\n {\n c = String::Format( \"{0}\", a + b);\n }\n}\n\n// cs\nnamespace TestQMCLInterface\n{\n class Program\n {\n VHT_QMCLInterface.Client m_Client = new VHT_QMCLInterface.Client();\n static void Main(string[] args)\n {\n Program l_Program = new Program();\n l_Program.DoReturnInt();\n l_Program.DoReturnString();\n Console.ReadKey();\n }\n\n void DoReturnInt()\n {\n int x = 10;\n int y = 20;\n int z = 0;\n m_Client.ReturnInteger( x, y, out z);\n Console.WriteLine(\"\\nReturnInteger: {0} + {1} = {2}\", x, y, z);\n }\n\n void DoReturnString()\n {\n int x = 10;\n int y = 20;\n String z = \"xxxx\";\n m_Client.ReturnString(x, y, out z);\n Console.WriteLine(\"\\nReturnString: {0} + {1} = '{2}'\", x, y, z);\n }\n }\n}\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
] |
I have a function which parses one string into two strings. In C# I would declare it like this:
```
void ParseQuery(string toParse, out string search, out string sort)
{
...
}
```
and I'd call it like this:
```
string searchOutput, sortOutput;
ParseQuery(userInput, out searchOutput, out sortOutput);
```
The current project has to be done in C++/CLI. I've tried
```
using System::Runtime::InteropServices;
...
void ParseQuery(String ^ toParse, [Out] String^ search, [Out] String^ sort)
{
...
}
```
but if I call it like this:
```
String ^ searchOutput, ^ sortOutput;
ParseQuery(userInput, [Out] searchOutput, [Out] sortOutput);
```
I get a compiler error, and if I call it like this:
```
String ^ searchOutput, ^ sortOutput;
ParseQuery(userInput, searchOutput, sortOutput);
```
then I get an error at runtime. How should I declare and call my function?
|
C++/CLI itself doesn't support a real 'out' argument, but you can mark a reference as an out argument to make other languages see it as a real out argument.
You can do this for reference types as:
```
void ReturnString([Out] String^% value)
{
value = "Returned via out parameter";
}
// Called as
String^ result;
ReturnString(result);
```
And for value types as:
```
void ReturnInt([Out] int% value)
{
value = 32;
}
// Called as
int result;
ReturnInt(result);
```
The % makes it a 'ref' parameter and the OutAttribute marks that it is only used for output values.
|
186,522 |
<p>Is there a better way to profile code then:</p>
<pre><code>$start1 = microtime(TRUE);
for($i=0;$i<count($array);$i++)
{
//do something
}
$time1 = microtime(TRUE) - $start1;
</code></pre>
|
[
{
"answer_id": 186596,
"author": "Dinoboff",
"author_id": 1771,
"author_profile": "https://Stackoverflow.com/users/1771",
"pm_score": 3,
"selected": true,
"text": "<p>Xdebug or Zend Debugger if you have some difficulty to install Xdebug.</p>\n\n<p>Their profiler will time everything for you without any modification of your code.</p>\n\n<p><a href=\"http://www.xdebug.org/\" rel=\"nofollow noreferrer\">http://www.xdebug.org/</a></p>\n\n<p><a href=\"http://www.zend.com/en/community/pdt\" rel=\"nofollow noreferrer\">http://www.zend.com/en/community/pdt</a></p>\n\n<p><a href=\"http://devzone.zend.com/article/2899-Profiling-PHP-Applications-With-xdebug\" rel=\"nofollow noreferrer\">http://devzone.zend.com/article/2899-Profiling-PHP-Applications-With-xdebug</a> - a serie of tutorials about xdebug.</p>\n"
},
{
"answer_id": 186874,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "<p>Without using an external tool, I would say you've done the best you can.</p>\n\n<p>If you want to use a tool built for the purpose, the other answers are dead-on.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
Is there a better way to profile code then:
```
$start1 = microtime(TRUE);
for($i=0;$i<count($array);$i++)
{
//do something
}
$time1 = microtime(TRUE) - $start1;
```
|
Xdebug or Zend Debugger if you have some difficulty to install Xdebug.
Their profiler will time everything for you without any modification of your code.
<http://www.xdebug.org/>
<http://www.zend.com/en/community/pdt>
<http://devzone.zend.com/article/2899-Profiling-PHP-Applications-With-xdebug> - a serie of tutorials about xdebug.
|
186,544 |
<p>I need a function which executes an INSERT statement on a database and returns the Auto_Increment primary key. I have the following C# code but, while the INSERT statement works fine (I can see the record in the database, the PK is generated correctly and rows == 1), the id value is always 0. Any ideas on what might be going wrong?</p>
<pre><code> public int ExecuteInsertStatement(string statement)
{
InitializeAndOpenConnection();
int id = -1;
IDbCommand cmdInsert = connection.CreateCommand();
cmdInsert.CommandText = statement;
int rows = cmdInsert.ExecuteNonQuery();
if (rows == 1)
{
IDbCommand cmdId = connection.CreateCommand();
cmdId.CommandText = "SELECT @@Identity;";
id = (int)cmdId.ExecuteScalar();
}
return id;
}
private void InitializeAndOpenConnection()
{
if (connection == null)
connection = OleDbProviderFactory.Instance.CreateConnection(connectString);
if(connection.State != ConnectionState.Open)
connection.Open();
}
</code></pre>
<p>In response to answers, I tried:</p>
<pre><code>public int ExecuteInsertStatement(string statement, string tableName)
{
InitializeAndOpenConnection();
int id = -1;
IDbCommand cmdInsert = connection.CreateCommand();
cmdInsert.CommandText = statement + ";SELECT OID FROM " + tableName + " WHERE OID = SCOPE_IDENTITY();";
id = (int)cmdInsert.ExecuteScalar();
return id;
}
</code></pre>
<p>but I'm now getting the error "Characters found after end of SQL statement"</p>
<p>I'm using an MS Access database with OleDb connection, Provider=Microsoft.Jet.OLEDB.4.0</p>
|
[
{
"answer_id": 186555,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 1,
"selected": false,
"text": "<p>I think you need to have the Select @@identity with the first create command - try appending it via \";SELECT @@Identity\" and .ExecuteScalar the insert statement</p>\n"
},
{
"answer_id": 186557,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "<p>Are there any triggers on your table that might be inserting into other tables? Generally we're advised against using @@Identity in favour of <a href=\"http://msdn.microsoft.com/en-us/library/ms175098.aspx\" rel=\"nofollow noreferrer\">IDENT_CURRENT</a> so that you can guarantee that the identity returned is for the table you just inserted into.</p>\n"
},
{
"answer_id": 186562,
"author": "ila",
"author_id": 1178,
"author_profile": "https://Stackoverflow.com/users/1178",
"pm_score": 0,
"selected": false,
"text": "<p>I think that @@identity is valid only in the scope of the command - in your case when you execute \"statement\".</p>\n\n<p>Modify your \"statement\"so that the stored procedure itself will return the @@IDENTITY value right after the INSERT statement, and read it as the return code of the stored procedure execution.</p>\n"
},
{
"answer_id": 186563,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 4,
"selected": false,
"text": "<p>1) combine the INSERT and SELECT statement (concatenate using \";\") into 1 db command</p>\n\n<p>2) use SCOPE_IDENTITY() instead of @@IDENTITY</p>\n\n<p>INSERT INTO blabla... ; SELECT OID FROM table WHERE OID = SCOPE_IDENTITY()</p>\n\n<p>-- update:</p>\n\n<p>as it turned out that the question was related to MS ACCESS, I found <a href=\"http://www.mikesdotnetting.com/Article.aspx?ArticleID=54\" rel=\"noreferrer\">this article</a> which suggests that simply reusing the first command and setting its CommandText to \"SELECT @@IDENTITY\" should be sufficient.</p>\n"
},
{
"answer_id": 186564,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": -1,
"selected": false,
"text": "<p>As you're using Access, take a look at <a href=\"http://databases.aspfaq.com/general/how-do-i-get-the-identity/autonumber-value-for-the-row-i-inserted.html\" rel=\"nofollow noreferrer\">this article</a> from aspfaq, scroll down to about half way down the page. The code's in classic ASP, but hopefully the principles should still stand.</p>\n\n<hr>\n\n<p>The SELECT @@Identity ends up being treated as a separate execution context, I believe. Code that <em>should</em> work would be:</p>\n\n<pre><code>public int ExecuteInsertStatement(string statement)\n{\n InitializeAndOpenConnection();\n\n IDbCommand cmdInsert = connection.CreateCommand();\n cmdInsert.CommandText = statement + \"; SELECT @@Identity\";\n object result = cmdInsert.ExecuteScalar();\n\n if (object == DBNull.Value)\n {\n return -1;\n }\n else\n {\n return Convert.ToInt32(result);\n }\n}\n</code></pre>\n\n<p>You'd probably want/need to tidy up the concatenation that adds the 'SELECT @@Identity' onto the end of the code though.</p>\n"
},
{
"answer_id": 186565,
"author": "evilhomer",
"author_id": 2806,
"author_profile": "https://Stackoverflow.com/users/2806",
"pm_score": 2,
"selected": false,
"text": "<p>you need to return the identity at the same time as you open the initial connection.\nReturn a result set from your insert or an output variable. </p>\n\n<p>You should also always use SCOPE_IDENTITY() not @@identity. <a href=\"http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/\" rel=\"nofollow noreferrer\">Reference here</a></p>\n\n<p>You should add </p>\n\n<pre><code>SELECT SCOPE_IDENTITY() \n</code></pre>\n\n<p>After the insert.</p>\n"
},
{
"answer_id": 186603,
"author": "Geir-Tore Lindsve",
"author_id": 4582,
"author_profile": "https://Stackoverflow.com/users/4582",
"pm_score": 0,
"selected": false,
"text": "<p>Check your database settings. I had a similar problem a while ago and discovered that the SQL Server connection setting 'no count' was enabled.</p>\n\n<p>In SQL Server Management Studio, you can find this by right-clicking the server in the Object Explorer, select Properties and then navigate to the Connections page. Look at the settings for \"Default connection options\"</p>\n"
},
{
"answer_id": 186659,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 2,
"selected": false,
"text": "<p>You are using Jet (not SQL Server) and Jet can only handle one SQL statement per command, therefore you need to execute <code>SELECT @@IDENTITY</code> in a separate command, obviously ensuring it uses the same connection as the <code>INSERT</code>.</p>\n"
},
{
"answer_id": 186725,
"author": "moffdub",
"author_id": 10759,
"author_profile": "https://Stackoverflow.com/users/10759",
"pm_score": 0,
"selected": false,
"text": "<p>Aren't most of the answerers forgetting that the asker is not using SQL Server?</p>\n\n<p><strike>Apparently, MS Access 2000 and later <a href=\"http://msdn.microsoft.com/en-us/library/ks9f57t0(VS.71).aspx\" rel=\"nofollow noreferrer\">doesn't support @@IDENTITY</a>.</strike> The alternative is \"Using the RowUpdated event, you can determine if an INSERT has occurred, retrieve the latest @@IDENTITY value, and place that in the identity column of the local table in the DataSet.\"</p>\n\n<p>And yes, this is for embedded VBA in the Access DB. That is still callable outside of Access via the Access Object Library.</p>\n\n<p>Edit: ok, it is supported, sorry for the groggy early-morning answer. But the rest of this answer might help.</p>\n"
},
{
"answer_id": 186992,
"author": "Adrian",
"author_id": 11304,
"author_profile": "https://Stackoverflow.com/users/11304",
"pm_score": 3,
"selected": false,
"text": "<p>Microsoft.Jet.OLEDB.4.0 provider supports Jet v3 and Jet v4 database engines, however \nSELECT @@IDENTITY is not supported for Jet v3.</p>\n\n<p>MSAccess 97 is Jet v3 and does not support SELECT @@IDENTITY; It supported on MSAccess 2000 and above.</p>\n"
},
{
"answer_id": 900394,
"author": "Fuangwith S.",
"author_id": 24550,
"author_profile": "https://Stackoverflow.com/users/24550",
"pm_score": 0,
"selected": false,
"text": "<p>If you would like to retrieve value of auto running number of transaction that you're inserting and your environment following\n 1. Database is MsAccess.\n 2. Driver is Jet4 with connection string like this \"Provider=Microsoft.Jet.OLEDB.4.0;Password={0};Data Source={1};Persist Security Info=True\"\n 3. use Oledb</p>\n\n<p>You can apply my example to your code</p>\n\n<pre><code>OleDbConnection connection = String.Format(\"Provider=Microsoft.Jet.OLEDB.4.0;Password={0};Data Source={1};Persist Security Info=True\",dbinfo.Password,dbinfo.MsAccessDBFile);\nconnection.Open();\nOleDbTransaction transaction = null;\ntry{\n connection.BeginTransaction();\n String commandInsert = \"INSERT INTO TB_SAMPLE ([NAME]) VALUES ('MR. DUKE')\";\n OleDbCommand cmd = new OleDbCommand(commandInsert , connection, transaction);\n cmd.ExecuteNonQuery();\n String commandIndentity = \"SELECT @@IDENTITY\";\n cmd = new OleDbCommandcommandIndentity, connection, transaction);\n Console.WriteLine(\"New Running No = {0}\", (int)cmd.ExecuteScalar());\n connection.Commit();\n}catch(Exception ex){\n connection.Rollback();\n}finally{\n connection.Close();\n} \n</code></pre>\n"
},
{
"answer_id": 2036484,
"author": "imam kuncoro",
"author_id": 242000,
"author_profile": "https://Stackoverflow.com/users/242000",
"pm_score": -1,
"selected": false,
"text": "<pre><code>CREATE procedure dbo.sp_whlogin\n(\n @id nvarchar(20),\n @ps nvarchar(20),\n @curdate datetime,\n @expdate datetime\n)\n\nAS\nBEGIN\n DECLARE @role nvarchar(20)\n DECLARE @menu varchar(255)\n DECLARE @loginid int\n\n SELECT @role = RoleID\n FROM dbo.TblUsers\n WHERE UserID = @id AND UserPass = @ps\n\n if @role is not null \n BEGIN\n INSERT INTO TblLoginLog (UserID, LoginAt, ExpireAt, IsLogin) VALUES (@id, @curdate, @expdate, 1);\n SELECT @loginid = @@IDENTITY;\n SELECT @loginid as loginid, RoleName as role, RoleMenu as menu FROM TblUserRoles WHERE RoleName = @role\n END\n else\n BEGIN\n SELECT '' as role, '' as menu\n END\nEND\nGO\n</code></pre>\n"
},
{
"answer_id": 30603486,
"author": "user1943915",
"author_id": 1943915,
"author_profile": "https://Stackoverflow.com/users/1943915",
"pm_score": 0,
"selected": false,
"text": "<p>The short answer: <br>\n 1. Create two commands each accepting a single query.<br>\n 2. First sql query is the INSERT record.<br>\n 3. Second sql query is \"SELECT @@Identity;\" which returns the AutoNumber.<br>\n 4. Use cmd.ExecuteScalar() which returns a first column of first row.<br>\n 5. The returned result output is the AutoNumber value generated in the current insert query.<br></p>\n\n<p><a href=\"http://blogs.msdn.com/b/spike/archive/2009/12/02/getting-autonumber-from-access-via-select-identity-needs-to-be-done-in-same-connection-as-the-insert.aspx\" rel=\"nofollow\">It is referenced from this link</a>. The example code is as under. Note the difference for \"SAME Connection VS NEW Connection\". The SAME Connection gives the desired output.</p>\n\n<pre><code> class Program\n{\n static string path = @\"<your path>\";\n static string db = @\"Test.mdb\";\n static void Main(string[] args)\n {\n string cs = String.Format(@\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}\\{1}\", path, db);\n // Using the same connection for the insert and the SELECT @@IDENTITY\n using (OleDbConnection con = new OleDbConnection(cs))\n {\n con.Open();\n OleDbCommand cmd = con.CreateCommand();\n for (int i = 0; i < 3; i++)\n {\n cmd.CommandText = \"INSERT INTO TestTable(OurTxt) VALUES ('\" + i.ToString() + \"')\";\n cmd.ExecuteNonQuery();\n\n cmd.CommandText = \"SELECT @@IDENTITY\";\n Console.WriteLine(\"AutoNumber: {0}\", (int)cmd.ExecuteScalar());\n }\n con.Close();\n }\n // Using a new connection and then SELECT @@IDENTITY\n using (OleDbConnection con = new OleDbConnection(cs))\n {\n con.Open();\n OleDbCommand cmd = con.CreateCommand();\n cmd.CommandText = \"SELECT @@IDENTITY\";\n Console.WriteLine(\"\\nNew connection, AutoNumber: {0}\", (int)cmd.ExecuteScalar());\n con.Close();\n }\n }\n}\n</code></pre>\n\n<p>This should produce the self-explanatory output:</p>\n\n<pre><code>AutoNumber: 1 <br>\nAutoNumber: 2 <br>\nAutoNumber: 3 <br>\n\nNew connection, AutoNumber: 0\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23826/"
] |
I need a function which executes an INSERT statement on a database and returns the Auto\_Increment primary key. I have the following C# code but, while the INSERT statement works fine (I can see the record in the database, the PK is generated correctly and rows == 1), the id value is always 0. Any ideas on what might be going wrong?
```
public int ExecuteInsertStatement(string statement)
{
InitializeAndOpenConnection();
int id = -1;
IDbCommand cmdInsert = connection.CreateCommand();
cmdInsert.CommandText = statement;
int rows = cmdInsert.ExecuteNonQuery();
if (rows == 1)
{
IDbCommand cmdId = connection.CreateCommand();
cmdId.CommandText = "SELECT @@Identity;";
id = (int)cmdId.ExecuteScalar();
}
return id;
}
private void InitializeAndOpenConnection()
{
if (connection == null)
connection = OleDbProviderFactory.Instance.CreateConnection(connectString);
if(connection.State != ConnectionState.Open)
connection.Open();
}
```
In response to answers, I tried:
```
public int ExecuteInsertStatement(string statement, string tableName)
{
InitializeAndOpenConnection();
int id = -1;
IDbCommand cmdInsert = connection.CreateCommand();
cmdInsert.CommandText = statement + ";SELECT OID FROM " + tableName + " WHERE OID = SCOPE_IDENTITY();";
id = (int)cmdInsert.ExecuteScalar();
return id;
}
```
but I'm now getting the error "Characters found after end of SQL statement"
I'm using an MS Access database with OleDb connection, Provider=Microsoft.Jet.OLEDB.4.0
|
1) combine the INSERT and SELECT statement (concatenate using ";") into 1 db command
2) use SCOPE\_IDENTITY() instead of @@IDENTITY
INSERT INTO blabla... ; SELECT OID FROM table WHERE OID = SCOPE\_IDENTITY()
-- update:
as it turned out that the question was related to MS ACCESS, I found [this article](http://www.mikesdotnetting.com/Article.aspx?ArticleID=54) which suggests that simply reusing the first command and setting its CommandText to "SELECT @@IDENTITY" should be sufficient.
|
186,548 |
<p>I am using IIS6, I've written an HttpModule, and I get this error? After googling the web I find that this problem is caused by the .NET framework 3.5, so I put this on a machine where I didn't install .NET 3.5, but the problem is still there!</p>
|
[
{
"answer_id": 186574,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 3,
"selected": false,
"text": "<p>Only IIS7 supports the integrated pipeline. On IIS7 a HttpModule can participate in all requests coming to the web server not just those targeting specific file extensions.</p>\n\n<p>II6 uses what IIS7 calls the classic pipeline where a HttpModules can only get involved once the earlier ISAPI based pipeline determines that the script mapping requires the request to handed over to ASP.NET.</p>\n"
},
{
"answer_id": 186610,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 5,
"selected": false,
"text": "<p>My attempt at psychic debugging: you're using a statement like:</p>\n\n<pre><code>Response.Headers(\"X-Foo\") = \"bar\"\n</code></pre>\n\n<p>If this is indeed the case, changing this as shown below will work around the problem:</p>\n\n<pre><code>Response.AddHeader(\"X-Foo\", \"bar\")\n</code></pre>\n"
},
{
"answer_id": 2852833,
"author": "Michael Itzoe",
"author_id": 24566,
"author_profile": "https://Stackoverflow.com/users/24566",
"pm_score": 3,
"selected": false,
"text": "<p>Just came across this problem. Using IIS6 and .NET 3.5. Fix for me was to use <code>Response.AddHeader</code> instead of <code>Response.Headers.Add</code>. HTH.</p>\n"
},
{
"answer_id": 21110920,
"author": "Russell",
"author_id": 185589,
"author_profile": "https://Stackoverflow.com/users/185589",
"pm_score": 0,
"selected": false,
"text": "<p>Inspired by other answers, I've found that it's accessing the <code>Response.Headers</code> <em>object</em> that causes the \"operation requires IIS integrated pipeline mode\" exception.</p>\n\n<p>Avoid <code>.Headers</code> and call other (older?) helper functions like:</p>\n\n<ul>\n<li><code>Response.AddHeader()</code> and</li>\n<li><code>Response.ClearHeaders()</code> (in my case!) </li>\n</ul>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20142/"
] |
I am using IIS6, I've written an HttpModule, and I get this error? After googling the web I find that this problem is caused by the .NET framework 3.5, so I put this on a machine where I didn't install .NET 3.5, but the problem is still there!
|
My attempt at psychic debugging: you're using a statement like:
```
Response.Headers("X-Foo") = "bar"
```
If this is indeed the case, changing this as shown below will work around the problem:
```
Response.AddHeader("X-Foo", "bar")
```
|
186,553 |
<p>There is the button control in silverlight application . Can I send a mouse click event to it programmatically?</p>
|
[
{
"answer_id": 186618,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": -1,
"selected": false,
"text": "<p>I've not used Silverlight but I assume it's the same process as Windows.Forms and WebControls. You'll just need to call the button's <code>.Click(Object o, EventArgs e)</code> method.</p>\n"
},
{
"answer_id": 186940,
"author": "Bill Reiss",
"author_id": 18967,
"author_profile": "https://Stackoverflow.com/users/18967",
"pm_score": 1,
"selected": false,
"text": "<p>You can't make the Click event fire for security reasons, because then you would be able to do things like force a user into full screen mode without them knowing it. As Oli said, you could call the Click event handler directly, but you can't actually fire a Click event.</p>\n"
},
{
"answer_id": 189729,
"author": "John Smith",
"author_id": 24661,
"author_profile": "https://Stackoverflow.com/users/24661",
"pm_score": 0,
"selected": false,
"text": "<p>The classic way to do this in .Net is to P/Invoke SendInput() from user32.dll, since there's no way to do this with the .Net framework.</p>\n\n<p>I'm not familiar with Silverlight, but I know that it uses a compact sandbox of a .Net, so if interoperability is available, you'll find plenty examples on the internet.</p>\n"
},
{
"answer_id": 2038555,
"author": "Damián Ulises Cedillo",
"author_id": 247630,
"author_profile": "https://Stackoverflow.com/users/247630",
"pm_score": 0,
"selected": false,
"text": "<p>I have buttons for CRUD operations in my page, after Save, Delete or Update I need Refresh the Data in a Datagrid, The most easy way was to send click event to the \"Read\" Button, from the Others CRUD buttons</p>\n\n<p>This code fire that event:</p>\n\n<pre><code> private void btnSave_Click(object sender, RoutedEventArgs e)\n {\n //.....Save Operation\n\n //--At Finish refresh the datagrid\n btnRead_Click(btnRead, new RoutedEventArgs());\n }\n</code></pre>\n"
},
{
"answer_id": 2310214,
"author": "moonlightdock",
"author_id": 117161,
"author_profile": "https://Stackoverflow.com/users/117161",
"pm_score": 0,
"selected": false,
"text": "<p>Try using Automation Peers (if you absolutely need to do this programmatically). </p>\n\n<p><a href=\"http://www.vbdotnetheaven.com/UploadFile/dbeniwal321/TriggerEvent01232009020637AM/TriggerEvent.aspx\" rel=\"nofollow noreferrer\">http://www.vbdotnetheaven.com/UploadFile/dbeniwal321/TriggerEvent01232009020637AM/TriggerEvent.aspx</a> has a sample using vb.net</p>\n\n<p>Ideal way would be to have a shared function which gets called both from button click handler as well as other cases where needed</p>\n"
},
{
"answer_id": 3095409,
"author": "Nadzzz",
"author_id": 224214,
"author_profile": "https://Stackoverflow.com/users/224214",
"pm_score": 4,
"selected": false,
"text": "<p>If you still want to do that. You can now upgrade to Silverlight version 3.0 or later versions and do the following:</p>\n\n<p>You can use the button automation peer from System.Windows.Automation.Peers to accomplish what you want.</p>\n\n<pre><code>if (button is Button)\n{\n ButtonAutomationPeer peer = new ButtonAutomationPeer((Button)button);\n\n IInvokeProvider ip = (IInvokeProvider)peer;\n ip.Invoke();\n}\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
There is the button control in silverlight application . Can I send a mouse click event to it programmatically?
|
If you still want to do that. You can now upgrade to Silverlight version 3.0 or later versions and do the following:
You can use the button automation peer from System.Windows.Automation.Peers to accomplish what you want.
```
if (button is Button)
{
ButtonAutomationPeer peer = new ButtonAutomationPeer((Button)button);
IInvokeProvider ip = (IInvokeProvider)peer;
ip.Invoke();
}
```
|
186,556 |
<p>Say you have 100 directories and for each directory you have a file named .pdf stored somewhere else. If you want to move/copy each file into the directory with the same name, can this be done on the Windows command line?</p>
|
[
{
"answer_id": 186580,
"author": "Liam",
"author_id": 445016,
"author_profile": "https://Stackoverflow.com/users/445016",
"pm_score": 0,
"selected": false,
"text": "<p>You would need to write a script to iterate through each file (and its path), extract the filename-'.pdf' and then move the file to the directory of the same name</p>\n"
},
{
"answer_id": 186592,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it using the <a href=\"http://technet.microsoft.com/en-us/library/bb490909.aspx\" rel=\"nofollow noreferrer\">FOR command</a>. Something in the line of:</p>\n\n<pre><code>for /f %%f in ('dir /s /b c:\\source\\*.pdf') do copy \"%%f\" c:\\target\n</code></pre>\n\n<p>If you have a list of the file names w/ full path in a text file, say files.txt, you can also do</p>\n\n<pre><code>for /f %%f in (files.txt) do copy \"%%f\" c:\\target\n</code></pre>\n"
},
{
"answer_id": 186608,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "<p>This is a batch script that probably does what you want:</p>\n\n<pre><code>setlocal\nset target_dir=D:\\\nset source_dir=C:\\WINDOWS\n\nfor %%i in (%source_dir%\\*.pdf) do move %%i %target_dir%\\%%~ni.%%~xi\n\nendlocal\n</code></pre>\n"
},
{
"answer_id": 217613,
"author": "Richard A",
"author_id": 24355,
"author_profile": "https://Stackoverflow.com/users/24355",
"pm_score": 2,
"selected": false,
"text": "<p>From the command line:</p>\n\n<pre><code>for /f %f in ('dir /s /b mypath\\*.pdf') do @copy %~nxf myotherpath\n</code></pre>\n\n<p>As it's on a command line and not in a batch file you only need %, not %%.</p>\n\n<p>dir /s /b is recursive and bare. (see dir /?)</p>\n\n<p>The @ before copy stops the echo of each copy command. You can echo them if you like, up to you.</p>\n\n<p>%~nxf gets the name and extension of %f. (see call /?)</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13220/"
] |
Say you have 100 directories and for each directory you have a file named .pdf stored somewhere else. If you want to move/copy each file into the directory with the same name, can this be done on the Windows command line?
|
You can do it using the [FOR command](http://technet.microsoft.com/en-us/library/bb490909.aspx). Something in the line of:
```
for /f %%f in ('dir /s /b c:\source\*.pdf') do copy "%%f" c:\target
```
If you have a list of the file names w/ full path in a text file, say files.txt, you can also do
```
for /f %%f in (files.txt) do copy "%%f" c:\target
```
|
186,588 |
<p>When you limit the number of rows to be returned by a SQL query, usually used in paging, there are two methods to determine the total number of records:</p>
<h3>Method 1</h3>
<p>Include the <code>SQL_CALC_FOUND_ROWS</code> option in the original <code>SELECT</code>, and then get the total number of rows by running <code>SELECT FOUND_ROWS()</code>:</p>
<pre><code>SELECT SQL_CALC_FOUND_ROWS * FROM table WHERE id > 100 LIMIT 10;
SELECT FOUND_ROWS();
</code></pre>
<h3>Method 2</h3>
<p>Run the query normally, and then get the total number of rows by running <code>SELECT COUNT(*)</code></p>
<pre><code>SELECT * FROM table WHERE id > 100 LIMIT 10;
SELECT COUNT(*) FROM table WHERE id > 100;
</code></pre>
<p><strong>Which method is the best / fastest?</strong></p>
|
[
{
"answer_id": 188682,
"author": "nathan",
"author_id": 16430,
"author_profile": "https://Stackoverflow.com/users/16430",
"pm_score": 8,
"selected": true,
"text": "<p>It depends. See the MySQL Performance Blog post on this subject: <a href=\"https://www.percona.com/blog/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/\" rel=\"noreferrer\">To <code>SQL_CALC_FOUND_ROWS</code> or not to <code>SQL_CALC_FOUND_ROWS</code>?</a></p>\n<p>Just a quick summary: Peter says that it depends on your indexes and other factors. Many of the comments to the post seem to say that <code>SQL_CALC_FOUND_ROWS</code> is almost always slower - sometimes up to 10x slower - than running two queries.</p>\n"
},
{
"answer_id": 20688884,
"author": "Jeff Clemens",
"author_id": 1159077,
"author_profile": "https://Stackoverflow.com/users/1159077",
"pm_score": 5,
"selected": false,
"text": "<p>When choosing the \"best\" approach, a more important consideration than speed might be the maintainability and correctness of your code. If so, SQL_CALC_FOUND_ROWS is preferable because you only need to maintain a single query. Using a single query completely precludes the possibility of a subtle difference between the main and count queries, which may lead to an inaccurate COUNT.</p>\n"
},
{
"answer_id": 25124430,
"author": "Pierre-Olivier Vares",
"author_id": 2955802,
"author_profile": "https://Stackoverflow.com/users/2955802",
"pm_score": 3,
"selected": false,
"text": "<p>IMHO, the reason why 2 queries </p>\n\n<pre><code>SELECT * FROM count_test WHERE b = 666 ORDER BY c LIMIT 5;\nSELECT count(*) FROM count_test WHERE b = 666;\n</code></pre>\n\n<p>are faster than using SQL_CALC_FOUND_ROWS</p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS * FROM count_test WHERE b = 555 ORDER BY c LIMIT 5;\n</code></pre>\n\n<p>has to be seen as a particular case.</p>\n\n<p>It in facts depends on the selectivity of the WHERE clause compared to the selectivity of the implicit one equivalent to the ORDER + LIMIT.</p>\n\n<p>As Arvids told in comment (<a href=\"http://www.mysqlperformanceblog.com/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/#comment-1174394\">http://www.mysqlperformanceblog.com/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/#comment-1174394</a>), the fact that the EXPLAIN use, or not, a temporay table, should be a good base for knowing if SCFR will be faster or not.</p>\n\n<p>But, as I added (<a href=\"http://www.mysqlperformanceblog.com/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/#comment-8166482\">http://www.mysqlperformanceblog.com/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/#comment-8166482</a>), the result really, really depends on the case. For a particular paginator, you could get to the conclusion that “for the 3 first pages, use 2 queries; for the following pages, use a SCFR” !</p>\n"
},
{
"answer_id": 30983158,
"author": "patapouf_ai",
"author_id": 3990607,
"author_profile": "https://Stackoverflow.com/users/3990607",
"pm_score": 4,
"selected": false,
"text": "<p>According to the following article: <a href=\"https://www.percona.com/blog/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/\" rel=\"noreferrer\">https://www.percona.com/blog/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/</a></p>\n\n<p>If you have an <em>INDEX</em> on your where clause (if id is indexed in your case), then it is better not to use <strong>SQL_CALC_FOUND_ROWS</strong> and use 2 queries instead, but if you don't have an index on what you put in your where clause (id in your case) then using <strong>SQL_CALC_FOUND_ROWS</strong> is more efficient. </p>\n"
},
{
"answer_id": 36485946,
"author": "Jessé Catrinck",
"author_id": 3625217,
"author_profile": "https://Stackoverflow.com/users/3625217",
"pm_score": 3,
"selected": false,
"text": "<p>Removing some unnecessary SQL and then <code>COUNT(*)</code> will be faster than <code>SQL_CALC_FOUND_ROWS</code>. Example:</p>\n\n<pre><code>SELECT Person.Id, Person.Name, Job.Description, Card.Number\nFROM Person\nJOIN Job ON Job.Id = Person.Job_Id\nLEFT JOIN Card ON Card.Person_Id = Person.Id\nWHERE Job.Name = 'WEB Developer'\nORDER BY Person.Name\n</code></pre>\n\n<p>Then count without unnecessary part:</p>\n\n<pre><code>SELECT COUNT(*)\nFROM Person\nJOIN Job ON Job.Id = Person.Job_Id\nWHERE Job.Name = 'WEB Developer'\n</code></pre>\n"
},
{
"answer_id": 55708509,
"author": "Madhur Bhaiya",
"author_id": 2469308,
"author_profile": "https://Stackoverflow.com/users/2469308",
"pm_score": 5,
"selected": false,
"text": "<p>MySQL has started deprecating <a href=\"https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_found-rows\" rel=\"noreferrer\"><code>SQL_CALC_FOUND_ROWS</code></a> functionality with version 8.0.17 onwards.</p>\n\n<p>So, it is <strong>always preferred</strong> to consider executing your query with <code>LIMIT</code>, and then a second query with <code>COUNT(*)</code> and without <code>LIMIT</code> to determine whether there are additional rows.</p>\n\n<p>From <a href=\"https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_found-rows\" rel=\"noreferrer\">docs</a>:</p>\n\n<blockquote>\n <p>The SQL_CALC_FOUND_ROWS query modifier and accompanying FOUND_ROWS()\n function are deprecated as of MySQL 8.0.17 and will be removed in a\n future MySQL version.</p>\n \n <p>COUNT(*) is subject to certain optimizations. SQL_CALC_FOUND_ROWS\n causes some optimizations to be disabled.</p>\n \n <p>Use these queries instead:</p>\n\n<pre><code>SELECT * FROM tbl_name WHERE id > 100 LIMIT 10;\nSELECT COUNT(*) WHERE id > 100;\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>Also, <code>SQL_CALC_FOUND_ROWS</code> has been observed to having more issues generally, as explained in the <a href=\"https://dev.mysql.com/worklog/task/?id=12615\" rel=\"noreferrer\">MySQL WL# 12615</a> : </p>\n\n<blockquote>\n <p>SQL_CALC_FOUND_ROWS has a number of problems. First of all, it's slow.\n Frequently, it would be cheaper to run the query with LIMIT and then a\n separate SELECT COUNT(<em>) for the same query, since COUNT(</em>) can make\n use of optimizations that can't be done when searching for the entire\n result set (e.g. filesort can be skipped for COUNT(*), whereas with\n CALC_FOUND_ROWS, we must disable some filesort optimizations to\n guarantee the right result)</p>\n \n <p>More importantly, it has very unclear semantics in a number of\n situations. In particular, when a query has multiple query blocks\n (e.g. with UNION), there's simply no way to calculate the number of\n “would-have-been” rows at the same time as producing a valid query. As\n the iterator executor is progressing towards these kinds of queries,\n it is genuinely difficult to try to retain the same semantics.\n Furthermore, if there are multiple LIMITs in the query (e.g. for\n derived tables), it's not necessarily clear to which of them\n SQL_CALC_FOUND_ROWS should refer to. Thus, such nontrivial queries\n will necessarily get different semantics in the iterator executor\n compared to what they had before.</p>\n \n <p>Finally, most of the use cases where SQL_CALC_FOUND_ROWS would seem\n useful should simply be solved by other mechanisms than LIMIT/OFFSET.\n E.g., a phone book should be paginated by letter (both in terms of UX\n and in terms of index use), not by record number. Discussions are\n increasingly infinite-scroll ordered by date (again allowing index\n use), not by paginated by post number. And so on.</p>\n</blockquote>\n"
},
{
"answer_id": 55909522,
"author": "Code4R7",
"author_id": 7740888,
"author_profile": "https://Stackoverflow.com/users/7740888",
"pm_score": 2,
"selected": false,
"text": "<p>There are other options for you to benchmark:</p>\n\n<p><strong>1.)</strong> A window function will return the actual size directly (tested in MariaDB):</p>\n\n<pre><code>SELECT \n `mytable`.*,\n COUNT(*) OVER() AS `total_count`\nFROM `mytable`\nORDER BY `mycol`\nLIMIT 10, 20\n</code></pre>\n\n<p><strong>2.)</strong> Thinking out of the box, most of the time users don't need to know the <em>EXACT</em> size of the table, an approximate is often good enough.</p>\n\n<pre><code>SELECT `TABLE_ROWS` AS `rows_approx`\nFROM `INFORMATION_SCHEMA`.`TABLES`\nWHERE `TABLE_SCHEMA` = DATABASE()\n AND `TABLE_TYPE` = \"BASE TABLE\"\n AND `TABLE_NAME` = ?\n</code></pre>\n"
},
{
"answer_id": 69598853,
"author": "Ja Loc",
"author_id": 4678594,
"author_profile": "https://Stackoverflow.com/users/4678594",
"pm_score": 0,
"selected": false,
"text": "<p>Simple example on table with 2.000.000 rows and query like this :</p>\n<pre><code>select fieldname \nfrom table_add \nwhere \ndescryption_per like '%marihuana%' \nor addiction_per like '%alkohol%';\n</code></pre>\n<p>it is a full table scan every query - so it take time x 2.\nI mean "select count(*) from .....</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6681/"
] |
When you limit the number of rows to be returned by a SQL query, usually used in paging, there are two methods to determine the total number of records:
### Method 1
Include the `SQL_CALC_FOUND_ROWS` option in the original `SELECT`, and then get the total number of rows by running `SELECT FOUND_ROWS()`:
```
SELECT SQL_CALC_FOUND_ROWS * FROM table WHERE id > 100 LIMIT 10;
SELECT FOUND_ROWS();
```
### Method 2
Run the query normally, and then get the total number of rows by running `SELECT COUNT(*)`
```
SELECT * FROM table WHERE id > 100 LIMIT 10;
SELECT COUNT(*) FROM table WHERE id > 100;
```
**Which method is the best / fastest?**
|
It depends. See the MySQL Performance Blog post on this subject: [To `SQL_CALC_FOUND_ROWS` or not to `SQL_CALC_FOUND_ROWS`?](https://www.percona.com/blog/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/)
Just a quick summary: Peter says that it depends on your indexes and other factors. Many of the comments to the post seem to say that `SQL_CALC_FOUND_ROWS` is almost always slower - sometimes up to 10x slower - than running two queries.
|
186,606 |
<p>Can i override fetchall method in a model? I need to check sth everytime fetchAll is called. The model extends Zend_db_table_abstract</p>
|
[
{
"answer_id": 198102,
"author": "Kieran Hall",
"author_id": 6085,
"author_profile": "https://Stackoverflow.com/users/6085",
"pm_score": 3,
"selected": false,
"text": "<p>To override this method you would need to subclass the Zend_Db_Table_Abstract. Like so:</p>\n\n<pre><code><?php\nabstract class My_Db_Table_Abstract extends Zend_Db_Table_Abstract\n{\n ...\n\n public function fetchAll($where, $order)\n {\n ...\n }\n\n ...\n}\n</code></pre>\n\n<p>Then make sure your models extend My_Db_Table_Abstract instead. This way, you will always inherit your overridden fetchAll method.</p>\n"
},
{
"answer_id": 229727,
"author": "Andrew Taylor",
"author_id": 1776,
"author_profile": "https://Stackoverflow.com/users/1776",
"pm_score": 0,
"selected": false,
"text": "<p>Yes. Just define a new fetchAll() method in your model with the same construction as the Zend_db_table_abstract method (ie same input / output) then at the end of your method call the parent method:</p>\n\n<p>parent::fetchAll($params)</p>\n\n<p>Andrew</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24789/"
] |
Can i override fetchall method in a model? I need to check sth everytime fetchAll is called. The model extends Zend\_db\_table\_abstract
|
To override this method you would need to subclass the Zend\_Db\_Table\_Abstract. Like so:
```
<?php
abstract class My_Db_Table_Abstract extends Zend_Db_Table_Abstract
{
...
public function fetchAll($where, $order)
{
...
}
...
}
```
Then make sure your models extend My\_Db\_Table\_Abstract instead. This way, you will always inherit your overridden fetchAll method.
|
186,622 |
<ol>
<li>How precise is the VB6 <code>Date</code> data type (by way of fractions of a second)?</li>
<li>How to format it to show fractions of a second?</li>
</ol>
<p>I'm revisiting VB6 after many years absence, and for the life of me can't remember the things I used to know. I considered putting a <a href="/questions/tagged/memory-leak" class="post-tag" title="show questions tagged 'memory-leak'" rel="tag">memory-leak</a> tag on this, because my memory leaked (hur hur hur).</p>
<p>I found this API call afterwards, and it seems to work:</p>
<pre><code>Declare Sub GetSystemTime Lib "kernel32.dll" (lpSystemTime As SystemTime)
Public Type SystemTime
Year As Integer
Month As Integer
DayOfWeek As Integer
Day As Integer
Hour As Integer
Minute As Integer
Second As Integer
Milliseconds As Integer
End Type
</code></pre>
|
[
{
"answer_id": 186669,
"author": "dummy",
"author_id": 6297,
"author_profile": "https://Stackoverflow.com/users/6297",
"pm_score": 1,
"selected": false,
"text": "<p>I think that the Date Datatype in VB6 can not handle fractions of a second.</p>\n"
},
{
"answer_id": 186675,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 3,
"selected": true,
"text": "<p>1) Seconds only, and</p>\n\n<p>2) There's no way.</p>\n"
},
{
"answer_id": 187052,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>Date</code> data type is based on the <code>Double</code> data type with range checking (min/max Date values) plus a considered epoch. In other words, there's nothing very special about it, especially considering VBA is not a strongly typed language.</p>\n\n<p>If you think of time in a continuum (and IMO you should) then a <code>Double</code> is a good fit. The precision for double precision floating point where one day = 1 (integer) is effectively nine decimal places. So a value of type <code>Double</code> (and therefore of type <code>Date</code>) can comfortably accommodate subsecond values.</p>\n\n<p>However, the problem you face is that temporal functions within VBA (<code>Now</code>, <code>DateSerial</code>, <code>DateDiff</code>, <code>DateAdd</code> etc) have a minimum granularity of <strong>one second</strong>. If you use them with your date values stored as <code>Double</code> with subsecond precision, you will experience rounding to one second. Ditto for user controls etc written for VBA6.</p>\n\n<p>You <em>could</em> write your own implementation of the temporal functions your require, of course (I recall having to implement wrapper classes for <code>StdDataFormat</code> in order to read/write subsecond SQL Server values without rounding into a MS Data Grid in in VBA) but it will begin to feel like you are rolling your own temporal data type (ouch!)</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18797/"
] |
1. How precise is the VB6 `Date` data type (by way of fractions of a second)?
2. How to format it to show fractions of a second?
I'm revisiting VB6 after many years absence, and for the life of me can't remember the things I used to know. I considered putting a [memory-leak](/questions/tagged/memory-leak "show questions tagged 'memory-leak'") tag on this, because my memory leaked (hur hur hur).
I found this API call afterwards, and it seems to work:
```
Declare Sub GetSystemTime Lib "kernel32.dll" (lpSystemTime As SystemTime)
Public Type SystemTime
Year As Integer
Month As Integer
DayOfWeek As Integer
Day As Integer
Hour As Integer
Minute As Integer
Second As Integer
Milliseconds As Integer
End Type
```
|
1) Seconds only, and
2) There's no way.
|
186,631 |
<p>I have a WCF service and I want to expose it as both a RESTfull service and as a SOAP service.
Anyone has done something like this before?</p>
|
[
{
"answer_id": 186695,
"author": "Ray Lu",
"author_id": 11413,
"author_profile": "https://Stackoverflow.com/users/11413",
"pm_score": 10,
"selected": true,
"text": "<p>You can expose the service in two different endpoints.\nthe SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration</p>\n\n<pre><code><endpointBehaviors>\n <behavior name=\"jsonBehavior\">\n <enableWebScript/>\n </behavior>\n</endpointBehaviors>\n</code></pre>\n\n<p>An example of endpoint configuration in your scenario is </p>\n\n<pre><code><services>\n <service name=\"TestService\">\n <endpoint address=\"soap\" binding=\"basicHttpBinding\" contract=\"ITestService\"/>\n <endpoint address=\"json\" binding=\"webHttpBinding\" behaviorConfiguration=\"jsonBehavior\" contract=\"ITestService\"/>\n </service>\n</services>\n</code></pre>\n\n<p>so, the service will be available at</p>\n\n<ul>\n<li><a href=\"http://www.example.com/soap\" rel=\"noreferrer\">http://www.example.com/soap</a></li>\n<li><a href=\"http://www.example.com/json\" rel=\"noreferrer\">http://www.example.com/json</a></li>\n</ul>\n\n<p>Apply [WebGet] to the operation contract to make it RESTful.\ne.g.</p>\n\n<pre><code>public interface ITestService\n{\n [OperationContract]\n [WebGet]\n string HelloWorld(string text)\n}\n</code></pre>\n\n<p>Note, if the REST service is not in JSON, parameters of the operations can not contain complex type.</p>\n\n<h2>Reply to the post for SOAP and RESTful POX(XML)</h2>\n\n<p>For plain old XML as return format, this is an example that would work both for SOAP and XML.</p>\n\n<pre><code>[ServiceContract(Namespace = \"http://test\")]\npublic interface ITestService\n{\n [OperationContract]\n [WebGet(UriTemplate = \"accounts/{id}\")]\n Account[] GetAccount(string id);\n}\n</code></pre>\n\n<p><strong>POX behavior for REST</strong> Plain Old XML</p>\n\n<pre><code><behavior name=\"poxBehavior\">\n <webHttp/>\n</behavior>\n</code></pre>\n\n<p><strong>Endpoints</strong></p>\n\n<pre><code><services>\n <service name=\"TestService\">\n <endpoint address=\"soap\" binding=\"basicHttpBinding\" contract=\"ITestService\"/>\n <endpoint address=\"xml\" binding=\"webHttpBinding\" behaviorConfiguration=\"poxBehavior\" contract=\"ITestService\"/>\n </service>\n</services>\n</code></pre>\n\n<p>Service will be available at</p>\n\n<ul>\n<li><a href=\"http://www.example.com/soap\" rel=\"noreferrer\">http://www.example.com/soap</a></li>\n<li><a href=\"http://www.example.com/xml\" rel=\"noreferrer\">http://www.example.com/xml</a></li>\n</ul>\n\n<p><strong>REST request</strong>\ntry it in browser,</p>\n\n<blockquote>\n <p><a href=\"http://www.example.com/xml/accounts/A123\" rel=\"noreferrer\">http://www.example.com/xml/accounts/A123</a></p>\n</blockquote>\n\n<p><strong>SOAP request</strong>\nclient endpoint configuration for SOAP service after adding the service reference,</p>\n\n<pre><code> <client>\n <endpoint address=\"http://www.example.com/soap\" binding=\"basicHttpBinding\"\n contract=\"ITestService\" name=\"BasicHttpBinding_ITestService\" />\n </client>\n</code></pre>\n\n<p>in C#</p>\n\n<pre><code>TestServiceClient client = new TestServiceClient();\nclient.GetAccount(\"A123\");\n</code></pre>\n\n<p>Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working.</p>\n"
},
{
"answer_id": 2295887,
"author": "Tuomas Hietanen",
"author_id": 17791,
"author_profile": "https://Stackoverflow.com/users/17791",
"pm_score": 5,
"selected": false,
"text": "<p>This post has already a very good answer by \"Community wiki\" and I also recommend to look at Rick Strahl's Web Blog, there are many good posts about WCF Rest like <a href=\"http://west-wind.com/weblog/posts/896411.aspx\" rel=\"noreferrer\">this</a>.</p>\n\n<p>I used both to get this kind of MyService-service... Then I can use the REST-interface from jQuery or SOAP from Java.</p>\n\n<p>This is from my Web.Config:</p>\n\n<pre><code><system.serviceModel>\n <services>\n <service name=\"MyService\" behaviorConfiguration=\"MyServiceBehavior\">\n <endpoint name=\"rest\" address=\"\" binding=\"webHttpBinding\" contract=\"MyService\" behaviorConfiguration=\"restBehavior\"/>\n <endpoint name=\"mex\" address=\"mex\" binding=\"mexHttpBinding\" contract=\"MyService\"/>\n <endpoint name=\"soap\" address=\"soap\" binding=\"basicHttpBinding\" contract=\"MyService\"/>\n </service>\n </services>\n <behaviors>\n <serviceBehaviors>\n <behavior name=\"MyServiceBehavior\">\n <serviceMetadata httpGetEnabled=\"true\"/>\n <serviceDebug includeExceptionDetailInFaults=\"true\" />\n </behavior>\n </serviceBehaviors>\n <endpointBehaviors>\n <behavior name=\"restBehavior\">\n <webHttp/>\n </behavior>\n </endpointBehaviors>\n </behaviors>\n</system.serviceModel>\n</code></pre>\n\n<p>And this is my service-class (.svc-codebehind, no interfaces required):</p>\n\n<pre><code> /// <summary> MyService documentation here ;) </summary>\n[ServiceContract(Name = \"MyService\", Namespace = \"http://myservice/\", SessionMode = SessionMode.NotAllowed)]\n//[ServiceKnownType(typeof (IList<MyDataContractTypes>))]\n[ServiceBehavior(Name = \"MyService\", Namespace = \"http://myservice/\")]\npublic class MyService\n{\n [OperationContract(Name = \"MyResource1\")]\n [WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = \"MyXmlResource/{key}\")]\n public string MyResource1(string key)\n {\n return \"Test: \" + key;\n }\n\n [OperationContract(Name = \"MyResource2\")]\n [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = \"MyJsonResource/{key}\")]\n public string MyResource2(string key)\n {\n return \"Test: \" + key;\n }\n}\n</code></pre>\n\n<p>Actually I use only Json or Xml but those both are here for a demo purpose. Those are GET-requests to get data. To insert data I would use method with attributes:</p>\n\n<pre><code>[OperationContract(Name = \"MyResourceSave\")]\n[WebInvoke(Method = \"POST\", ResponseFormat = WebMessageFormat.Json, UriTemplate = \"MyJsonResource\")]\npublic string MyResourceSave(string thing){\n //...\n</code></pre>\n"
},
{
"answer_id": 3508407,
"author": "mythz",
"author_id": 85785,
"author_profile": "https://Stackoverflow.com/users/85785",
"pm_score": 5,
"selected": false,
"text": "<p>If you only want to develop a single web service and have it hosted on many different endpoints (i.e. SOAP + REST, with XML, JSON, CSV, HTML outputes). You should also consider using <strong><a href=\"http://www.servicestack.net\" rel=\"noreferrer\">ServiceStack</a></strong> which I've built for exactly this purpose where every service you develop is automatically available on on both SOAP and REST endpoints out-of-the-box without any configuration required.</p>\n\n<p>The <a href=\"http://www.servicestack.net/ServiceStack.Hello/\" rel=\"noreferrer\">Hello World</a> example shows how to create a simple with service with just (no config required):</p>\n\n<pre><code>public class Hello {\n public string Name { get; set; }\n}\n\npublic class HelloResponse {\n public string Result { get; set; }\n}\n\npublic class HelloService : IService\n{\n public object Any(Hello request)\n {\n return new HelloResponse { Result = \"Hello, \" + request.Name };\n }\n}\n</code></pre>\n\n<p>No other configuration is required, and this service is immediately available with REST in:</p>\n\n<ul>\n<li>SOAP</li>\n<li><a href=\"http://www.servicestack.net/ServiceStack.Hello/hello/World!?format=xml\" rel=\"noreferrer\">XML</a></li>\n<li><a href=\"http://www.servicestack.net/ServiceStack.Hello/hello/World!?format=json\" rel=\"noreferrer\">JSON</a></li>\n<li><a href=\"http://www.servicestack.net/ServiceStack.Hello/hello/World!\" rel=\"noreferrer\">HTML</a></li>\n</ul>\n\n<p>It also comes in-built with <a href=\"https://github.com/ServiceStack/ServiceStack/wiki/HTML5ReportFormat\" rel=\"noreferrer\">a friendly HTML output</a> (when called with a HTTP client that has <strong>Accept:text/html</strong> e.g a browser) so you're able to better visualize the output of your services.</p>\n\n<p>Handling different REST verbs are also as trivial, here's a complete REST-service CRUD app in 1 page of C# (less than it would take to configure WCF ;):</p>\n\n<ul>\n<li><a href=\"http://www.servicestack.net/Backbone.Todos/\" rel=\"noreferrer\">Front-end TODO applicaiton</a></li>\n<li><a href=\"https://github.com/ServiceStack/ServiceStack.Examples/blob/master/src/Backbone.Todos/Global.asax.cs\" rel=\"noreferrer\">Back-end REST Service implementation</a></li>\n</ul>\n"
},
{
"answer_id": 13348834,
"author": "FMFF",
"author_id": 304661,
"author_profile": "https://Stackoverflow.com/users/304661",
"pm_score": 3,
"selected": false,
"text": "<p>MSDN seems to have an article for this now: </p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/bb412196(v=vs.110).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/bb412196(v=vs.110).aspx</a></p>\n\n<p>Intro: </p>\n\n<blockquote>\n <p>By default, Windows Communication Foundation (WCF) makes endpoints available only to SOAP clients. In How to: Create a Basic WCF Web HTTP Service, an endpoint is made available to non-SOAP clients. There may be times when you want to make the same contract available both ways, as a Web endpoint and as a SOAP endpoint. This topic shows an example of how to do this.</p>\n</blockquote>\n"
},
{
"answer_id": 48614701,
"author": "Jailson Evora",
"author_id": 7002459,
"author_profile": "https://Stackoverflow.com/users/7002459",
"pm_score": 2,
"selected": false,
"text": "<p>We must define the behavior configuration to <strong>REST</strong> endpoint</p>\n\n<pre><code><endpointBehaviors>\n <behavior name=\"restfulBehavior\">\n <webHttp defaultOutgoingResponseFormat=\"Json\" defaultBodyStyle=\"Wrapped\" automaticFormatSelectionEnabled=\"False\" />\n </behavior>\n</endpointBehaviors>\n</code></pre>\n\n<p>and also to a service </p>\n\n<pre><code><serviceBehaviors>\n <behavior>\n <serviceMetadata httpGetEnabled=\"true\" httpsGetEnabled=\"true\" />\n <serviceDebug includeExceptionDetailInFaults=\"false\" />\n </behavior>\n</serviceBehaviors>\n</code></pre>\n\n<p>After the behaviors, next step is the bindings. For example basicHttpBinding to <strong>SOAP</strong> endpoint and webHttpBinding to <strong>REST</strong>.</p>\n\n<pre><code><bindings>\n <basicHttpBinding>\n <binding name=\"soapService\" />\n </basicHttpBinding>\n <webHttpBinding>\n <binding name=\"jsonp\" crossDomainScriptAccessEnabled=\"true\" />\n </webHttpBinding>\n</bindings>\n</code></pre>\n\n<p>Finally we must define the 2 endpoint in the service definition. Attention for the address=\"\" of endpoint, where to REST service is not necessary nothing.</p>\n\n<pre><code><services>\n <service name=\"ComposerWcf.ComposerService\">\n <endpoint address=\"\" behaviorConfiguration=\"restfulBehavior\" binding=\"webHttpBinding\" bindingConfiguration=\"jsonp\" name=\"jsonService\" contract=\"ComposerWcf.Interface.IComposerService\" />\n <endpoint address=\"soap\" binding=\"basicHttpBinding\" name=\"soapService\" contract=\"ComposerWcf.Interface.IComposerService\" />\n <endpoint address=\"mex\" binding=\"mexHttpBinding\" name=\"metadata\" contract=\"IMetadataExchange\" />\n </service>\n</services>\n</code></pre>\n\n<p>In Interface of the service we define the operation with its attributes. </p>\n\n<pre><code>namespace ComposerWcf.Interface\n{\n [ServiceContract]\n public interface IComposerService\n {\n [OperationContract]\n [WebInvoke(Method = \"GET\", UriTemplate = \"/autenticationInfo/{app_id}/{access_token}\", ResponseFormat = WebMessageFormat.Json,\n RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]\n Task<UserCacheComplexType_RootObject> autenticationInfo(string app_id, string access_token);\n }\n}\n</code></pre>\n\n<p>Joining all parties, this will be our WCF system.serviceModel definition.</p>\n\n<pre><code><system.serviceModel>\n\n <behaviors>\n <endpointBehaviors>\n <behavior name=\"restfulBehavior\">\n <webHttp defaultOutgoingResponseFormat=\"Json\" defaultBodyStyle=\"Wrapped\" automaticFormatSelectionEnabled=\"False\" />\n </behavior>\n </endpointBehaviors>\n <serviceBehaviors>\n <behavior>\n <serviceMetadata httpGetEnabled=\"true\" httpsGetEnabled=\"true\" />\n <serviceDebug includeExceptionDetailInFaults=\"false\" />\n </behavior>\n </serviceBehaviors>\n </behaviors>\n\n <bindings>\n <basicHttpBinding>\n <binding name=\"soapService\" />\n </basicHttpBinding>\n <webHttpBinding>\n <binding name=\"jsonp\" crossDomainScriptAccessEnabled=\"true\" />\n </webHttpBinding>\n </bindings>\n\n <protocolMapping>\n <add binding=\"basicHttpsBinding\" scheme=\"https\" />\n </protocolMapping>\n\n <serviceHostingEnvironment aspNetCompatibilityEnabled=\"true\" multipleSiteBindingsEnabled=\"true\" />\n\n <services>\n <service name=\"ComposerWcf.ComposerService\">\n <endpoint address=\"\" behaviorConfiguration=\"restfulBehavior\" binding=\"webHttpBinding\" bindingConfiguration=\"jsonp\" name=\"jsonService\" contract=\"ComposerWcf.Interface.IComposerService\" />\n <endpoint address=\"soap\" binding=\"basicHttpBinding\" name=\"soapService\" contract=\"ComposerWcf.Interface.IComposerService\" />\n <endpoint address=\"mex\" binding=\"mexHttpBinding\" name=\"metadata\" contract=\"IMetadataExchange\" />\n </service>\n </services>\n\n</system.serviceModel>\n</code></pre>\n\n<p>To test the both endpoint, we can use <strong>WCFClient</strong> to <strong>SOAP</strong> and <strong>PostMan</strong> to <strong>REST</strong>.</p>\n"
},
{
"answer_id": 49169251,
"author": "Nayas Subramanian",
"author_id": 4315441,
"author_profile": "https://Stackoverflow.com/users/4315441",
"pm_score": 0,
"selected": false,
"text": "<p>This is what i did to make it work. Make sure you put<br>\n<strong>webHttp automaticFormatSelectionEnabled=\"true\"</strong> inside endpoint behaviour.</p>\n\n<pre><code>[ServiceContract]\npublic interface ITestService\n{\n\n [WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = \"/product\", ResponseFormat = WebMessageFormat.Json)]\n string GetData();\n}\n\npublic class TestService : ITestService\n{\n public string GetJsonData()\n {\n return \"I am good...\";\n }\n}\n</code></pre>\n\n<p>Inside service model</p>\n\n<pre><code> <service name=\"TechCity.Business.TestService\">\n\n <endpoint address=\"soap\" binding=\"basicHttpBinding\" name=\"SoapTest\"\n bindingName=\"BasicSoap\" contract=\"TechCity.Interfaces.ITestService\" />\n <endpoint address=\"mex\"\n contract=\"IMetadataExchange\" binding=\"mexHttpBinding\"/>\n <endpoint behaviorConfiguration=\"jsonBehavior\" binding=\"webHttpBinding\"\n name=\"Http\" contract=\"TechCity.Interfaces.ITestService\" />\n <host>\n <baseAddresses>\n <add baseAddress=\"http://localhost:8739/test\" />\n </baseAddresses>\n </host>\n </service>\n</code></pre>\n\n<p>EndPoint Behaviour</p>\n\n<pre><code> <endpointBehaviors>\n <behavior name=\"jsonBehavior\">\n <webHttp automaticFormatSelectionEnabled=\"true\" />\n <!-- use JSON serialization -->\n </behavior>\n </endpointBehaviors>\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15314/"
] |
I have a WCF service and I want to expose it as both a RESTfull service and as a SOAP service.
Anyone has done something like this before?
|
You can expose the service in two different endpoints.
the SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration
```
<endpointBehaviors>
<behavior name="jsonBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
```
An example of endpoint configuration in your scenario is
```
<services>
<service name="TestService">
<endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
<endpoint address="json" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="ITestService"/>
</service>
</services>
```
so, the service will be available at
* <http://www.example.com/soap>
* <http://www.example.com/json>
Apply [WebGet] to the operation contract to make it RESTful.
e.g.
```
public interface ITestService
{
[OperationContract]
[WebGet]
string HelloWorld(string text)
}
```
Note, if the REST service is not in JSON, parameters of the operations can not contain complex type.
Reply to the post for SOAP and RESTful POX(XML)
-----------------------------------------------
For plain old XML as return format, this is an example that would work both for SOAP and XML.
```
[ServiceContract(Namespace = "http://test")]
public interface ITestService
{
[OperationContract]
[WebGet(UriTemplate = "accounts/{id}")]
Account[] GetAccount(string id);
}
```
**POX behavior for REST** Plain Old XML
```
<behavior name="poxBehavior">
<webHttp/>
</behavior>
```
**Endpoints**
```
<services>
<service name="TestService">
<endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
<endpoint address="xml" binding="webHttpBinding" behaviorConfiguration="poxBehavior" contract="ITestService"/>
</service>
</services>
```
Service will be available at
* <http://www.example.com/soap>
* <http://www.example.com/xml>
**REST request**
try it in browser,
>
> <http://www.example.com/xml/accounts/A123>
>
>
>
**SOAP request**
client endpoint configuration for SOAP service after adding the service reference,
```
<client>
<endpoint address="http://www.example.com/soap" binding="basicHttpBinding"
contract="ITestService" name="BasicHttpBinding_ITestService" />
</client>
```
in C#
```
TestServiceClient client = new TestServiceClient();
client.GetAccount("A123");
```
Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working.
|
186,634 |
<p>I've got the following example running in a simple Silverlight page:</p>
<pre><code>public Page()
{
InitializeComponent();
InitializeOther();
}
private DoubleCollection dashes;
public DoubleCollection Dashes
{
get
{
//dashes = new DoubleCollection(); //works ok
//dashes.Add(2.0);
//dashes.Add(2.0);
if (dashes == null)
{
dashes = new DoubleCollection(); //causes exception
dashes.Add(2.0);
dashes.Add(2.0);
}
return dashes;
}
set
{
dashes = value;
}
}
private void InitializeOther()
{
Line line;
for (int i = 0; i < 10; i++)
{
line = new Line();
line.Stroke = new SolidColorBrush(Colors.Blue);
line.StrokeDashArray = Dashes; //exception thrown here
line.X1 = 10;
line.Y2 = 10;
line.X2 = 400;
line.Y2 = 10 + (i * 40);
canvas1.Children.Add(line);
}
}
</code></pre>
<p>The above code throws a System.ArgumentException on the line marked. One solution to the problem is also marked in the example.</p>
<p>Does anybody know if this problem is related to the fact that the property System.Windows.Shapes.Shape.StrokeDashArray is a dependency property? </p>
|
[
{
"answer_id": 187228,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 0,
"selected": false,
"text": "<p>The fact that StrokeDashArray is a dependency property shouldn't have anything to do with that code failing, since in XAML you are constantly setting dependency properties which are processed during parsing in InitializeComponent.</p>\n\n<p>I would say that the problem is that in your code you are reusing the same double collection for each line. Whenever you try to set a children to different parents SL fails with an argument exception, same when you reuse a resource that is not a style. Seems like each line needs its own DoubleCollection.</p>\n"
},
{
"answer_id": 187699,
"author": "Shunyata Kharg",
"author_id": 23724,
"author_profile": "https://Stackoverflow.com/users/23724",
"pm_score": 1,
"selected": false,
"text": "<p>Thank you for your answers and comments.</p>\n\n<p>I can run exactly the same code in a WPF application and it does not fail. For me, this is a clear indication that it is a Silverlight bug. I don't now think it has anything to do with dependency properties.</p>\n"
},
{
"answer_id": 188301,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 0,
"selected": false,
"text": "<p>I guess this real question is, what are you trying to do here? Do you really want all the lines to share the same DoubleCollection? Obviously you're probably doing a lot more and this is just a good way to share the question, but you should probably give each line its own collection. Pretty easy to do with:</p>\n\n<pre><code>line = new Line(); \nline.Stroke = new SolidColorBrush(Colors.Blue);\nline.StrokeDashArray = **new DoubleCollection() { 2.0, 2.0 };** \nline.X1 = 10; \n...\n</code></pre>\n\n<p>Do you really need to share the StoreDashArray between lines and then also expose it as a property on your class? I'd look into other ways of writing that code. </p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23724/"
] |
I've got the following example running in a simple Silverlight page:
```
public Page()
{
InitializeComponent();
InitializeOther();
}
private DoubleCollection dashes;
public DoubleCollection Dashes
{
get
{
//dashes = new DoubleCollection(); //works ok
//dashes.Add(2.0);
//dashes.Add(2.0);
if (dashes == null)
{
dashes = new DoubleCollection(); //causes exception
dashes.Add(2.0);
dashes.Add(2.0);
}
return dashes;
}
set
{
dashes = value;
}
}
private void InitializeOther()
{
Line line;
for (int i = 0; i < 10; i++)
{
line = new Line();
line.Stroke = new SolidColorBrush(Colors.Blue);
line.StrokeDashArray = Dashes; //exception thrown here
line.X1 = 10;
line.Y2 = 10;
line.X2 = 400;
line.Y2 = 10 + (i * 40);
canvas1.Children.Add(line);
}
}
```
The above code throws a System.ArgumentException on the line marked. One solution to the problem is also marked in the example.
Does anybody know if this problem is related to the fact that the property System.Windows.Shapes.Shape.StrokeDashArray is a dependency property?
|
Thank you for your answers and comments.
I can run exactly the same code in a WPF application and it does not fail. For me, this is a clear indication that it is a Silverlight bug. I don't now think it has anything to do with dependency properties.
|
186,648 |
<p>I'm working on a C++ library that (among other stuff) has functions to read config files; and I want to add tests for this. So far, this has lead me to create lots of valid and invalid config files, each with only a few lines that test one specific functionality. But it has now got very unwieldy, as there are so many files, and also lots of small C++ test apps. Somehow this seems wrong to me :-) so do you have hints how to organise all these tests, the test apps, and the test data?</p>
<p>Note: the library's public API itself is not easily testable (it requires a config file as parameter). The juicy, bug-prone methods for actually reading and interpreting config values are private, so I don't see a way to test them directly?</p>
<p>So: would you stick with testing against real files; and if so, how would you organise all these files and apps so that they are still maintainable?</p>
|
[
{
"answer_id": 186690,
"author": "richq",
"author_id": 4596,
"author_profile": "https://Stackoverflow.com/users/4596",
"pm_score": 3,
"selected": false,
"text": "<p>Perhaps the library could accept some kind of stream input, so you could pass in a string-like object and avoid all the input files? Or depending on the type of configuration, you could provide \"get/setAttribute()\" functions to directly, publicy, fiddle the parameters. If that is not really a design goal, then never mind. Data-driven unit tests are frowned upon in some places, but it is definitely better than nothing! I would probably lay out the code like this:</p>\n\n<pre><code> project/\n src/\n tests/\n test1/\n input/\n test2\n input/\n</code></pre>\n\n<p>In each testN directory you would have a cpp file associated to the config files in the input directory.</p>\n\n<p>Then, assuming you are using an xUnit-style test library (<a href=\"http://cppunit.sourceforge.net/\" rel=\"nofollow noreferrer\">cppunit</a>, <a href=\"http://code.google.com/p/googletest/\" rel=\"nofollow noreferrer\">googletest</a>, <a href=\"http://unittest-cpp.sourceforge.net/\" rel=\"nofollow noreferrer\">unittest++</a>, or whatever) you can add various testXXX() functions to a single class to test out associated groups of functionality. That way you could cut out part of the lots-of-little-programs problem by grouping at least some tests together.</p>\n\n<p>The only problem with this is if the library expects the config file to be called something specific, or to be in a specific place. That shouldn't be the case, but if it is would have to be worked around by copying your test file to the expected location.</p>\n\n<p>And don't worry about lots of tests cluttering your project up, if they are tucked away in a tests directory then they won't bother anyone.</p>\n"
},
{
"answer_id": 186704,
"author": "Anthony Cramp",
"author_id": 488,
"author_profile": "https://Stackoverflow.com/users/488",
"pm_score": 0,
"selected": false,
"text": "<p>In some tests I have done, I have actually used the test code to write the configuration files and then delete them after the test had made use of the file. It pads out the code somewhat and I have no idea if it is good practice, but it worked. If you happen to be using boost, then its filesystem module is useful for creating directories, navigating directories, and removing the files.</p>\n"
},
{
"answer_id": 186713,
"author": "Lev",
"author_id": 7224,
"author_profile": "https://Stackoverflow.com/users/7224",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with what @Richard Quirk said, but also you might want to make your test suite class a friend of the class you're testing and test its private functions.</p>\n"
},
{
"answer_id": 186778,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Part 1.</strong></p>\n\n<p>As Richard suggested, I'd take a look at the <a href=\"http://cpptest.sourceforge.net/\" rel=\"nofollow noreferrer\">CPPUnit</a> test framework. That will drive the location of your test framework to a certain extent.</p>\n\n<p>Your tests could be in a parallel directory located at a high-level, as per Richard's example, or in test subdirectories or test directories parallel with the area you want to test.</p>\n\n<p>Either way, please be consistent in the directory structure across the project! <strong>Especially</strong> in the case of tests being contained in a single high-level directory. </p>\n\n<p>There's nothing worse than having to maintain a mental mapping of source code in a location such as:</p>\n\n<pre><code>/project/src/component_a/piece_2/this_bit\n</code></pre>\n\n<p>and having the test(s) located somewhere such as:</p>\n\n<pre><code>/project/test/the_first_components/connection_tests/test_a\n</code></pre>\n\n<p>And I've worked on projects where someone did that!</p>\n\n<p>What a waste of wetware cycles! 8-O Talk about violating the Alexander's concept of Quality Without a Name.</p>\n\n<p>Much better is having your tests consistently located w.r.t. location of the source code under test:</p>\n\n<pre><code>/project/test/component_a/piece_2/this_bit/test_a\n</code></pre>\n\n<p><strong>Part 2</strong></p>\n\n<p>As for the API config files, make local copies of a reference config in each local test area as a part of the test env. setup that is run before executing a test. Don't sprinkle copies of config's (or data) all through your test tree.</p>\n\n<p>HTH.</p>\n\n<p>cheers,</p>\n\n<p>Rob</p>\n\n<p>BTW Really glad to see you asking this now when setting things up!</p>\n"
},
{
"answer_id": 186804,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 0,
"selected": false,
"text": "<p>For things like this I always have a small utility class that will load a config into a memory buffer and from there it gets fed into the actually config class. This means the real source doesn't matter - it could be a file or a db. For the unit-test it is hard coded one in a std::string that is then passed to the class for testing. You can simulate currup!pte3d data easily for testing failure paths.</p>\n\n<p>I use <a href=\"http://unittest-cpp.sourceforge.net/UnitTest++.html\" rel=\"nofollow noreferrer\">UnitTest++</a>. I have the tests as part of the src tree. So:</p>\n\n<pre><code>solution/project1/src <-- source code\nsolution/project1/src/tests <-- unit test code \nsolution/project2/src <-- source code\nsolution/project2/src/tests <-- unit test code \n</code></pre>\n"
},
{
"answer_id": 186884,
"author": "andreas buykx",
"author_id": 19863,
"author_profile": "https://Stackoverflow.com/users/19863",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming that you have control over the design of the library, I would expect that you'd be able to refactor such that you separate the concerns of actual file reading from interpreting it as a configuration file:</p>\n\n<ol>\n<li>class FileReader reads the file and produces a input stream, </li>\n<li>class ConfigFileInterpreter validates/interprets etc. the contents of the input stream </li>\n</ol>\n\n<p>Now to test FileReader you'd need a very small number of actual files (empty, binary, plain text etc.), and for ConfigFileInterpreter you would use a stub of the FileReader class that returns an input stream to read from. Now you can prepare all your various config situations as strings and you would not have to read so many files.</p>\n"
},
{
"answer_id": 742373,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You will not find a unit testing framework worse than CppUnit. Seriously, anybody who recommends CppUnit has not really taken a look at any of the competing frameworks.</p>\n\n<p>So yes, go for a unit testing franework, but do not use CppUnit.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148773/"
] |
I'm working on a C++ library that (among other stuff) has functions to read config files; and I want to add tests for this. So far, this has lead me to create lots of valid and invalid config files, each with only a few lines that test one specific functionality. But it has now got very unwieldy, as there are so many files, and also lots of small C++ test apps. Somehow this seems wrong to me :-) so do you have hints how to organise all these tests, the test apps, and the test data?
Note: the library's public API itself is not easily testable (it requires a config file as parameter). The juicy, bug-prone methods for actually reading and interpreting config values are private, so I don't see a way to test them directly?
So: would you stick with testing against real files; and if so, how would you organise all these files and apps so that they are still maintainable?
|
Perhaps the library could accept some kind of stream input, so you could pass in a string-like object and avoid all the input files? Or depending on the type of configuration, you could provide "get/setAttribute()" functions to directly, publicy, fiddle the parameters. If that is not really a design goal, then never mind. Data-driven unit tests are frowned upon in some places, but it is definitely better than nothing! I would probably lay out the code like this:
```
project/
src/
tests/
test1/
input/
test2
input/
```
In each testN directory you would have a cpp file associated to the config files in the input directory.
Then, assuming you are using an xUnit-style test library ([cppunit](http://cppunit.sourceforge.net/), [googletest](http://code.google.com/p/googletest/), [unittest++](http://unittest-cpp.sourceforge.net/), or whatever) you can add various testXXX() functions to a single class to test out associated groups of functionality. That way you could cut out part of the lots-of-little-programs problem by grouping at least some tests together.
The only problem with this is if the library expects the config file to be called something specific, or to be in a specific place. That shouldn't be the case, but if it is would have to be worked around by copying your test file to the expected location.
And don't worry about lots of tests cluttering your project up, if they are tucked away in a tests directory then they won't bother anyone.
|
186,649 |
<p>I have a class hierarchy as such:</p>
<pre><code> +-- VirtualNode
|
INode --+ +-- SiteNode
| |
+-- AbstractNode --+
|
+-- SiteSubNode
</code></pre>
<p>And a corresponding <code>NodeCollection</code> class that is build on <code>INode</code>. In order to display a <code>NodeCollection</code> I need to know the final type of each member. So I need a function like this</p>
<pre><code>foreach (INode n in myNodeCollection)
{
switch(n.GetType())
{
case(typeof(SiteNode)):
// Display n as SiteNode
}
}
</code></pre>
<p>Now, this is really not an object oriented way of doing it. <strong>Are there any patterns or recommended ways of doing the same thing, in your opinion?</strong></p>
<p><strong>EDIT</strong><br>
I already thought of adding a <code>Display</code> or <code>Render</code> method to the INode interface. That has the side effect of coupling the view to the model, which I would really like to avoid.</p>
|
[
{
"answer_id": 186654,
"author": "Andrew",
"author_id": 826,
"author_profile": "https://Stackoverflow.com/users/826",
"pm_score": 2,
"selected": true,
"text": "<p>What you're after is the <a href=\"http://en.wikipedia.org/wiki/Visitor_pattern\" rel=\"nofollow noreferrer\">visitor pattern</a>, I think.</p>\n"
},
{
"answer_id": 186703,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming\" rel=\"nofollow noreferrer\">Polymorphism:</a> </p>\n\n<p>When ever you have a select statement using the type of an object, it is a prime candidate for refactoring to polymorphism.</p>\n\n<p>Check out the book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201485672\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Refactoring</a> by Martin Fowler:</p>\n\n<p>\"One of the most obvious symptoms of object-oriented code is its comparative lack of switch (or\ncase) statements. The problem with switch statements is essentially that of duplication. Often you\nfind the same switch statement scattered about a program in different places. If you add a new\nclause to the switch, you have to find all these switch, statements and change them. The objectoriented\nnotion of polymorphism gives you an elegant way to deal with this problem.</p>\n\n<p>Most times you see a switch statement you should consider polymorphism. The issue is where\nthe polymorphism should occur. Often the switch statement switches on a type code. You want\nthe method or class that hosts the type code value. So use Extract Method to extract the switch\nstatement and then Move Method to get it onto the class where the polymorphism is needed. At\nthat point you have to decide whether to Replace Type Code with Subclasses or Replace\nType Code with State/Strategy. When you have set up the inheritance structure, you can use\nReplace Conditional with Polymorphism.\"</p>\n\n<p>Here is one approach to using polymorphism in your situation:</p>\n\n<ol>\n<li><p>Define an abstract method in\nAbstractNode named something like\nDisplay().</p></li>\n<li><p>Then actually implement Display() in\neach of the SiteNode and SiteSubNode\nclasses.</p></li>\n<li><p>Then, when you need to display these\nnodes, you could simply iterate\nthrough a collection containing\nitems of type AbstractNode and call\nDisplay() for each. </p></li>\n<li><p>The call to Display() will\nautomatically resolve to the actual\nconcrete implementation for the real\ntype of that item.</p></li>\n<li><p>Note: You could also move the\nDisplay() method from AbstractNode\nto the INode interface if\nVirtualNode is to be displayed.</p></li>\n</ol>\n"
},
{
"answer_id": 186724,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 0,
"selected": false,
"text": "<p>If you can change the INode interface - add a virtual method that returns the \"view\" and override it in the inherited classes.</p>\n\n<p>If you can't change the base interface - implement extension methods for each of the classes and have them return the \"view\" of for each particular class.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7028/"
] |
I have a class hierarchy as such:
```
+-- VirtualNode
|
INode --+ +-- SiteNode
| |
+-- AbstractNode --+
|
+-- SiteSubNode
```
And a corresponding `NodeCollection` class that is build on `INode`. In order to display a `NodeCollection` I need to know the final type of each member. So I need a function like this
```
foreach (INode n in myNodeCollection)
{
switch(n.GetType())
{
case(typeof(SiteNode)):
// Display n as SiteNode
}
}
```
Now, this is really not an object oriented way of doing it. **Are there any patterns or recommended ways of doing the same thing, in your opinion?**
**EDIT**
I already thought of adding a `Display` or `Render` method to the INode interface. That has the side effect of coupling the view to the model, which I would really like to avoid.
|
What you're after is the [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern), I think.
|
186,671 |
<p>What avenues are there for using an XSD to generate message instances? I seem to remember reading about generating classes from XSD, but can't find anything specific now. I know you can generate classes and datasets from XSD, but I'm looking for a pattern for automating the actual generation of the messages.</p>
<p>BTW, SO is my knowledge sharer of choice, not Google.</p>
|
[
{
"answer_id": 186684,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 2,
"selected": true,
"text": "<pre><code>xsd /c yourschema.xsd > yourschema.cs\n</code></pre>\n"
},
{
"answer_id": 526236,
"author": "ccook",
"author_id": 51275,
"author_profile": "https://Stackoverflow.com/users/51275",
"pm_score": 1,
"selected": false,
"text": "<p>You can also create an XSD from XML samples with xsd.exe. Start the visual studio command prompt and use it to create an xsd from an xml sample. Then you can, as leppie shows, use xsd.exe to create a typed data set from that XSD. I wouldn't recommend doing this blindly, but it can certainly help when using a third party xml service.</p>\n\n<p>XML -> XSD -> TypedDS by using xsd.exe.</p>\n"
},
{
"answer_id": 526288,
"author": "Aussie Craig",
"author_id": 58757,
"author_profile": "https://Stackoverflow.com/users/58757",
"pm_score": 2,
"selected": false,
"text": "<p>Visual Studio XSD should be the first port of call. It will generate classes which you can serialise and deserialize the xml documents to/from.</p>\n\n<p>XSD will work for \"simple\" schemas, there are plenty which it cannot cope with. </p>\n\n<p>NB: if you schema imports other schema files you need to include those schema files on the command line as well.</p>\n\n<p>Other code generation from schema files tools include XMLSpy, Enterprise Architect. Worth looking at if XSD fails your requirements.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
What avenues are there for using an XSD to generate message instances? I seem to remember reading about generating classes from XSD, but can't find anything specific now. I know you can generate classes and datasets from XSD, but I'm looking for a pattern for automating the actual generation of the messages.
BTW, SO is my knowledge sharer of choice, not Google.
|
```
xsd /c yourschema.xsd > yourschema.cs
```
|
186,693 |
<p>I'm trying to balance a set of currency values using vb.net. The totals for both these values is cast as a double. I'm getting rounding errors in some situations. </p>
<p>What's the best way to avoid this? Is there a type I can use in preference to double? How do I round the resultant value to two decimal places?</p>
<p>Here's my code - I probably don't need to show it, but just in case. </p>
<pre><code> Dim nInvValue As Double
Dim nCreditValue As Double
For Each oReferenceItem In oMatchInvoices
Dim nUnallocated As Double = oReferenceItem.DocumentOutstandingValue - oReferenceItem.DocumentAllocatedValue
If ((nUnallocated <> 0) And (sReferenceValue = oReferenceItem.InstrumentNo)) Then
iCount = iCount + 1
If (oReferenceItem.IsDebit) And (nUnallocated > 0) Then
nInvValue = nInvValue + nUnallocated
InvoiceList.Add(nUnallocated.ToString("c"), oReferenceItem.URN.ToString)
End If
If (oReferenceItem.IsCredit) And (nUnallocated < 0) Then
nCreditValue = nCreditValue - nUnallocated
CreditList.Add(nUnallocated.ToString("c"), oReferenceItem.URN.ToString)
End If
End If
Next
</code></pre>
|
[
{
"answer_id": 186697,
"author": "Inisheer",
"author_id": 2982,
"author_profile": "https://Stackoverflow.com/users/2982",
"pm_score": 2,
"selected": false,
"text": "<p>Try using the Decimal type.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.decimal.aspx\" rel=\"nofollow noreferrer\">MSDN - Decimal</a></p>\n"
},
{
"answer_id": 186705,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 4,
"selected": true,
"text": "<p>For financial calculations I believe that the current wisdom is to use Decimals instead of Doubles.</p>\n\n<p>You might be interested in this discussion <a href=\"https://stackoverflow.com/questions/4/decimal-vs-double\">Decimal Vs. Double</a>.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726/"
] |
I'm trying to balance a set of currency values using vb.net. The totals for both these values is cast as a double. I'm getting rounding errors in some situations.
What's the best way to avoid this? Is there a type I can use in preference to double? How do I round the resultant value to two decimal places?
Here's my code - I probably don't need to show it, but just in case.
```
Dim nInvValue As Double
Dim nCreditValue As Double
For Each oReferenceItem In oMatchInvoices
Dim nUnallocated As Double = oReferenceItem.DocumentOutstandingValue - oReferenceItem.DocumentAllocatedValue
If ((nUnallocated <> 0) And (sReferenceValue = oReferenceItem.InstrumentNo)) Then
iCount = iCount + 1
If (oReferenceItem.IsDebit) And (nUnallocated > 0) Then
nInvValue = nInvValue + nUnallocated
InvoiceList.Add(nUnallocated.ToString("c"), oReferenceItem.URN.ToString)
End If
If (oReferenceItem.IsCredit) And (nUnallocated < 0) Then
nCreditValue = nCreditValue - nUnallocated
CreditList.Add(nUnallocated.ToString("c"), oReferenceItem.URN.ToString)
End If
End If
Next
```
|
For financial calculations I believe that the current wisdom is to use Decimals instead of Doubles.
You might be interested in this discussion [Decimal Vs. Double](https://stackoverflow.com/questions/4/decimal-vs-double).
|
186,718 |
<p>I have some really complicated legacy code I've been working on that crashes when collecting big chunks of data. I've been unable to find the exact reason for the crashes and am trying different ways to solve it or at least recover nicely. The last thing I did was enclose the crashing code in a</p>
<pre><code>try
...
except
cleanup();
end;
</code></pre>
<p>just to make it behave. But the cleanup never gets done. Under what circumstances does an exception not get caught? This might be due to some memory overflow or something since the app is collecting quite a bit of data.</p>
<p>Oh and the exception I got before adding the <code>try</code> was "Access violation" (what else?) and the CPU window points to very low addresses. Any ideas or pointers would be much appreciated!</p>
|
[
{
"answer_id": 186739,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 4,
"selected": true,
"text": "<p>\"Very low address\" probably means that somebody tried to call a virtual method on an object that was not really there (i.e. was 'nil'). For example:</p>\n\n<p>TStringList(nil).Clear;</p>\n\n<p>The first part is very mysterious, though. I have no idea how that can happen.</p>\n\n<p>I think you should try to catch that exception with <a href=\"http://www.madshi.net/madExceptDescription.htm\" rel=\"nofollow noreferrer\">madExcept</a>. It has never failed me yet. (Disclaimer: I am not using D7.)</p>\n"
},
{
"answer_id": 186956,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 3,
"selected": false,
"text": "<p>A trashed stack or a stack overflow can both cause irreparable harm to the structures on the stack that structured exception handling (SEH) in Windows uses to find the actual exception handlers.</p>\n\n<p>If you have a buffer overflow in a buffer on the stack (e.g. a static array as a local variable but written beyond its end), and overwrite an exception record, then you can overwrite the \"next\" pointer, which points at the next exception record on the stack. If the pointer gets clobbered, there's nothing the OS can do to find the next exception handler and eventually reach your catch-all one.</p>\n\n<p>Stack overflows are different: they can prevent calling functions at all, since every function call requires at least one dword of stack space for the return address.</p>\n"
},
{
"answer_id": 188331,
"author": "Gustavo",
"author_id": 2015,
"author_profile": "https://Stackoverflow.com/users/2015",
"pm_score": 1,
"selected": false,
"text": "<p>I used to get this strange behabiour when calling some COM object that used a safecall calling convention. This object/method may raise an EOleException, not trapped by the usual try/except on the client code.\nYou should trap an EOleException and the handle it properly. </p>\n\n<pre><code>try\n...\nexcept\non E: EOleException do\n...\nend;\n</code></pre>\n\n<p>I don't know if it is the problem you are facing. But if it is, i recommend you to take a look at <a href=\"http://www.techvanguards.com/com/tutorials/tips.asp\" rel=\"nofollow noreferrer\">Implement error handling correctly</a>, a very clarifiyng post about exception handling in delphi.</p>\n\n<p>You can also enable your IDE Debug Options to stop on delhi exceptions e monitor the stack trace.</p>\n"
},
{
"answer_id": 188733,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 1,
"selected": false,
"text": "<p>I'll leave the reasons why the except might not work to <a href=\"https://stackoverflow.com/questions/186718/delphi-7-exception-not-caught#186956\">Barry</a>... </p>\n\n<p>But I strongly suggest a simple strategy to narrow down the area where it happens.\nCut the big chunk in smaller parts surrounded by</p>\n\n<pre><code>try\n OutputDebugString('entering part abc');\n ... // part abc code here\nexcept\n OutputDebugString('horror in part abc');\n raise;\nend;\n... \ntry\n OutputDebugString('entering in part xyz');\n ... // part xyz code here\nexcept\n OutputDebugString('horror in part xyz');\n raise;\nend;\n</code></pre>\n\n<p>and run your code with <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx\" rel=\"nofollow noreferrer\">DebugView</a> on the side... (works for apps without GUI as well like services).<br>\nYou'll see which part is executed and if the exceptions are caught there.</p>\n"
},
{
"answer_id": 189532,
"author": "X-Ray",
"author_id": 14031,
"author_profile": "https://Stackoverflow.com/users/14031",
"pm_score": 2,
"selected": false,
"text": "<p>you have a number of good answers. the wildest problems i've had to chase come from stack corruption issues like barry mentioned. i've seen stuff happen with the project's \"Memory sizes\" section on the linker page. i might be superstitious but it seemed like larger wasn't necessarily better. you might consider using the enhanced memory manager FastMM4--it's free & very helpful.</p>\n\n<p><a href=\"http://sourceforge.net/projects/fastmm/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/fastmm/</a></p>\n\n<p>i've used it with d7 and found some access to stale pointers and other evil things. </p>\n\n<p>you may also wish to create a way to track valid objects and or instrument the code in other ways to have the code checking itself as it works.</p>\n\n<p>when i'm seeing access to addresses like 0x00001000 or less, i think of access to a nil pointer. myStringList:=nil; myStringList.Clear;</p>\n\n<p>when i'm seeing access to other addresses with much larger numbers, i think of stale pointers.</p>\n\n<p>when things are strangely unstable & stack traces are proving to be nonsense and/or wildly varying, i know i have stack issues. one time it's in Controls.pas; next time it's in mmsys.pas, etc.</p>\n\n<p>using the wrong calling convention to a DLL can really mess up your stack as well. this is because of the parameter passing/releasing when calling/returning from the DLL.</p>\n\n<p>MadExcept will be helpful in finding the source of this, even if it shows nonsense...you'll win either way because you'll know where the problem is occurring or you'll know you have a stack issue.</p>\n\n<p>is there any testing framework you can put on it to exercise it? i've found that to be <em>very</em> powerful because it makes it entirely repeatable.</p>\n\n<p>i've fixed some pretty ugly problems this way.</p>\n"
},
{
"answer_id": 197944,
"author": "Steve",
"author_id": 22712,
"author_profile": "https://Stackoverflow.com/users/22712",
"pm_score": 0,
"selected": false,
"text": "<p>Is this perhaps a DLL or a COM object? If so, it is possible that the FPUExcpetion mask is being set by the host application to something different than Delphi is used to. An overflow, by default in Delphi produces an exception, but the FPUExcpetionmask can be set so that it doesn't, and the value is set to NAN. See the math.pas unit for more information on FPUExceptionmask </p>\n"
},
{
"answer_id": 291129,
"author": "Peter Turner",
"author_id": 1765,
"author_profile": "https://Stackoverflow.com/users/1765",
"pm_score": 0,
"selected": false,
"text": "<p>I've gotten exceptions in the initialization and finalization blocks of my code which madExcept doesn't even seem to even catch. This might occur if you're referencing external DLL's inside of that try block. I'm not certain of the reason. </p>\n\n<p>Actually (and thanks to @Gung for informing me of the worthlessness of my ancient answer), I read this recently in the ancient O'Reilly Delphi Tome. You should put SysUtils as the first (or second after your non-standard memory manager unit) in your main form's DPR so that it's resident in memory with all it's Exception Catching goodness. Otherwise, if it's loaded from some other unit, it will be unloaded with that unit too and you can kiss built in exception handling goodbye.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9077/"
] |
I have some really complicated legacy code I've been working on that crashes when collecting big chunks of data. I've been unable to find the exact reason for the crashes and am trying different ways to solve it or at least recover nicely. The last thing I did was enclose the crashing code in a
```
try
...
except
cleanup();
end;
```
just to make it behave. But the cleanup never gets done. Under what circumstances does an exception not get caught? This might be due to some memory overflow or something since the app is collecting quite a bit of data.
Oh and the exception I got before adding the `try` was "Access violation" (what else?) and the CPU window points to very low addresses. Any ideas or pointers would be much appreciated!
|
"Very low address" probably means that somebody tried to call a virtual method on an object that was not really there (i.e. was 'nil'). For example:
TStringList(nil).Clear;
The first part is very mysterious, though. I have no idea how that can happen.
I think you should try to catch that exception with [madExcept](http://www.madshi.net/madExceptDescription.htm). It has never failed me yet. (Disclaimer: I am not using D7.)
|
186,737 |
<p>I want to delete a folder that contains thousands of files and folders. If I use Windows Explorer to delete the folder it can take 10-15 minutes (not always, but often). Is there a faster way in Windows to delete folders? </p>
<p>Other details:</p>
<ul>
<li>I don't care about the recycle bin.</li>
<li>It's an NTFS drive.</li>
</ul>
|
[
{
"answer_id": 186748,
"author": "Stephen Denne",
"author_id": 11721,
"author_profile": "https://Stackoverflow.com/users/11721",
"pm_score": 10,
"selected": true,
"text": "<h3>Using Windows Command Prompt:</h3>\n<pre><code>rmdir /s /q folder\n</code></pre>\n<h3>Using Powershell:</h3>\n<pre><code>powershell -Command "Remove-Item -LiteralPath 'folder' -Force -Recurse"\n</code></pre>\n<p>Note that in more cases <code>del</code> and <code>rmdir</code> wil leave you with leftover files, where Powershell manages to delete the files.</p>\n"
},
{
"answer_id": 186758,
"author": "nicodemus13",
"author_id": 26463,
"author_profile": "https://Stackoverflow.com/users/26463",
"pm_score": 2,
"selected": false,
"text": "<p>use the command prompt, as suggested. I figured out why explorer is so slow a while ago, it gives you an estimate of how long it will take to delete the files/folders. To do this, it has to scan the number of items and the size. This takes ages, hence the ridiculous wait with large folders.</p>\n\n<p>Also, explorer will stop if there is a particular problem with a file,</p>\n"
},
{
"answer_id": 629219,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>and to delete a lot of folders, you could also create a batch file with the command spdenne posted. </p>\n\n<p>1) make a text file that has the following contents replacing the folder names in quotes with your folder names:</p>\n\n<pre><code>rmdir /s /q \"My Apps\" \nrmdir /s /q \"My Documents\" \nrmdir /s /q \"My Pictures\" \nrmdir /s /q \"My Work Files\"\n</code></pre>\n\n<p>2) save the batch file with a .bat extension (for example deletefiles.bat)<br>\n3) open a command prompt (Start > Run > Cmd) and execute the batch file. you can do this like so from the command prompt (substituting X for your drive letter):</p>\n\n<pre><code>X: \ndeletefiles.bat\n</code></pre>\n"
},
{
"answer_id": 901598,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>use <a href=\"http://www.ipmsg.org/tools/fastcopy.html.en\" rel=\"noreferrer\">fastcopy</a>, a free tool.\n it has a delete option that is a lot faster then the way windows deletes files.</p>\n"
},
{
"answer_id": 6208144,
"author": "Hugo",
"author_id": 724176,
"author_profile": "https://Stackoverflow.com/users/724176",
"pm_score": 10,
"selected": false,
"text": "<p>The worst way is to send to Recycle Bin: you still need to delete them. Next worst is shift+delete with Windows Explorer: it wastes loads of time checking the contents before starting deleting anything.</p>\n<p>Next best is to use <code>rmdir /s/q foldername</code> from the command line. <code>del /f/s/q foldername</code> is good too, but it leaves behind the directory structure.</p>\n<p>The best I've found is a two line batch file with a first pass to delete files and outputs to nul to avoid the overhead of writing to screen for every singe file. A second pass then cleans up the remaining directory structure:</p>\n<pre><code>del /f/s/q foldername > nul\nrmdir /s/q foldername\n</code></pre>\n<p>This is nearly three times faster than a single rmdir, based on time tests with a Windows XP encrypted disk, deleting ~30GB/1,000,000 files/15,000 folders: <code>rmdir</code> takes ~2.5 hours, <code>del+rmdir</code> takes ~53 minutes. More info at <a href=\"https://superuser.com/questions/19762/mass-deleting-files-in-windows/289399#289399\">Super User</a>.</p>\n<p>This is a regular task for me, so I usually move the stuff I need to delete to C:\\stufftodelete and have those <code>del+rmdir</code> commands in a deletestuff.bat batch file. This is scheduled to run at night, but sometimes I need to run it during the day so the quicker the better.</p>\n<p>Technet documentation for <code>del</code> command can be found <a href=\"https://technet.microsoft.com/en-us/library/cc771049(v=ws.11).aspx\" rel=\"noreferrer\">here</a>. Additional info on the parameters used above:</p>\n<ul>\n<li><code>/f</code> - Force (i.e. delete files even if they're read only)</li>\n<li><code>/s</code> - Recursive / Include Subfolders (this definition from <a href=\"https://ss64.com/nt/del.html\" rel=\"noreferrer\">SS64</a>, as technet simply states "specified files", which isn't helpful).</li>\n<li><code>/q</code> - Quiet (i.e. do not prompt user for confirmation)</li>\n</ul>\n<p>Documentation for <code>rmdir</code> <a href=\"https://technet.microsoft.com/en-us/library/cc726055(v=ws.11).aspx\" rel=\"noreferrer\">here</a>. Parameters are:</p>\n<ul>\n<li><code>/s</code> - Recursive (i.e. same as del's /s parameter)</li>\n<li><code>/q</code> - Quiet (i.e. same as del's /q parameter)</li>\n</ul>\n"
},
{
"answer_id": 6355510,
"author": "jeroen",
"author_id": 799281,
"author_profile": "https://Stackoverflow.com/users/799281",
"pm_score": -1,
"selected": false,
"text": "<p>Try <kbd>Shift</kbd> + <kbd>Delete</kbd>. Did 24.000 files in 2 minutes for me.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11766/"
] |
I want to delete a folder that contains thousands of files and folders. If I use Windows Explorer to delete the folder it can take 10-15 minutes (not always, but often). Is there a faster way in Windows to delete folders?
Other details:
* I don't care about the recycle bin.
* It's an NTFS drive.
|
### Using Windows Command Prompt:
```
rmdir /s /q folder
```
### Using Powershell:
```
powershell -Command "Remove-Item -LiteralPath 'folder' -Force -Recurse"
```
Note that in more cases `del` and `rmdir` wil leave you with leftover files, where Powershell manages to delete the files.
|
186,756 |
<p>How do I generate a range of consecutive numbers (one per line) from a MySQL query so that I can insert them into a table?</p>
<p>For example:</p>
<pre><code>nr
1
2
3
4
5
</code></pre>
<p>I would like to use only MySQL for this (not PHP or other languages).</p>
|
[
{
"answer_id": 186780,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "<pre><code>DECLARE i INT DEFAULT 0;\n\nWHILE i < 6 DO\n /* insert into table... */\n SET i = i + 1;\nEND WHILE;\n</code></pre>\n"
},
{
"answer_id": 186814,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 6,
"selected": true,
"text": "<p>If you need the records in a table and you want to avoid concurrency issues, here's how to do it.</p>\n\n<p>First you create a table in which to store your records</p>\n\n<pre><code>CREATE TABLE `incr` (\n `Id` int(11) NOT NULL auto_increment,\n PRIMARY KEY (`Id`)\n) ENGINE=MyISAM DEFAULT CHARSET=utf8;\n</code></pre>\n\n<p>Secondly create a stored procedure like this:</p>\n\n<pre><code>DELIMITER ;;\nCREATE PROCEDURE dowhile()\nBEGIN\n DECLARE v1 INT DEFAULT 5;\n WHILE v1 > 0 DO\n INSERT incr VALUES (NULL);\n SET v1 = v1 - 1;\n END WHILE;\nEND;;\nDELIMITER ;\n</code></pre>\n\n<p>Lastly call the SP:</p>\n\n<pre><code>CALL dowhile();\nSELECT * FROM incr;\n</code></pre>\n\n<p>Result</p>\n\n<pre><code>Id\n1\n2\n3\n4\n5\n</code></pre>\n"
},
{
"answer_id": 187410,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 6,
"selected": false,
"text": "<p>Here is one way to do it set-based without loops. This can also be made into a view for re-use. The example shows the generation of a sequence from 0 through 999, but of course, it may be modified to suit.</p>\n\n<pre><code>INSERT INTO\n myTable\n (\n nr\n )\nSELECT\n SEQ.SeqValue\nFROM\n(\nSELECT\n (HUNDREDS.SeqValue + TENS.SeqValue + ONES.SeqValue) SeqValue\nFROM\n (\n SELECT 0 SeqValue\n UNION ALL\n SELECT 1 SeqValue\n UNION ALL\n SELECT 2 SeqValue\n UNION ALL\n SELECT 3 SeqValue\n UNION ALL\n SELECT 4 SeqValue\n UNION ALL\n SELECT 5 SeqValue\n UNION ALL\n SELECT 6 SeqValue\n UNION ALL\n SELECT 7 SeqValue\n UNION ALL\n SELECT 8 SeqValue\n UNION ALL\n SELECT 9 SeqValue\n ) ONES\nCROSS JOIN\n (\n SELECT 0 SeqValue\n UNION ALL\n SELECT 10 SeqValue\n UNION ALL\n SELECT 20 SeqValue\n UNION ALL\n SELECT 30 SeqValue\n UNION ALL\n SELECT 40 SeqValue\n UNION ALL\n SELECT 50 SeqValue\n UNION ALL\n SELECT 60 SeqValue\n UNION ALL\n SELECT 70 SeqValue\n UNION ALL\n SELECT 80 SeqValue\n UNION ALL\n SELECT 90 SeqValue\n ) TENS\nCROSS JOIN\n (\n SELECT 0 SeqValue\n UNION ALL\n SELECT 100 SeqValue\n UNION ALL\n SELECT 200 SeqValue\n UNION ALL\n SELECT 300 SeqValue\n UNION ALL\n SELECT 400 SeqValue\n UNION ALL\n SELECT 500 SeqValue\n UNION ALL\n SELECT 600 SeqValue\n UNION ALL\n SELECT 700 SeqValue\n UNION ALL\n SELECT 800 SeqValue\n UNION ALL\n SELECT 900 SeqValue\n ) HUNDREDS\n) SEQ\n</code></pre>\n"
},
{
"answer_id": 8349837,
"author": "David Ehrmann",
"author_id": 1076480,
"author_profile": "https://Stackoverflow.com/users/1076480",
"pm_score": 6,
"selected": false,
"text": "<p>Here's a hardware engineer's version of <a href=\"https://stackoverflow.com/a/187410\">Pittsburgh DBA's solution</a>:</p>\n\n<pre><code>SELECT\n (TWO_1.SeqValue + TWO_2.SeqValue + TWO_4.SeqValue + TWO_8.SeqValue + TWO_16.SeqValue) SeqValue\nFROM\n (SELECT 0 SeqValue UNION ALL SELECT 1 SeqValue) TWO_1\n CROSS JOIN (SELECT 0 SeqValue UNION ALL SELECT 2 SeqValue) TWO_2\n CROSS JOIN (SELECT 0 SeqValue UNION ALL SELECT 4 SeqValue) TWO_4\n CROSS JOIN (SELECT 0 SeqValue UNION ALL SELECT 8 SeqValue) TWO_8\n CROSS JOIN (SELECT 0 SeqValue UNION ALL SELECT 16 SeqValue) TWO_16;\n</code></pre>\n"
},
{
"answer_id": 8497960,
"author": "JaredC",
"author_id": 339532,
"author_profile": "https://Stackoverflow.com/users/339532",
"pm_score": 5,
"selected": false,
"text": "<p>Let's say you want to insert numbers 1 through 100 into your table. As long as you have some other table that has at least that many rows (doesn't matter the content of the table), then this is my preferred method:</p>\n\n<pre><code>INSERT INTO pivot100 \nSELECT @ROW := @ROW + 1 AS ROW\n FROM someOtherTable t\n join (SELECT @ROW := 0) t2\n LIMIT 100\n;\n</code></pre>\n\n<p>Want a range that starts with something other than 1? Just change what @ROW gets set to on the join.</p>\n"
},
{
"answer_id": 21286493,
"author": "Jakob Eriksson",
"author_id": 956415,
"author_profile": "https://Stackoverflow.com/users/956415",
"pm_score": 3,
"selected": false,
"text": "<p>As you all understand, this is rather hacky so use with care</p>\n<pre><code>SELECT\n id % 12 + 1 as one_to_twelve\nFROM\n any_large_table\nGROUP BY\n one_to_twelve\n;\n</code></pre>\n"
},
{
"answer_id": 42613456,
"author": "Paul Spiegel",
"author_id": 5563083,
"author_profile": "https://Stackoverflow.com/users/5563083",
"pm_score": 1,
"selected": false,
"text": "<p>The \"shortest\" way i know (in MySQL) to create a table with a long sequence is to (cross) join an existing table with itself. Since any (common) MySQL server has the <code>information_schema.COLUMNS</code> table i would use it:</p>\n\n<pre><code>DROP TABLE IF EXISTS seq;\nCREATE TABLE seq (i MEDIUMINT AUTO_INCREMENT PRIMARY KEY)\n SELECT NULL AS i\n FROM information_schema.COLUMNS t1\n JOIN information_schema.COLUMNS t2\n JOIN information_schema.COLUMNS t3\n LIMIT 100000; -- <- set your limit here\n</code></pre>\n\n<p>Usually one join should be enough to create over 1M rows - But one more join will not hurt :-) - Just don't forget to set a limit.</p>\n\n<p>If you want to include <code>0</code>, you should \"remove\" the <code>AUTO_INCEMENT</code> property.</p>\n\n<pre><code>ALTER TABLE seq ALTER i DROP DEFAULT;\nALTER TABLE seq MODIFY i MEDIUMINT;\n</code></pre>\n\n<p>Now you can insert <code>0</code></p>\n\n<pre><code>INSERT INTO seq (i) VALUES (0);\n</code></pre>\n\n<p>and negative numbers as well</p>\n\n<pre><code>INSERT INTO seq (i) SELECT -i FROM seq WHERE i <> 0;\n</code></pre>\n\n<p>You can validate the numbers with</p>\n\n<pre><code>SELECT MIN(i), MAX(i), COUNT(*) FROM seq;\n</code></pre>\n"
},
{
"answer_id": 48798014,
"author": "Csongor Halmai",
"author_id": 3823826,
"author_profile": "https://Stackoverflow.com/users/3823826",
"pm_score": 0,
"selected": false,
"text": "<p>The idea I want to share is not a precise response for the question but can be useful for some so I would like to share it.</p>\n\n<p>If you frequently need only a limited set of numbers then it can be beneficial to create a table with the numbers you may need and just use that table every time. For example:</p>\n\n<pre><code>CREATE TABLE _numbers (num int);\nINSERT _numbers VALUES (0), (1), (2), (3), ...;\n</code></pre>\n\n<p>This can be applied only if you need numbers below a certain reasonable limit, so don't use it for generating sequence 1...1 million but can be used for numbers 1...10k, for example.</p>\n\n<p>If you have this list of numbers in the <code>_numbers</code> table then you can write queries like this, for obtaining the individual characters of a string:</p>\n\n<pre><code>SELECT number, substr(name, num, 1) \n FROM users\n JOIN _numbers ON num < length(name)\n WHERE user_id = 1234\n ORDER BY num;\n</code></pre>\n\n<p>If you need larger numbers than 10k then you can join the table to itself:</p>\n\n<pre><code>SELECT n1.num * 10000 + n2.num\n FROM _numbers n1\n JOIN _numbers n2\n WHERE n1 < 100 \n ORDER BY n1.num * 10000 + n2.num; -- or just ORDER BY 1 meaning the first column\n</code></pre>\n"
},
{
"answer_id": 53125278,
"author": "elyalvarado",
"author_id": 3236163,
"author_profile": "https://Stackoverflow.com/users/3236163",
"pm_score": 2,
"selected": false,
"text": "<p>Very similar to the accepted response, but using the new <code>WITH</code> syntax for mysql >= 8.0 which makes a lot more legible and the intent is also clearer</p>\n\n<pre><code>WITH DIGITS (N) AS (\n SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL\n SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL\n SELECT 8 UNION ALL SELECT 9)\nSELECT \n UNITS.N + TENS.N*10 + HUNDREDS.N*100 + THOUSANDS.N*1000 \nFROM \n DIGITS AS UNITS, DIGITS AS TENS, DIGITS AS HUNDREDS, DIGITS AS THOUSANDS;\n</code></pre>\n"
},
{
"answer_id": 60173743,
"author": "dannymac",
"author_id": 2009581,
"author_profile": "https://Stackoverflow.com/users/2009581",
"pm_score": 1,
"selected": false,
"text": "<p>This is based on a previous answer (<a href=\"https://stackoverflow.com/a/53125278/2009581\">https://stackoverflow.com/a/53125278/2009581</a>), but is compatible with MySQL 5.7. It works for replicas and read-only users:</p>\n\n<pre><code>SELECT x1.N + x10.N*10 + x100.N*100 + x1000.N*1000\n FROM (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) x1,\n (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) x10,\n (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) x100,\n (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) x1000\n WHERE x1.N + x10.N*10 + x100.N*100 + x1000.N*1000 <= @max;\n</code></pre>\n\n<p>It generates integers in the range of [0, <code>@max</code>].</p>\n"
},
{
"answer_id": 63543993,
"author": "Justin Levene",
"author_id": 1938802,
"author_profile": "https://Stackoverflow.com/users/1938802",
"pm_score": 2,
"selected": false,
"text": "<p>All other answers are good, however they all have speed issues for larger ranges because they force MySQL to generate every number then filter them.</p>\n<p>The following only makes MySQL generate the numbers that are needed, and therefore is faster:</p>\n<pre><code>set @amount = 55; # How many numbers from zero you want to generate\n\nselect `t0`.`i`+`t1`.`i`+`t2`.`i`+`t3`.`i` as `offset`\nfrom\n(select 0 `i` union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) `t0`,\n(select 0 `i` union select 10 union select 20 union select 30 union select 40 union select 50 union select 60 union select 70 union select 80 union select 90) `t1`,\n(select 0 `i` union select 100 union select 200 union select 300 union select 400 union select 500 union select 600 union select 700 union select 800 union select 900) `t2`,\n(select 0 `i` union select 1000 union select 2000 union select 3000 union select 4000 union select 5000 union select 6000 union select 7000 union select 8000 union select 9000) `t3`\nwhere `t3`.`i`<@amount\nand `t2`.`i`<@amount\nand `t1`.`i`<@amount\nand `t0`.`i`+`t1`.`i`+`t2`.`i`+`t3`.`i`<@amount;\n</code></pre>\n<p>With the above you can generate upto 10,000 numbers (0 to 9,999) with no slower speed overhead for lower numbers, regardless how low they are.</p>\n"
},
{
"answer_id": 66226974,
"author": "Liam",
"author_id": 3714181,
"author_profile": "https://Stackoverflow.com/users/3714181",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a way to do it with json_table if you have MySql 8 and above:</p>\n<pre><code>set @noRows = 100;\nSELECT tt.rowid - 1 AS value\n FROM JSON_TABLE(CONCAT('[{}', REPEAT(',{}', @noRows - 1), ']'),\n "$[*]" COLUMNS(rowid FOR ORDINALITY)\n ) AS tt; \n</code></pre>\n<p>(h/t - <a href=\"https://www.percona.com/blog/2020/07/27/generating-numeric-sequences-in-mysql/\" rel=\"nofollow noreferrer\">https://www.percona.com/blog/2020/07/27/generating-numeric-sequences-in-mysql/</a>)</p>\n"
},
{
"answer_id": 67980354,
"author": "Naresh",
"author_id": 13535919,
"author_profile": "https://Stackoverflow.com/users/13535919",
"pm_score": 0,
"selected": false,
"text": "<p>with recursive cte..</p>\n<pre><code> with recursive rnums as (\n select 1 as n\n union all\n select n+1 as n from rnums\n where n <10\n )\n select * from rnums\n ;\n</code></pre>\n<p>Result would be..\n+------+\n| n |\n+------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n| 6 |\n| 7 |\n| 8 |\n| 9 |\n| 10 |\n+------+\n10 rows in set (0.00 sec)</p>\n"
},
{
"answer_id": 69058632,
"author": "Brad Rhoads",
"author_id": 122630,
"author_profile": "https://Stackoverflow.com/users/122630",
"pm_score": 1,
"selected": false,
"text": "<p>In MariaDB you can do:</p>\n<p>SELECT * FROM seq_i_to_N</p>\n<p>For example:</p>\n<p>SELECT * FROM seq_0_to_1000</p>\n<p>SELECT * FROM seq_1_to_1000000</p>\n<p>Reference: <a href=\"https://www.percona.com/blog/2020/07/27/generating-numeric-sequences-in-mysql/\" rel=\"nofollow noreferrer\">https://www.percona.com/blog/2020/07/27/generating-numeric-sequences-in-mysql/</a></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14635/"
] |
How do I generate a range of consecutive numbers (one per line) from a MySQL query so that I can insert them into a table?
For example:
```
nr
1
2
3
4
5
```
I would like to use only MySQL for this (not PHP or other languages).
|
If you need the records in a table and you want to avoid concurrency issues, here's how to do it.
First you create a table in which to store your records
```
CREATE TABLE `incr` (
`Id` int(11) NOT NULL auto_increment,
PRIMARY KEY (`Id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
```
Secondly create a stored procedure like this:
```
DELIMITER ;;
CREATE PROCEDURE dowhile()
BEGIN
DECLARE v1 INT DEFAULT 5;
WHILE v1 > 0 DO
INSERT incr VALUES (NULL);
SET v1 = v1 - 1;
END WHILE;
END;;
DELIMITER ;
```
Lastly call the SP:
```
CALL dowhile();
SELECT * FROM incr;
```
Result
```
Id
1
2
3
4
5
```
|
186,799 |
<p>When using JDBC, I often come across constructs like </p>
<pre><code>ResultSet rs = ps.executeQuery();
while (rs.next()) {
int id = rs.getInt(1);
// Some other actions
}
</code></pre>
<p>I asked myself (and authors of code too) why not to use labels for retrieving column values: </p>
<pre><code>int id = rs.getInt("CUSTOMER_ID");
</code></pre>
<p>The best explanation I've heard is something concerning performance. But actually, does it make processing extremely fast? I don't believe so, though I have never performed measurements. Even if retrieving by label would be a bit slower, nevertheless, it provide better readability and flexibility, in my opinion.<br>
So could someone give me good explanation of avoiding to retrieve column values by column index instead of column label? What are pros and cons of both approaches (maybe, concerning certain DBMS)? </p>
|
[
{
"answer_id": 186812,
"author": "zloster",
"author_id": 25429,
"author_profile": "https://Stackoverflow.com/users/25429",
"pm_score": 1,
"selected": false,
"text": "<p>The JDBC driver takes care for the column to index look-up. So if you extract values by column name each time the driver makes a look-up (usually in hash map) to check the corresponding index for the column name. </p>\n"
},
{
"answer_id": 186818,
"author": "Cowan",
"author_id": 17041,
"author_profile": "https://Stackoverflow.com/users/17041",
"pm_score": 6,
"selected": false,
"text": "<p>Warning: I'm going to get bombastic here, because this drives me crazy.</p>\n\n<p>99%* of the time, it's a ridiculous micro-optimization that people have some vague idea makes things 'better'. This completely ignores the fact that, unless you're in an extremely tight and busy loop over millions of SQL results <em>all the time</em>, which is hopefully rare, you'll never notice it. For everyone who's not doing that, the developer time cost of maintaing, updating, and fixing bugs in the column indexing are far greater than the incremental cost of hardware for your infinitesimally-worse-performing application.</p>\n\n<p>Don't code optimizations like this in. Code for the person maintaining it. Then observe, measure, analyse, and optimize. Observe again, measure again, analyse again, and optimize again.</p>\n\n<p>Optimization is pretty much the last step in development, not the first.</p>\n\n<p>* Figure is made up.</p>\n"
},
{
"answer_id": 186821,
"author": "Sietse",
"author_id": 6400,
"author_profile": "https://Stackoverflow.com/users/6400",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think using the labels impacts performance by much. But there is another reason not to use <code>String</code>s. Or <code>int</code>s, for that matter.</p>\n\n<p>Consider using constants. Using an <code>int</code> constant makes the code more readably, but also less likely to have errors. </p>\n\n<p>Besides being more readable, the constant also prevents you from making typo's in the label names - the compiler will throw an error if you do. And any IDE worth anything will pick it up. This is not the case if you use <code>String</code>s or <code>ints</code>.</p>\n"
},
{
"answer_id": 187007,
"author": "Cha2lenger",
"author_id": 26475,
"author_profile": "https://Stackoverflow.com/users/26475",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with previous answers that performance is not something that can force us to select either of the approaches. It would be good to consider the following things instead:</p>\n\n<ul>\n<li>Code readability: for every developer reading your code labels have much more sense than indexes.</li>\n<li>Maintenance: think of the SQL query and the way it is maintained. What is more likely to happen in your case after fixing/improving/refactoring SQL query: changing the order of the columns extracted or changing result column names. It seems for me that changing the order of the columns extracted (as the results of adding/deleting new columns in result set) has greater probability to happen.</li>\n<li>Encapsulation: in spite of the way you choose try to isolate the code where you run SQL query and parse result set in the same component and make only this component aware about the column names and their mapping to the indexes (if you decided to use them).</li>\n</ul>\n"
},
{
"answer_id": 187035,
"author": "databyss",
"author_id": 9094,
"author_profile": "https://Stackoverflow.com/users/9094",
"pm_score": 0,
"selected": false,
"text": "<p>Using the index is an attempt at optimization.</p>\n\n<p>The time saved by this is wasted by the extra effort it takes the developer to look up the necessary data to check if their code will work properly after the changes.</p>\n\n<p>I think it's our built-in instinct to use numbers instead of text.</p>\n"
},
{
"answer_id": 187425,
"author": "Martin Klinke",
"author_id": 1793,
"author_profile": "https://Stackoverflow.com/users/1793",
"pm_score": 7,
"selected": true,
"text": "<p>You should use <strong>string labels by default.</strong></p>\n\n<p><strong>Pros:</strong></p>\n\n<ul>\n<li>Independence of column order</li>\n<li>Better readability/maintainability</li>\n</ul>\n\n<p><strong>Cons:</strong></p>\n\n<ul>\n<li>You have no control over the column names (access via stored procedures)</li>\n</ul>\n\n<p><strong>Which would you prefer?</strong></p>\n\n<p>ints?</p>\n\n<pre><code>int i = 1; \ncustomerId = resultSet.getInt(i++); \ncustomerName = resultSet.getString(i++); \ncustomerAddress = resultSet.getString(i++);\n</code></pre>\n\n<p>or Strings?</p>\n\n<pre><code>customerId = resultSet.getInt(\"customer_id\"); \ncustomerName = resultSet.getString(\"customer_name\"); \ncustomerAddress = resultSet.getString(\"customer_address\");\n</code></pre>\n\n<p>And what if there is a new column inserted at position 1? Which code would you prefer? Or if the order of the columns is changed, which code version would you need to change at all?</p>\n\n<p>That's why you should use <strong>string labels by default.</strong></p>\n"
},
{
"answer_id": 380471,
"author": "Vinod Singh",
"author_id": 47704,
"author_profile": "https://Stackoverflow.com/users/47704",
"pm_score": 0,
"selected": false,
"text": "<p>Besides the look up in Map for labels it also leads to an extra String creation. Though it will happens on stack but still it caries a cost with it.</p>\n\n<p>It all depends on the individual choice and till date I have used only indexes :-)</p>\n"
},
{
"answer_id": 402586,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I did some performance profiling on this exact subject on an Oracle database. In our code we have a ResultSet with numerous colums and a huge number of rows. Of the 20 seconds (!) the request takes to execute method oracle.jdbc.driver.ScrollableResultSet.findColumn(String name) takes about 4 seconds.</p>\n\n<p>Obviously there's something wrong with the overall design, but using indexes instead of the column names would probably take this 4 seconds away.</p>\n"
},
{
"answer_id": 2197406,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Sure, using column names increases readability and makes maintenance easy. But using column names has a flipside. As you know, SQL allows multiple column names with same name, there's no guarantee that the column name you typed in the getter method of resultSet actually points to the column name you intend to access. In theory, using index numbers instead of column names is preferred, but it reduces the readability.</p>\n"
},
{
"answer_id": 2197441,
"author": "Kevin Brock",
"author_id": 219394,
"author_profile": "https://Stackoverflow.com/users/219394",
"pm_score": 3,
"selected": false,
"text": "<p>The answer has been accepted, none-the-less, here is some additional information and personal experience that I have not seen put forward yet.</p>\n\n<p>Use column names (constants and not literals is preferred) in general and if possible. This is both clearer, is easier to maintain, and future changes are less likely to break the code.</p>\n\n<p>There is, however, a use for column indexes. In some cases these are faster, but not sufficiently that this should override the above reasons for names*. These are very valuable when developing tools and general methods dealing with <code>ResultSet</code>s. Finally, an index may be required because the column does not have a name (such as an unnamed aggregate) or there are duplicate names so there is no easy way to reference both.</p>\n\n<p>*Note that I have written some JDBC drivers and looked inside some open sources one and internally these use column indexes to reference the result columns. In all cases I have worked with, the internal driver first maps a column name to an index. Thus, you can easily see that the column name, in all those cases, would always take longer. This may not be true for all drivers though.</p>\n"
},
{
"answer_id": 4299050,
"author": "Rick Post",
"author_id": 523198,
"author_profile": "https://Stackoverflow.com/users/523198",
"pm_score": 2,
"selected": false,
"text": "<p>You can have the best of both! The speed of using indexes with the maintainability and security of using column names.</p>\n\n<p>First - unless you are looping thru a result set just use column names.</p>\n\n<ol>\n<li><p>Define a set of integer variables, one for each column you will access. The names of the variables can include the name of the column: e.g. iLast_Name.</p></li>\n<li><p>Before the result set loop iterate thru the column metadata and set the value of each integer variable to the column index of the corresponding column name. If the index of the 'Last_Name' column is 3 then set the value of 'iLast_Name' to 3.</p></li>\n<li><p>In the result set loop use the integer variable names in the GET/SET methods. The variable name is a visual clue to the developer/maintainer as to the actual column name being accessed but the value is the column index and will give the best performance.</p></li>\n</ol>\n\n<p>NOTE: the initial mapping (i.e. column name to index mapping) is only done once before the loop rather than for every record and column in the loop.</p>\n"
},
{
"answer_id": 17312976,
"author": "Jason",
"author_id": 481248,
"author_profile": "https://Stackoverflow.com/users/481248",
"pm_score": 3,
"selected": false,
"text": "<p>From the java documentation:</p>\n\n<blockquote>\n <p>The ResultSet interface provides getter methods (getBoolean, getLong, and so on) for retrieving column values from the current row. Values can be retrieved using either the index number of the column or the name of the column. In general, using the column index will be more efficient. Columns are numbered from 1. For maximum portability, result set columns within each row should be read in left-to-right order, and each column should be read only once.</p>\n</blockquote>\n\n<p>Of course each method (named or indexed) has its place. I agree that named columns should be the default. However, in cases where a huge number of loops are required, and where the SELECT statement is defined and maintained in the same section of code (or class), indexes should be ok - it is advisable to list the columns being selected, not just \"SELECT * FROM...\", since any table change will break the code.</p>\n"
},
{
"answer_id": 55691772,
"author": "Rober2D2",
"author_id": 5441783,
"author_profile": "https://Stackoverflow.com/users/5441783",
"pm_score": 0,
"selected": false,
"text": "<p>As it is pointed out by other posters, I would stick to column names unless you have a really powerful reason not to do so. The impact in performance is negligible compared to, for example, query optimization. In this case, maintenance is much more important than an small optmization.</p>\n"
},
{
"answer_id": 74154693,
"author": "Lukas Eder",
"author_id": 521799,
"author_profile": "https://Stackoverflow.com/users/521799",
"pm_score": 0,
"selected": false,
"text": "<p>Other answers focused a lot on performance, when there's a correctness discussion to be had, first. Here's a simple case where column labels won't work but column indexes do:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE TABLE author (\n id BIGINT PRIMARY KEY,\n first_name TEXT, ...\n);\n\nCREATE TABLE book (\n id BIGINT PRIMARY KEY,\n author_id BIGINT REFERENCES author,\n title TEXT, ...\n);\n</code></pre>\n<p>Then query:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT *\nFROM author\nJOIN book ON author.id = book.author_id\n</code></pre>\n<p>Seems like an every day case to me. Surrogate keys, joins, quite common. What's <code>ID</code> in this case? You can't read them both with labels. Of course, you could alias your columns, or design your schema to avoid any naming conflicts, but who does that all the time?</p>\n<p>It depends on whether this is a problem for you, but for any non-trivial JDBC usage, you'll either create a wrapper around JDBC or use any off-the-shelf API that abstracts over JDBC anyway, which won't have this ambiguity anymore.</p>\n<p>I've elaborated a bit more on why <a href=\"https://www.jooq.org\" rel=\"nofollow noreferrer\">jOOQ</a> uses column indexes behind the scenes <a href=\"https://stackoverflow.com/a/72127206/521799\">in this answer to a similar question</a>. That answer also shows why ORMs or JDBC wrappers like jOOQ or Hibernate better work with indexes than labels for mere performance reasons.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11732/"
] |
When using JDBC, I often come across constructs like
```
ResultSet rs = ps.executeQuery();
while (rs.next()) {
int id = rs.getInt(1);
// Some other actions
}
```
I asked myself (and authors of code too) why not to use labels for retrieving column values:
```
int id = rs.getInt("CUSTOMER_ID");
```
The best explanation I've heard is something concerning performance. But actually, does it make processing extremely fast? I don't believe so, though I have never performed measurements. Even if retrieving by label would be a bit slower, nevertheless, it provide better readability and flexibility, in my opinion.
So could someone give me good explanation of avoiding to retrieve column values by column index instead of column label? What are pros and cons of both approaches (maybe, concerning certain DBMS)?
|
You should use **string labels by default.**
**Pros:**
* Independence of column order
* Better readability/maintainability
**Cons:**
* You have no control over the column names (access via stored procedures)
**Which would you prefer?**
ints?
```
int i = 1;
customerId = resultSet.getInt(i++);
customerName = resultSet.getString(i++);
customerAddress = resultSet.getString(i++);
```
or Strings?
```
customerId = resultSet.getInt("customer_id");
customerName = resultSet.getString("customer_name");
customerAddress = resultSet.getString("customer_address");
```
And what if there is a new column inserted at position 1? Which code would you prefer? Or if the order of the columns is changed, which code version would you need to change at all?
That's why you should use **string labels by default.**
|
186,800 |
<p>I need to configure a website to access a webservice on another machine, via a proxy. I can configure the website to use a proxy, but I can't find a way of specifying the credentials that the proxy requires, is that possible? Here is my current configuration:</p>
<pre><code><defaultProxy useDefaultCredentials="false">
<proxy usesystemdefault="true" proxyaddress="<proxy address>" bypassonlocal="true" />
</defaultProxy>
</code></pre>
<p>I know you can do this via code, but the software the website is running is a closed-source CMS so I can't do this.</p>
<p>Is there any way to do this? MSDN isn't helping me much..</p>
|
[
{
"answer_id": 186859,
"author": "questzen",
"author_id": 25210,
"author_profile": "https://Stackoverflow.com/users/25210",
"pm_score": 1,
"selected": false,
"text": "<p>Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision</p>\n"
},
{
"answer_id": 194414,
"author": "Jérôme Laban",
"author_id": 26346,
"author_profile": "https://Stackoverflow.com/users/26346",
"pm_score": 8,
"selected": true,
"text": "<p>Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.</p>\n\n<p>Create an assembly called <em>SomeAssembly.dll</em> with this class :</p>\n\n<pre><code>namespace SomeNameSpace\n{\n public class MyProxy : IWebProxy\n {\n public ICredentials Credentials\n {\n get { return new NetworkCredential(\"user\", \"password\"); }\n //or get { return new NetworkCredential(\"user\", \"password\",\"domain\"); }\n set { }\n }\n\n public Uri GetProxy(Uri destination)\n {\n return new Uri(\"http://my.proxy:8080\");\n }\n\n public bool IsBypassed(Uri host)\n {\n return false;\n }\n }\n}\n</code></pre>\n\n<p>Add this to your config file :</p>\n\n<pre><code><defaultProxy enabled=\"true\" useDefaultCredentials=\"false\">\n <module type = \"SomeNameSpace.MyProxy, SomeAssembly\" />\n</defaultProxy>\n</code></pre>\n\n<p>This \"injects\" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application.</p>\n\n<p>This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationsection.aspx\" rel=\"noreferrer\">ConfigurationSection</a>, or add some information in the <a href=\"http://msdn.microsoft.com/en-us/library/ms228154.aspx\" rel=\"noreferrer\">AppSettings</a>, which is far more easier.</p>\n"
},
{
"answer_id": 875700,
"author": "Scott Ferguson",
"author_id": 5007,
"author_profile": "https://Stackoverflow.com/users/5007",
"pm_score": 4,
"selected": false,
"text": "<p>While I haven't found a good way to specify proxy network credentials in the web.config, you might find that you can still use a non-coding solution, by including this in your web.config:</p>\n\n<pre><code> <system.net>\n <defaultProxy useDefaultCredentials=\"true\">\n <proxy proxyaddress=\"proxyAddress\" usesystemdefault=\"True\"/>\n </defaultProxy>\n </system.net>\n</code></pre>\n\n<p>The key ingredient in getting this going, is to change the IIS settings, ensuring the account that runs the process has access to the proxy server.\nIf your process is running under LocalService, or NetworkService, then this probably won't work. Chances are, you'll want a domain account.</p>\n"
},
{
"answer_id": 31082422,
"author": "Silas Humberto Souza",
"author_id": 3964740,
"author_profile": "https://Stackoverflow.com/users/3964740",
"pm_score": 3,
"selected": false,
"text": "<p>You can specify credentials by adding a new Generic Credential of your proxy server in Windows Credentials Manager:</p>\n<p>1 In Web.config</p>\n<pre><code><system.net> \n<defaultProxy enabled="true" useDefaultCredentials="true"> \n<proxy usesystemdefault="True" /> \n</defaultProxy> \n</system.net>\n</code></pre>\n<ol start=\"2\">\n<li>In Control Panel\\All Control Panel Items\\Credential Manager >> Add a Generic Credential</li>\n</ol>\n<p>Internet or network address: your proxy address<br>\nUser name: your user name<br>\nPassword: you pass</p>\n<p>This configuration worked for me, without change the code.</p>\n"
},
{
"answer_id": 72569636,
"author": "Malik",
"author_id": 5891307,
"author_profile": "https://Stackoverflow.com/users/5891307",
"pm_score": 0,
"selected": false,
"text": "<p>Though its very late but it might be helpful for someone looking for solution to the same problem. I came across this question after having same problem. I am giving my solution to the problem, how I made it work.\nI created the proxy using using credentials like this,</p>\n<pre><code>public class MyProxy : IWebProxy\n{\n public ICredentials Credentials\n {\n //get { return new NetworkCredential("user", "password"); }\n get { return new NetworkCredential("user", "password","domain"); }\n set { }\n }\n\n public Uri GetProxy(Uri destination)\n {\n return new Uri("http://my.proxy:8080");\n }\n\n public bool IsBypassed(Uri host)\n {\n return false;\n }\n}\n</code></pre>\n<p>And then you have to register the HttpClient in the DI container like this and it will work perfectly.</p>\n<pre><code>services.AddHttpClient("Lynx", client =>\n {\n client.BaseAddress = new Uri(Configuration.GetSection("LynxUrl").Value);\n }).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { Proxy = new MyProxy()});\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5793/"
] |
I need to configure a website to access a webservice on another machine, via a proxy. I can configure the website to use a proxy, but I can't find a way of specifying the credentials that the proxy requires, is that possible? Here is my current configuration:
```
<defaultProxy useDefaultCredentials="false">
<proxy usesystemdefault="true" proxyaddress="<proxy address>" bypassonlocal="true" />
</defaultProxy>
```
I know you can do this via code, but the software the website is running is a closed-source CMS so I can't do this.
Is there any way to do this? MSDN isn't helping me much..
|
Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.
Create an assembly called *SomeAssembly.dll* with this class :
```
namespace SomeNameSpace
{
public class MyProxy : IWebProxy
{
public ICredentials Credentials
{
get { return new NetworkCredential("user", "password"); }
//or get { return new NetworkCredential("user", "password","domain"); }
set { }
}
public Uri GetProxy(Uri destination)
{
return new Uri("http://my.proxy:8080");
}
public bool IsBypassed(Uri host)
{
return false;
}
}
}
```
Add this to your config file :
```
<defaultProxy enabled="true" useDefaultCredentials="false">
<module type = "SomeNameSpace.MyProxy, SomeAssembly" />
</defaultProxy>
```
This "injects" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application.
This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own [ConfigurationSection](http://msdn.microsoft.com/en-us/library/system.configuration.configurationsection.aspx), or add some information in the [AppSettings](http://msdn.microsoft.com/en-us/library/ms228154.aspx), which is far more easier.
|
186,802 |
<p>I have named_scope which is reused in multiple ActiveRecord models.
For example:</p>
<pre><code> named_scope :limit, lambda {|limit| {:limit => limit}}
</code></pre>
<p>What is the best practice to extract this code to be shared across models.
Is it possible to extract it to a module or should I rather reopen ActiveRecord::Base class?</p>
|
[
{
"answer_id": 187097,
"author": "Ben Scofield",
"author_id": 6478,
"author_profile": "https://Stackoverflow.com/users/6478",
"pm_score": 4,
"selected": false,
"text": "<p>Use a module. Something like this should work:</p>\n\n<pre><code>module CommonScopes\n def self.included(base)\n base.class_eval do\n named_scope :limit, lambda {|limit| {:limit => limit}}\n end\n end\nend\n</code></pre>\n\n<p>Then just include CommonScopes and you'll be good to go.</p>\n"
},
{
"answer_id": 12932330,
"author": "Hugo Stieglitz",
"author_id": 1147829,
"author_profile": "https://Stackoverflow.com/users/1147829",
"pm_score": 0,
"selected": false,
"text": "<p>@Matt via <a href=\"http://apidock.com/ruby/v1_9_1_378/BasicObject/instance_eval\" rel=\"nofollow noreferrer\">instance_eval</a>, @see <a href=\"https://stackoverflow.com/questions/7323793/shared-scopes-via-module\">Shared scopes via module?</a></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18715/"
] |
I have named\_scope which is reused in multiple ActiveRecord models.
For example:
```
named_scope :limit, lambda {|limit| {:limit => limit}}
```
What is the best practice to extract this code to be shared across models.
Is it possible to extract it to a module or should I rather reopen ActiveRecord::Base class?
|
Use a module. Something like this should work:
```
module CommonScopes
def self.included(base)
base.class_eval do
named_scope :limit, lambda {|limit| {:limit => limit}}
end
end
end
```
Then just include CommonScopes and you'll be good to go.
|
186,822 |
<p>How do I invoke a console application from my .NET application and capture all the output generated in the console? </p>
<p>(Remember, I don't want to save the information first in a file and then relist as I would love to receive it as live.)</p>
|
[
{
"answer_id": 186833,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 8,
"selected": true,
"text": "<p>This can be quite easily achieved using the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx\" rel=\"noreferrer\">ProcessStartInfo.RedirectStandardOutput</a> property. A full sample is contained in the linked MSDN documentation; the only caveat is that you may have to redirect the standard error stream as well to see all output of your application.</p>\n\n<pre><code>Process compiler = new Process();\ncompiler.StartInfo.FileName = \"csc.exe\";\ncompiler.StartInfo.Arguments = \"/r:System.dll /out:sample.exe stdstr.cs\";\ncompiler.StartInfo.UseShellExecute = false;\ncompiler.StartInfo.RedirectStandardOutput = true;\ncompiler.Start(); \n\nConsole.WriteLine(compiler.StandardOutput.ReadToEnd());\n\ncompiler.WaitForExit();\n</code></pre>\n"
},
{
"answer_id": 186835,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 4,
"selected": false,
"text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx\" rel=\"nofollow noreferrer\">ProcessStartInfo.RedirectStandardOutput</a> to redirect the output when creating your console process.</p>\n<p>Then you can use <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx\" rel=\"nofollow noreferrer\">Process.StandardOutput</a> to read the program output.</p>\n<p>The second link has a sample code how to do it.</p>\n"
},
{
"answer_id": 2850784,
"author": "livetogogo",
"author_id": 343246,
"author_profile": "https://Stackoverflow.com/users/343246",
"pm_score": 1,
"selected": false,
"text": "<p>From <em><a href=\"http://pythontr.org/index.php?option=com_content&view=article&id=50:python-script-lerinin-c-ile-caltrlmas-execute-python-script-in-c&catid=31:makale&Itemid=66\" rel=\"nofollow noreferrer\">PythonTR - Python Programcıları Derneği, e-kitap, örnek</a></em>:</p>\n\n<pre><code>Process p = new Process(); // Create new object\np.StartInfo.UseShellExecute = false; // Do not use shell\np.StartInfo.RedirectStandardOutput = true; // Redirect output\np.StartInfo.FileName = \"c:\\\\python26\\\\python.exe\"; // Path of our Python compiler\np.StartInfo.Arguments = \"c:\\\\python26\\\\Hello_C_Python.py\"; // Path of the .py to be executed\n</code></pre>\n"
},
{
"answer_id": 8280433,
"author": "Dinis Cruz",
"author_id": 262379,
"author_profile": "https://Stackoverflow.com/users/262379",
"pm_score": 2,
"selected": false,
"text": "<p>I've added a number of helper methods to the <a href=\"http://o2platform.com\" rel=\"nofollow\">O2 Platform</a> (Open Source project) which allow you easily script an interaction with another process via the console output and input (see <a href=\"http://code.google.com/p/o2platform/source/browse/trunk/O2_Scripts/APIs/Windows/CmdExe/CmdExeAPI.cs\" rel=\"nofollow\">http://code.google.com/p/o2platform/source/browse/trunk/O2_Scripts/APIs/Windows/CmdExe/CmdExeAPI.cs</a>)</p>\n\n<p>Also useful for you might be the API that allows the viewing of the console output of the current process (in an existing control or popup window). See this blog post for more details: <a href=\"http://o2platform.wordpress.com/2011/11/26/api_consoleout-cs-inprocess-capture-of-the-console-output/\" rel=\"nofollow\">http://o2platform.wordpress.com/2011/11/26/api_consoleout-cs-inprocess-capture-of-the-console-output/</a> (this blog also contains details of how to consume the console output of new processes)</p>\n"
},
{
"answer_id": 15725442,
"author": "SlavaGu",
"author_id": 319170,
"author_profile": "https://Stackoverflow.com/users/319170",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://github.com/slavagu/ConsoleAppLauncher\">ConsoleAppLauncher</a> is an open source library made specifically to answer that question. It captures all the output generated in the console and provides simple interface to start and close console application. </p>\n\n<p>The ConsoleOutput event is fired every time when a new line is written by the console to standard/error output. The lines are queued and guaranteed to follow the output order. </p>\n\n<p>Also available as <a href=\"https://nuget.org/packages/ConsoleAppLauncher/\">NuGet package</a>.</p>\n\n<p>Sample call to get full console output:</p>\n\n<pre><code>// Run simplest shell command and return its output.\npublic static string GetWindowsVersion()\n{\n return ConsoleApp.Run(\"cmd\", \"/c ver\").Output.Trim();\n}\n</code></pre>\n\n<p>Sample with live feedback:</p>\n\n<pre><code>// Run ping.exe asynchronously and return roundtrip times back to the caller in a callback\npublic static void PingUrl(string url, Action<string> replyHandler)\n{\n var regex = new Regex(\"(time=|Average = )(?<time>.*?ms)\", RegexOptions.Compiled);\n var app = new ConsoleApp(\"ping\", url);\n app.ConsoleOutput += (o, args) =>\n {\n var match = regex.Match(args.Line);\n if (match.Success)\n {\n var roundtripTime = match.Groups[\"time\"].Value;\n replyHandler(roundtripTime);\n }\n };\n app.Run();\n}\n</code></pre>\n"
},
{
"answer_id": 32487747,
"author": "Sergei Zinovyev",
"author_id": 5145258,
"author_profile": "https://Stackoverflow.com/users/5145258",
"pm_score": 1,
"selected": false,
"text": "<p>Added <code>process.StartInfo.**CreateNoWindow** = true;</code> and <code>timeout</code>.</p>\n\n<pre><code>private static void CaptureConsoleAppOutput(string exeName, string arguments, int timeoutMilliseconds, out int exitCode, out string output)\n{\n using (Process process = new Process())\n {\n process.StartInfo.FileName = exeName;\n process.StartInfo.Arguments = arguments;\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.RedirectStandardOutput = true;\n process.StartInfo.CreateNoWindow = true;\n process.Start();\n\n output = process.StandardOutput.ReadToEnd();\n\n bool exited = process.WaitForExit(timeoutMilliseconds);\n if (exited)\n {\n exitCode = process.ExitCode;\n }\n else\n {\n exitCode = -1;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 39624153,
"author": "Shital Shah",
"author_id": 207661,
"author_profile": "https://Stackoverflow.com/users/207661",
"pm_score": 6,
"selected": false,
"text": "<p>This is bit improvement over accepted answer from <strong>@mdb</strong>. Specifically, we also capture error output of the process. Additionally, we capture these outputs through events because <code>ReadToEnd()</code> doesn't work if you want to capture <em>both</em> error and regular output. It took me while to make this work because it actually also requires <code>BeginxxxReadLine()</code> calls after <code>Start()</code>.</p>\n\n<p>Asynchronous way:</p>\n\n<pre><code>using System.Diagnostics;\n\nProcess process = new Process();\n\nvoid LaunchProcess()\n{\n process.EnableRaisingEvents = true;\n process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived);\n process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_ErrorDataReceived);\n process.Exited += new System.EventHandler(process_Exited);\n\n process.StartInfo.FileName = \"some.exe\";\n process.StartInfo.Arguments = \"param1 param2\";\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.RedirectStandardError = true;\n process.StartInfo.RedirectStandardOutput = true;\n\n process.Start();\n process.BeginErrorReadLine();\n process.BeginOutputReadLine(); \n\n //below line is optional if we want a blocking call\n //process.WaitForExit();\n}\n\nvoid process_Exited(object sender, EventArgs e)\n{\n Console.WriteLine(string.Format(\"process exited with code {0}\\n\", process.ExitCode.ToString()));\n}\n\nvoid process_ErrorDataReceived(object sender, DataReceivedEventArgs e)\n{\n Console.WriteLine(e.Data + \"\\n\");\n}\n\nvoid process_OutputDataReceived(object sender, DataReceivedEventArgs e)\n{\n Console.WriteLine(e.Data + \"\\n\");\n}\n</code></pre>\n"
},
{
"answer_id": 59373604,
"author": "3dGrabber",
"author_id": 141397,
"author_profile": "https://Stackoverflow.com/users/141397",
"pm_score": 2,
"selected": false,
"text": "<p>I made a reactive version that accepts callbacks for stdOut and StdErr.<br>\n<code>onStdOut</code> and <code>onStdErr</code> are called asynchronously,<br>\nas soon as data arrives (before the process exits).<br>\n<br/></p>\n\n<pre><code>public static Int32 RunProcess(String path,\n String args,\n Action<String> onStdOut = null,\n Action<String> onStdErr = null)\n {\n var readStdOut = onStdOut != null;\n var readStdErr = onStdErr != null;\n\n var process = new Process\n {\n StartInfo =\n {\n FileName = path,\n Arguments = args,\n CreateNoWindow = true,\n UseShellExecute = false,\n RedirectStandardOutput = readStdOut,\n RedirectStandardError = readStdErr,\n }\n };\n\n process.Start();\n\n if (readStdOut) Task.Run(() => ReadStream(process.StandardOutput, onStdOut));\n if (readStdErr) Task.Run(() => ReadStream(process.StandardError, onStdErr));\n\n process.WaitForExit();\n\n return process.ExitCode;\n }\n\n private static void ReadStream(TextReader textReader, Action<String> callback)\n {\n while (true)\n {\n var line = textReader.ReadLine();\n if (line == null)\n break;\n\n callback(line);\n }\n }\n</code></pre>\n\n<p><br/></p>\n\n<h2>Example usage</h2>\n\n<p>The following will run <code>executable</code> with <code>args</code> and print </p>\n\n<ul>\n<li>stdOut in white</li>\n<li>stdErr in red </li>\n</ul>\n\n<p>to the console.</p>\n\n<pre><code>RunProcess(\n executable,\n args,\n s => { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(s); },\n s => { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(s); } \n);\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17519/"
] |
How do I invoke a console application from my .NET application and capture all the output generated in the console?
(Remember, I don't want to save the information first in a file and then relist as I would love to receive it as live.)
|
This can be quite easily achieved using the [ProcessStartInfo.RedirectStandardOutput](http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx) property. A full sample is contained in the linked MSDN documentation; the only caveat is that you may have to redirect the standard error stream as well to see all output of your application.
```
Process compiler = new Process();
compiler.StartInfo.FileName = "csc.exe";
compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs";
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;
compiler.Start();
Console.WriteLine(compiler.StandardOutput.ReadToEnd());
compiler.WaitForExit();
```
|
186,827 |
<p>I need to send email through an (external) SMTP server from Java however this server will only accept CRAM-MD5 authentication, which is not supported by JavaMail.</p>
<p>What would be a good way to get these emails to send? (It must be in Java.)</p>
|
[
{
"answer_id": 186906,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "<p>This doesn't help you directly, however, IMAP connections in JavaMail do support SASL (and thus CRAM-MD5, see the <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/security/sasl/sasl-refguide.html\" rel=\"nofollow noreferrer\">Java SASL documentation</a>) if you set the <a href=\"http://java.sun.com/products/javamail/javadocs/com/sun/mail/imap/package-summary.html\" rel=\"nofollow noreferrer\"><code>mail.imap.sasl.enable</code></a> boolean property to <code>true</code>.</p>\n\n<p>Unfortunately, there is no <code>mail.smtp.sasl.enable</code> property, and SASL cannot be enabled for SMTP in JavaMail. :-(</p>\n\n<p>However, you can download the <a href=\"https://maven-repository.dev.java.net/nonav/repository/javax.mail/java-sources/\" rel=\"nofollow noreferrer\">JavaMail source code</a>, and you can try to edit the SMTP code to support SASL in a similar manner to the IMAP code. Good luck!</p>\n"
},
{
"answer_id": 187254,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 2,
"selected": false,
"text": "<p>This probably won't help you but CRAM-MD5 and CRAM-SHA1 are fairly easy to implement assuming you have the correct library (md5/sha1) and, idealy, a base64 encoding library (though the base64 stuff is fairly easy to implement yourself in a pinch).</p>\n\n<p>The transaction looks like this:</p>\n\n<pre><code>C: AUTH CRAM-MD5\nS: 334 BASE64(NONCE)\nC: BASE64(USERNAME, \" \", MD5((SECRET XOR opad),MD5((SECRET XOR ipad), NONCE)))\nS: 235 Authentication succeeded\n</code></pre>\n\n<p>Where NONCE is the once time challenge string, USERNAME is the username you are tryng to authenticate, SECRET is the shared secret (\"password\"), opad is 0x5C, and ipad is 0x36.</p>\n\n<p>(CRAM-SHA1 would be the same transaction, but using SHA1() instead of MD5() to do the digesting)</p>\n\n<p>So, here's an example of a real CRAM-MD5 transaction</p>\n\n<pre><code>C: AUTH CRAM-MD5\nS: 334 PDQ1MDMuMTIyMzU1Nzg2MkBtYWlsMDEuZXhhbXBsZS5jb20+\nC: dXNlckBleGFtcGxlLmNvbSA4YjdjODA5YzQ0NTNjZTVhYTA5N2VhNWM4OTlmNGY4Nw==\nS: 235 Authentication succeeded\n</code></pre>\n\n<p>Backing up the process a step you get:</p>\n\n<pre><code>S: 334 BASE64(\"<[email protected]>\")\nC: BASE64(\"[email protected] 8b7c809c4453ce5aa097ea5c899f4f87\")\n</code></pre>\n\n<p>Backing up one step further to before the digest is calculated, you get:</p>\n\n<pre><code>S: 334 BASE64(\"<[email protected]>\")\nC: BASE64(\"[email protected] \", MD5((\"password\" XOR opad),MD5((\"password\" XOR ipad), \"<[email protected]>\")))\n</code></pre>\n\n<p>I guess that's kind of confusing now that I write it out, but trust me, compared to trying to do NTLM/SPA by hand, it's a breeze. If you're motivated, it's actually pretty easy to implement. Or maybe I've just spent way to long with my hands in the guts of mail clients and servers to think about it clearly anymore...</p>\n"
},
{
"answer_id": 403602,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<h2>Very Simple CRAMMD5 program in JAVA</h2>\n\n<hr>\n\n<pre><code>import java.security.*;\n\nclass CRAMMD5Test\n{\npublic static void main(String[] args) throws Exception\n{\n // This represents the BASE64 encoded timestamp sent by the POP server\n String dataString = Base64Decoder.decode(\"PDAwMDAuMDAwMDAwMDAwMEBteDEuc2VydmVyLmNvbT4=\");\n byte[] data = dataString.getBytes();\n\n // The password to access the account\n byte[] key = new String(\"password\").getBytes();\n\n // The address of the e-mail account\n String user = \"[email protected]\";\n\n MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\n md5.reset();\n\n if (key.length > 64)\n key = md5.digest(key);\n\n byte[] k_ipad = new byte[64];\n byte[] k_opad = new byte[64];\n\n System.arraycopy(key, 0, k_ipad, 0, key.length);\n System.arraycopy(key, 0, k_opad, 0, key.length);\n\n for (int i=0; i<64; i++)\n {\n k_ipad[i] ^= 0x36;\n k_opad[i] ^= 0x5c;\n }\n\n byte[] i_temp = new byte[k_ipad.length + data.length];\n\n System.arraycopy(k_ipad, 0, i_temp, 0, k_ipad.length);\n System.arraycopy(data, 0, i_temp, k_ipad.length, data.length);\n\n i_temp = md5.digest(i_temp);\n\n byte[] o_temp = new byte[k_opad.length + i_temp.length];\n\n System.arraycopy(k_opad, 0, o_temp, 0, k_opad.length);\n System.arraycopy(i_temp, 0, o_temp, k_opad.length, i_temp.length);\n\n byte[] result = md5.digest(o_temp);\n StringBuffer hexString = new StringBuffer();\n\n for (int i=0;i < result.length; i++) {\n hexString.append(Integer.toHexString((result[i] >>> 4) & 0x0F));\n hexString.append(Integer.toHexString(0x0F & result[i]));\n }\n\n\n System.out.println(Base64Encoder.encode(user + \" \" + hexString.toString()));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 468574,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I tried the code on the example of a real CRAM-MD5 transaction, and also on the example given into the RFC 2195.</p>\n\n<p>It does not work because the conversion to an hexadecimal string is not correct. For exmaple, with this code, you will obtain \"b913a62c7eda7a495b4e6e7334d3890\" instead of \"b913a602c7eda7a495b4e6e7334d3890\" and the sent authentication string will not be correct.</p>\n\n<p>If you download the source code of javaMail, you will see the implementation of the function toHex into the unit \"DigestMD5\". Using this conversion, it will work.</p>\n"
},
{
"answer_id": 509203,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Change:</strong></p>\n\n<pre><code>for (int i=0; i<result.length; i++)\n hexString.append(Integer.toHexString(0xFF & result[i]));\n</code></pre>\n\n<p><strong>To:</strong></p>\n\n<pre><code>for (int i=0;i < result.length; i++) {\n hexString.append(Integer.toHexString((result[i] >>> 4) & 0x0F));\n hexString.append(Integer.toHexString(0x0F & result[i]));\n}\n</code></pre>\n"
},
{
"answer_id": 12110971,
"author": "Alexey Ogarkov",
"author_id": 57588,
"author_profile": "https://Stackoverflow.com/users/57588",
"pm_score": 4,
"selected": true,
"text": "<p>Here is <a href=\"http://lists.gnu.org/archive/html/classpathx-javamail/2010-10/msg00004.html\" rel=\"noreferrer\">thread</a> which says that you need to add the following property:</p>\n\n<pre><code>props.put(\"mail.smtp.auth.mechanisms\", \"CRAM-MD5\")\n</code></pre>\n\n<p>Also in Geronimo implementation there is <a href=\"http://geronimo.apache.org/maven/javamail/1.7/geronimo-javamail_1.4_provider/apidocs/org/apache/geronimo/javamail/authentication/CramMD5Authenticator.html\" rel=\"noreferrer\">CramMD5Authenticator</a></p>\n\n<p>Hope it helps to resolve this old question.</p>\n"
},
{
"answer_id": 12155965,
"author": "Pumuckline",
"author_id": 987281,
"author_profile": "https://Stackoverflow.com/users/987281",
"pm_score": 3,
"selected": false,
"text": "<p>Since Java Mail 1.4.4, CRAM-MD5 is supported for use with smtp. \nJust set this parameter to your properties and it will work: </p>\n\n<p><code>props.put(\"mail.smtp.sasl.enable\", \"true\");</code></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15355/"
] |
I need to send email through an (external) SMTP server from Java however this server will only accept CRAM-MD5 authentication, which is not supported by JavaMail.
What would be a good way to get these emails to send? (It must be in Java.)
|
Here is [thread](http://lists.gnu.org/archive/html/classpathx-javamail/2010-10/msg00004.html) which says that you need to add the following property:
```
props.put("mail.smtp.auth.mechanisms", "CRAM-MD5")
```
Also in Geronimo implementation there is [CramMD5Authenticator](http://geronimo.apache.org/maven/javamail/1.7/geronimo-javamail_1.4_provider/apidocs/org/apache/geronimo/javamail/authentication/CramMD5Authenticator.html)
Hope it helps to resolve this old question.
|
186,829 |
<p>Conventional IPv4 dotted quad notation separates the address from the port with a colon, as in this example of a webserver on the loopback interface:</p>
<pre><code>127.0.0.1:80
</code></pre>
<p>but with IPv6 notation the address itself can contain colons. For example, this is the short form of the loopback address:</p>
<pre><code>::1
</code></pre>
<p>How are ports (or their functional equivalent) expressed in a textual representation of an IPv6 address/port endpoint? </p>
|
[
{
"answer_id": 186842,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 3,
"selected": false,
"text": "<p>They're the same, aren't they? Now I'm losing confidence in myself but I really thought IPv6 was just an addressing change. TCP and UDP are still addressed as they are under IPv4.</p>\n"
},
{
"answer_id": 186845,
"author": "Andrew Moore",
"author_id": 26210,
"author_profile": "https://Stackoverflow.com/users/26210",
"pm_score": 5,
"selected": false,
"text": "<p>The protocols used in IPv6 are the same as the protocols in IPv4. The only thing that changed between the two versions is the addressing scheme, DHCP [DHCPv6] and ICMP [ICMPv6]. So basically, anything TCP/UDP related, including the port range (0-65535) remains unchanged.</p>\n\n<p><strong>Edit:</strong> Port 0 is a reserved port in TCP but it does exist. See <a href=\"http://www.faqs.org/rfcs/rfc793.html\" rel=\"noreferrer\">RFC793</a></p>\n"
},
{
"answer_id": 186846,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 3,
"selected": false,
"text": "<p>I'm pretty certain that ports only have a part in tcp and udp. So it's exactly the same even if you use a new IP protocol</p>\n"
},
{
"answer_id": 186848,
"author": "Nico",
"author_id": 22970,
"author_profile": "https://Stackoverflow.com/users/22970",
"pm_score": 9,
"selected": true,
"text": "<p>They work almost the same as today. However, be sure you include <code>[]</code> around your IP.</p>\n\n<p>For example : <a href=\"http://en.wikipedia.org/wiki/IPv6_address#Literal_IPv6_addresses_in_network_resource_identifiers\" rel=\"noreferrer\"><code>http://[1fff:0:a88:85a3::ac1f]:8001/index.html</code></a></p>\n\n<p>Wikipedia has a pretty good article about IPv6: <a href=\"http://en.wikipedia.org/wiki/IPv6#Addressing\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/IPv6#Addressing</a></p>\n"
},
{
"answer_id": 25570552,
"author": "Ajedi32",
"author_id": 1157054,
"author_profile": "https://Stackoverflow.com/users/1157054",
"pm_score": 3,
"selected": false,
"text": "<p>Wikipedia <a href=\"http://en.wikipedia.org/wiki/IPv6#Addressing\" rel=\"noreferrer\">points out</a> that the syntax of an IPv6 address includes colons and has a short form preventing fixed-length parsing, and therefore you have to delimit the address portion with []. This completely avoids the odd parsing errors.</p>\n\n<p>(Taken from <a href=\"https://stackoverflow.com/revisions/186829/2\">an edit</a> <a href=\"https://stackoverflow.com/users/1715673/peter-wone\">Peter Wone</a> made to the original question.)</p>\n"
},
{
"answer_id": 35767204,
"author": "zhrist",
"author_id": 1930758,
"author_profile": "https://Stackoverflow.com/users/1930758",
"pm_score": 3,
"selected": false,
"text": "<p>I would say the best reference is <a href=\"http://www.ietf.org/rfc/rfc2732.txt\" rel=\"noreferrer\">Format for Literal IPv6 Addresses in URL's</a> where usage of [] is defined. </p>\n\n<p>Also, if it is for programming and code, specifically Java, I would suggest this reads<a href=\"https://docs.oracle.com/javase/8/docs/api/java/net/Inet6Address.html\" rel=\"noreferrer\">Class for Inet6Address</a> <a href=\"https://docs.oracle.com/javase/8/docs/api/java/net/URL.html\" rel=\"noreferrer\">java/net/URL definition</a> where usage of Inet4 address in Inet6 connotation and other cases are presented in details. For my case, IPv4-mapped address Of the form::ffff:w.x.y.z, for IPv6 address is used to represent an IPv4 address also solved my problem. It allows the native program to use the same address data structure and also the same socket when communicating with both IPv4 and IPv6 nodes. This is the case on Amazon cloud Linux boxes default setup.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1715673/"
] |
Conventional IPv4 dotted quad notation separates the address from the port with a colon, as in this example of a webserver on the loopback interface:
```
127.0.0.1:80
```
but with IPv6 notation the address itself can contain colons. For example, this is the short form of the loopback address:
```
::1
```
How are ports (or their functional equivalent) expressed in a textual representation of an IPv6 address/port endpoint?
|
They work almost the same as today. However, be sure you include `[]` around your IP.
For example : [`http://[1fff:0:a88:85a3::ac1f]:8001/index.html`](http://en.wikipedia.org/wiki/IPv6_address#Literal_IPv6_addresses_in_network_resource_identifiers)
Wikipedia has a pretty good article about IPv6: <http://en.wikipedia.org/wiki/IPv6#Addressing>
|
186,840 |
<p>My company runs a webmail service, and we were trying to diagnose a problem with Word downloads not opening automatically - the same *.doc file download from Yahoo Mail would open, but one from ours would not.</p>
<p>In the course of investigating the headers we saw this coming from Yahoo:</p>
<pre><code>content-disposition attachment; filename*="utf-8''word document.doc";
</code></pre>
<p>Whereas our headers were like this:</p>
<pre><code>content-disposition attachment; filename="word document.doc";
</code></pre>
<p>What exactly is Yahoo doing with the additional asterisk and utf-8'' designation?</p>
|
[
{
"answer_id": 186886,
"author": "Alphager",
"author_id": 21684,
"author_profile": "https://Stackoverflow.com/users/21684",
"pm_score": 0,
"selected": false,
"text": "<p>What Mime-Type are you using?</p>\n\n<p>The asterisk is required as per RFC 2183 (<a href=\"http://www.ietf.org/rfc/rfc2183.txt\" rel=\"nofollow noreferrer\">http://www.ietf.org/rfc/rfc2183.txt</a>):</p>\n\n<p>In the extended BNF notation of [RFC 822], the Content-Disposition\n header field is defined as follows:</p>\n\n<pre><code> disposition := \"Content-Disposition\" \":\"\n disposition-type\n *(\";\" disposition-parm)\n\n disposition-type := \"inline\"\n / \"attachment\"\n / extension-token\n ; values are not case-sensitive\n\n disposition-parm := filename-parm\n / creation-date-parm\n / modification-date-parm\n / read-date-parm\n / size-parm\n / parameter\n\n filename-parm := \"filename\" \"=\" value\n\n creation-date-parm := \"creation-date\" \"=\" quoted-date-time\n\n modification-date-parm := \"modification-date\" \"=\" quoted-date-time\n\n read-date-parm := \"read-date\" \"=\" quoted-date-time\n\n size-parm := \"size\" \"=\" 1*DIGIT\n\n quoted-date-time := quoted-string\n ; contents MUST be an RFC 822 `date-time'\n ; numeric timezones (+HHMM or -HHMM) MUST be used\n</code></pre>\n"
},
{
"answer_id": 187331,
"author": "z7q2",
"author_id": 25487,
"author_profile": "https://Stackoverflow.com/users/25487",
"pm_score": 2,
"selected": false,
"text": "<p>I think the correct answer to this is in rfc 2231:</p>\n\n<p>Asterisks (\"*\") are reused to provide the indicator that language and\n character set information is present and encoding is being used. A\n single quote (\"'\") is used to delimit the character set and language\n information at the beginning of the parameter value. Percent signs\n (\"%\") are used as the encoding flag, which agrees with RFC 2047.</p>\n\n<p>Specifically, an asterisk at the end of a parameter name acts as an\n indicator that character set and language information may appear at\n the beginning of the parameter value. A single quote is used to\n separate the character set, language, and actual value information in\n the parameter value string, and an percent sign is used to flag\n octets encoded in hexadecimal. For example:</p>\n\n<pre><code> Content-Type: application/x-stuff;\n title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25487/"
] |
My company runs a webmail service, and we were trying to diagnose a problem with Word downloads not opening automatically - the same \*.doc file download from Yahoo Mail would open, but one from ours would not.
In the course of investigating the headers we saw this coming from Yahoo:
```
content-disposition attachment; filename*="utf-8''word document.doc";
```
Whereas our headers were like this:
```
content-disposition attachment; filename="word document.doc";
```
What exactly is Yahoo doing with the additional asterisk and utf-8'' designation?
|
I think the correct answer to this is in rfc 2231:
Asterisks ("\*") are reused to provide the indicator that language and
character set information is present and encoding is being used. A
single quote ("'") is used to delimit the character set and language
information at the beginning of the parameter value. Percent signs
("%") are used as the encoding flag, which agrees with RFC 2047.
Specifically, an asterisk at the end of a parameter name acts as an
indicator that character set and language information may appear at
the beginning of the parameter value. A single quote is used to
separate the character set, language, and actual value information in
the parameter value string, and an percent sign is used to flag
octets encoded in hexadecimal. For example:
```
Content-Type: application/x-stuff;
title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A
```
|
186,854 |
<p>I can hookup to <code>AppDomain.CurrentDomain.UnhandledException</code> to log exceptions from background threads, but how do I prevent them terminating the runtime?</p>
|
[
{
"answer_id": 186863,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 3,
"selected": false,
"text": "<p>From Joe Albahari's excellent <a href=\"http://www.albahari.com/threading/\" rel=\"noreferrer\">threading</a> article:</p>\n\n<blockquote>\n <p>The .NET framework provides a\n lower-level event for global exception\n handling:\n AppDomain.UnhandledException. This\n event fires when there's an unhandled\n exception in any thread, and in any\n type of application (with or without a\n user interface). However, while it\n offers a good last-resort mechanism\n for logging untrapped exceptions, it\n provides no means of preventing the\n application from shutting down – and\n no means to suppress the .NET\n unhandled exception dialog.</p>\n \n <p>In production applications, explicit\n exception handling is required on all\n thread entry methods. One can cut the\n work by using a wrapper or helper\n class to perform the job, such as\n BackgroundWorker (discussed in Part\n 3).</p>\n</blockquote>\n"
},
{
"answer_id": 186879,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "<p>First, you really should try not to have exceptions thrown - and not handled - in a background thread. If you control the way your delegate is run, encapsulate it in a try catch block and figure a way to pass the exception information back to your main thread (using EndInvoke if you explicitly called BeginInvoke, or by updating some shared state somewhere).</p>\n\n<p>Ignoring a unhandled exception can be dangerous. If you have a real un-handlable exception (OutOfMemoryException comes into mind), there's not much you can do anyway and your process is basically doomed.</p>\n\n<p>Back to .Net 1.1, an unhandled exception in a backgroundthread would just be thrown to nowhere and the main thread would gladly plough on. And that could have nasty repercussions. So in .Net 2.0 this behavior has changed.</p>\n\n<p>Now, an unhandled exception thrown in a thread which is not the main thread will terminate the process. You may be notified of this (by subscribing to the event on the AppDomain) but the process will die nonetheless.</p>\n\n<p>Since this can be inconvenient (when you don't know what will be run in the thread and you are not absolutely sure it's properly guarded, and your main thread must be resilient), there's a workaround. It's intended as a legacy settings (meaning, it's strongly suggested you make sure you don't have stray threads) but you can force the former behavior this way :</p>\n\n<p>Just add this setting to your service/application/whatever configuration file :</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><configuration>\n <runtime>\n <!-- the following setting prevents the host from closing when an unhandled exception is thrown -->\n <legacyUnhandledExceptionPolicy enabled=\"1\" />\n </runtime>\n</configuration>\n</code></pre>\n\n<p>It doesn't seem to work with ASP.NET, though.</p>\n\n<p>For more information (and a huge warning that this setting may not be supported in upcoming versions of the CLR) see <a href=\"http://msdn.microsoft.com/en-us/library/ms228965.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms228965.aspx</a></p>\n"
},
{
"answer_id": 186896,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a great blog post about this problem: <a href=\"http://www.julmar.com/blog/mark/PermaLink,guid,f733e261-5d39-4ca1-be1a-c422f3cf1f1b.aspx\" rel=\"nofollow noreferrer\">Handling \"Unhandled Exceptions\" in .NET 2.0</a></p>\n\n<p>IMO it would be right to handle exceptions in background threads manually and re-throw them via callback if necessary.</p>\n\n<pre><code>delegate void ExceptionCallback(Exception ex);\n\nvoid MyExceptionCallback(Exception ex)\n{\n throw ex; // Handle/re-throw if necessary\n}\n\nvoid BackgroundThreadProc(Object obj)\n{\n try \n { \n throw new Exception(); \n }\n catch (Exception ex)\n { \n this.BeginInvoke(new ExceptionCallback(MyExceptionCallback), ex); \n }\n}\n\nprivate void Test()\n{\n ThreadPool.QueueUserWorkItem(new WaitCallback(BackgroundThreadProc));\n}\n</code></pre>\n"
},
{
"answer_id": 1056573,
"author": "bohdan_trotsenko",
"author_id": 58768,
"author_profile": "https://Stackoverflow.com/users/58768",
"pm_score": 3,
"selected": false,
"text": "<p>Keeping the answer short, yes, you do can prevent the runtime from terminating.</p>\n\n<p>Here is a demo of the workaround:</p>\n\n<pre><code>class Program\n{\n void Run()\n {\n AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);\n\n Console.WriteLine(\"Press enter to exit.\");\n\n do\n {\n (new Thread(delegate()\n {\n throw new ArgumentException(\"ha-ha\");\n })).Start();\n\n } while (Console.ReadLine().Trim().ToLowerInvariant() == \"x\");\n\n\n Console.WriteLine(\"last good-bye\");\n }\n\n int r = 0;\n\n void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)\n {\n Interlocked.Increment(ref r);\n Console.WriteLine(\"handled. {0}\", r);\n Console.WriteLine(\"Terminating \" + e.IsTerminating.ToString());\n\n Thread.CurrentThread.IsBackground = true;\n Thread.CurrentThread.Name = \"Dead thread\"; \n\n while (true)\n Thread.Sleep(TimeSpan.FromHours(1));\n //Process.GetCurrentProcess().Kill();\n }\n\n static void Main(string[] args)\n {\n Console.WriteLine(\"...\");\n (new Program()).Run();\n }\n}\n</code></pre>\n\n<p>Essentially, you just did not let the runtime to show the \"... program has stopped working\" dialog.</p>\n\n<p>In case you need to log the exception and <em>silently</em> exit, you can call <code>Process.GetCurrentProcess().Kill();</code></p>\n"
},
{
"answer_id": 47960142,
"author": "Evgeny Gorbovoy",
"author_id": 2362847,
"author_profile": "https://Stackoverflow.com/users/2362847",
"pm_score": 2,
"selected": false,
"text": "<pre><code> AppDomain.CurrentDomain.UnhandledException += (sender, e2) =>\n {\n Thread.CurrentThread.Join();\n };\n</code></pre>\n\n<p>But be careful, this code will freeze all the stack memory of the Thread and thread's managed object itself.\nHowever, if your application is in determined state (may be you threw LimitedDemoFunctionalityException or OperationStopWithUserMessageException) and you are not developing 24/7 application this trick will work.</p>\n\n<p>Finally, I think MS should allow developers to override the logic of unhandled exceptions from the top of the stack.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5978/"
] |
I can hookup to `AppDomain.CurrentDomain.UnhandledException` to log exceptions from background threads, but how do I prevent them terminating the runtime?
|
First, you really should try not to have exceptions thrown - and not handled - in a background thread. If you control the way your delegate is run, encapsulate it in a try catch block and figure a way to pass the exception information back to your main thread (using EndInvoke if you explicitly called BeginInvoke, or by updating some shared state somewhere).
Ignoring a unhandled exception can be dangerous. If you have a real un-handlable exception (OutOfMemoryException comes into mind), there's not much you can do anyway and your process is basically doomed.
Back to .Net 1.1, an unhandled exception in a backgroundthread would just be thrown to nowhere and the main thread would gladly plough on. And that could have nasty repercussions. So in .Net 2.0 this behavior has changed.
Now, an unhandled exception thrown in a thread which is not the main thread will terminate the process. You may be notified of this (by subscribing to the event on the AppDomain) but the process will die nonetheless.
Since this can be inconvenient (when you don't know what will be run in the thread and you are not absolutely sure it's properly guarded, and your main thread must be resilient), there's a workaround. It's intended as a legacy settings (meaning, it's strongly suggested you make sure you don't have stray threads) but you can force the former behavior this way :
Just add this setting to your service/application/whatever configuration file :
```xml
<configuration>
<runtime>
<!-- the following setting prevents the host from closing when an unhandled exception is thrown -->
<legacyUnhandledExceptionPolicy enabled="1" />
</runtime>
</configuration>
```
It doesn't seem to work with ASP.NET, though.
For more information (and a huge warning that this setting may not be supported in upcoming versions of the CLR) see <http://msdn.microsoft.com/en-us/library/ms228965.aspx>
|
186,857 |
<p>I have a string that looks like this:</p>
<pre><code>"Name1=Value1;Name2=Value2;Name3=Value3"
</code></pre>
<p>Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this:</p>
<pre><code>dict = {
"Name1": "Value1",
"Name2": "Value2",
"Name3": "Value3"
}
</code></pre>
<p>I have looked through the modules available but can't seem to find anything that matches.</p>
<hr>
<p>Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function.</p>
<p>I'll do it myself then.</p>
|
[
{
"answer_id": 186873,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 8,
"selected": true,
"text": "<p>There's no builtin, but you can accomplish this fairly simply with a generator comprehension:</p>\n\n<pre><code>s= \"Name1=Value1;Name2=Value2;Name3=Value3\"\ndict(item.split(\"=\") for item in s.split(\";\"))\n</code></pre>\n\n<p><strong>[Edit]</strong> From your update you indicate you may need to handle quoting. This does complicate things, depending on what the exact format you are looking for is (what quote chars are accepted, what escape chars etc). You may want to look at the csv module to see if it can cover your format. Here's an example: (Note that the API is a little clunky for this example, as CSV is designed to iterate through a sequence of records, hence the .next() calls I'm making to just look at the first line. Adjust to suit your needs):</p>\n\n<pre><code>>>> s = \"Name1='Value=2';Name2=Value2;Name3=Value3\"\n\n>>> dict(csv.reader([item], delimiter='=', quotechar=\"'\").next() \n for item in csv.reader([s], delimiter=';', quotechar=\"'\").next())\n\n{'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1=2'}\n</code></pre>\n\n<p>Depending on the exact structure of your format, you may need to write your own simple parser however.</p>\n"
},
{
"answer_id": 5149981,
"author": "Kyle Gibson",
"author_id": 513197,
"author_profile": "https://Stackoverflow.com/users/513197",
"pm_score": 3,
"selected": false,
"text": "<p>This comes close to doing what you wanted:</p>\n\n<pre><code>>>> import urlparse\n>>> urlparse.parse_qs(\"Name1=Value1;Name2=Value2;Name3=Value3\")\n{'Name2': ['Value2'], 'Name3': ['Value3'], 'Name1': ['Value1']}\n</code></pre>\n"
},
{
"answer_id": 15649648,
"author": "easytiger",
"author_id": 316957,
"author_profile": "https://Stackoverflow.com/users/316957",
"pm_score": -1,
"selected": false,
"text": "<pre><code>easytiger $ cat test.out test.py | sed 's/^/ /'\np_easytiger_quoting:1.84563302994\n{'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1'}\np_brian:2.30507516861\n{'Name2': 'Value2', 'Name3': \"'Value3'\", 'Name1': 'Value1'}\np_kyle:7.22536420822\n{'Name2': ['Value2'], 'Name3': [\"'Value3'\"], 'Name1': ['Value1']}\nimport timeit\nimport urlparse\n\ns = \"Name1=Value1;Name2=Value2;Name3='Value3'\"\n\ndef p_easytiger_quoting(s):\n d = {}\n s = s.replace(\"'\", \"\")\n for x in s.split(';'):\n k, v = x.split('=')\n d[k] = v\n return d\n\n\ndef p_brian(s):\n return dict(item.split(\"=\") for item in s.split(\";\"))\n\ndef p_kyle(s):\n return urlparse.parse_qs(s)\n\n\n\nprint \"p_easytiger_quoting:\" + str(timeit.timeit(lambda: p_easytiger_quoting(s)))\nprint p_easytiger_quoting(s)\n\n\nprint \"p_brian:\" + str(timeit.timeit(lambda: p_brian(s)))\nprint p_brian(s)\n\nprint \"p_kyle:\" + str(timeit.timeit(lambda: p_kyle(s)))\nprint p_kyle(s)\n</code></pre>\n"
},
{
"answer_id": 16189504,
"author": "Rabarberski",
"author_id": 50899,
"author_profile": "https://Stackoverflow.com/users/50899",
"pm_score": -1,
"selected": false,
"text": "<p>IF your Value1, Value2 are just placeholders for actual values, you can also use the <code>dict()</code> function in combination with <code>eval()</code>. </p>\n\n<pre><code>>>> s= \"Name1=1;Name2=2;Name3='string'\"\n>>> print eval('dict('+s.replace(';',',')+')')\n{'Name2: 2, 'Name3': 'string', 'Name1': 1}\n</code></pre>\n\n<p>This is beacuse the <code>dict()</code> function understand the syntax <code>dict(Name1=1, Name2=2,Name3='string')</code>. Spaces in the string (e.g. after each semicolon) are ignored. But note the string values do require quoting.</p>\n"
},
{
"answer_id": 27619606,
"author": "vijay",
"author_id": 601310,
"author_profile": "https://Stackoverflow.com/users/601310",
"pm_score": 1,
"selected": false,
"text": "<p>It can be simply done by string join and list comprehension</p>\n<p><code>",".join(["%s=%s" % x for x in d.items()])</code></p>\n<pre><code>>>d = {'a':1, 'b':2}\n>>','.join(['%s=%s'%x for x in d.items()])\n>>'a=1,b=2'\n</code></pre>\n"
},
{
"answer_id": 54984224,
"author": "D. Om",
"author_id": 11148339,
"author_profile": "https://Stackoverflow.com/users/11148339",
"pm_score": 2,
"selected": false,
"text": "<pre><code>s1 = \"Name1=Value1;Name2=Value2;Name3=Value3\"\n\ndict(map(lambda x: x.split('='), s1.split(';')))\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
] |
I have a string that looks like this:
```
"Name1=Value1;Name2=Value2;Name3=Value3"
```
Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this:
```
dict = {
"Name1": "Value1",
"Name2": "Value2",
"Name3": "Value3"
}
```
I have looked through the modules available but can't seem to find anything that matches.
---
Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function.
I'll do it myself then.
|
There's no builtin, but you can accomplish this fairly simply with a generator comprehension:
```
s= "Name1=Value1;Name2=Value2;Name3=Value3"
dict(item.split("=") for item in s.split(";"))
```
**[Edit]** From your update you indicate you may need to handle quoting. This does complicate things, depending on what the exact format you are looking for is (what quote chars are accepted, what escape chars etc). You may want to look at the csv module to see if it can cover your format. Here's an example: (Note that the API is a little clunky for this example, as CSV is designed to iterate through a sequence of records, hence the .next() calls I'm making to just look at the first line. Adjust to suit your needs):
```
>>> s = "Name1='Value=2';Name2=Value2;Name3=Value3"
>>> dict(csv.reader([item], delimiter='=', quotechar="'").next()
for item in csv.reader([s], delimiter=';', quotechar="'").next())
{'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1=2'}
```
Depending on the exact structure of your format, you may need to write your own simple parser however.
|
186,867 |
<p>I need to stream a file to the Response for saving on the end user's machine. The file is plain text, so what content type can I use to prevent the text being displayed in the browser?</p>
|
[
{
"answer_id": 186871,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "<p>I don't think it works that way.</p>\n\n<p>Use a <code>Content-Disposition: attachment</code> header, but stick with the correct Content-Type.</p>\n"
},
{
"answer_id": 186872,
"author": "Andrew Moore",
"author_id": 26210,
"author_profile": "https://Stackoverflow.com/users/26210",
"pm_score": 5,
"selected": false,
"text": "<p>In most cases, the following should work:</p>\n\n<pre><code>Content-type: application/octet-stream\nContent-Disposition: attachment; filename=\"myfile.txt\"\n</code></pre>\n\n<p>There are some marginal cases of browsers that will still display it as a text file, but none of the mainstream browsers will (I'm talking about browsers embedded in some MIDs).</p>\n\n<hr>\n\n<p><em>EDIT</em>: When this answer was originally published, sending the Mime-Type <code>application/octet-stream</code> was the only reliable way to trigger a download in some browsers. Now in 2016, if you do not need to support an ancient browser, you can safely specify the proper mime-type.</p>\n"
},
{
"answer_id": 186898,
"author": "Mun",
"author_id": 775,
"author_profile": "https://Stackoverflow.com/users/775",
"pm_score": 6,
"selected": true,
"text": "<p>To be on the safe side and ensure consistent behavior in all browsers, it's usually better to use both:</p>\n\n<pre><code>Content-Type: application/octet-stream\nContent-Disposition: attachment;filename=\\\"My Text File.txt\\\"\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
I need to stream a file to the Response for saving on the end user's machine. The file is plain text, so what content type can I use to prevent the text being displayed in the browser?
|
To be on the safe side and ensure consistent behavior in all browsers, it's usually better to use both:
```
Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"My Text File.txt\"
```
|
186,876 |
<p>The following works in Firefox, but breaks in IE7 & 8:</p>
<pre><code>$("#my-first-div, #my-second-div").hide();
</code></pre>
<p>so I have to do this:</p>
<pre><code>$("#my-first-div").hide();
$("#my-second-div").hide();
</code></pre>
<p>Is this normal?</p>
<p>EDIT: ok, my actual real-life code is this:</p>
<pre><code>$("#charges-gsm,#charges-gsm-faq,#charges-gsm-prices").html(html);
</code></pre>
<p>and my error is this</p>
<pre><code>( IE8): Message: 'nodeName' is null or not an object
Line: 19 Char: 150 Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js
</code></pre>
|
[
{
"answer_id": 186914,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 1,
"selected": false,
"text": "<p>Hmm, I can't seem to duplicate the problem in IE7 (both forms work fine for me). How does it break? Does it not hide either, or does it only hide the first one?</p>\n"
},
{
"answer_id": 186925,
"author": "Garry Shutler",
"author_id": 6369,
"author_profile": "https://Stackoverflow.com/users/6369",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried it without a space after the comma? <a href=\"http://docs.jquery.com/Selectors/multiple#selector1selector2selectorN\" rel=\"nofollow noreferrer\">The examples given in the specification have no space.</a></p>\n"
},
{
"answer_id": 186934,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 0,
"selected": false,
"text": "<p><em>Should</em> work, according to the <a href=\"http://docs.jquery.com/Selectors/multiple#selector1selector2selectorN\" rel=\"nofollow noreferrer\">documentation</a>. There's an outside chance you need to remove the trailing space character after the comma.</p>\n"
},
{
"answer_id": 187126,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": true,
"text": "<p>The location you specify states:</p>\n\n<pre><code>Message: 'nodeName' is null or not an object\n Line: 19 Char: 150 Code: 0\n URI: http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\n</code></pre>\n\n<p>That particular piece of jquery is:</p>\n\n<pre><code>nodeName:function(elem,name){\n return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();\n}\n</code></pre>\n\n<p>which is itself a closure created for the call to <code>jQuery.extend()</code>. So I would like to ask, if you do a \"View source\" or its IE equivalent, are there any other occurrences of the string \"nodeName\" that could be interfering with the jQuery one.</p>\n\n<p>Can you also test the following by creating an xx.html file and opeing it in IE7/8? It works fine under Firefox 3 in Ubuntu, with or without the spaces following the commas in the selector.</p>\n\n<pre><code><html>\n <head>\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function(){\n $(\"a\").click(function(event){\n $(\"#charges-gsm,#charges-gsm-faq,#charges-gsm-prices\").html(\"xx\")\n event.preventDefault();\n });\n });\n </script>\n </head>\n <body>\n <a href=\"http://jquery.com/\">jQuery</a>\n <hr>\n <div id=\"charges-gsm\">CHARGES-GSM</div>\n <div id=\"charges-gsm-faq\">CHARGES-GSM-FAQ</div>\n <div id=\"charges-gsm-prices\">CHARGES-GSM-PRICES</div>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 316942,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 0,
"selected": false,
"text": "<p>By chance, is one of your elements nested inside the other? </p>\n\n<p>ie: </p>\n\n<pre><code><div id=\"foo\">\n <div id=\"bar\"> \n <div id=\"baz\">\n </div>\n</div>\n</code></pre>\n\n<p>If so, you may be experiencing a pointer problem, where IE may have freed bar prior to you trying to work out that its a div. The behaviour of </p>\n\n<pre><code>$(\"#foo,#bar,#baz\").html(\"xx\"); \n</code></pre>\n\n<p>In this secenario is: </p>\n\n<ol>\n<li>Replace #foo with xx</li>\n<li>Replace #bar with xx</li>\n<li>Replace #baz with xx</li>\n</ol>\n\n<p>However, if at phases 2 & 3, #bar and #baz no longer exist, you are going to have a little fun. ( it doesn't matter if xx happens to contain a copy of #bar and #baz, they'll likely be different objects, and the initial objects that you're replacing have already been captured, just are no longer in the DOM :/ ) </p>\n\n<p>You can possibly suppress ( yes, gah, awful idea ) this error by encapsulating the procedure in a try/catch </p>\n\n<pre><code>try { \n $(\"#foo,#bar,#baz\").html(\"xx\"); \n}\ncatch( e ) \n{\n /* DO NOTHING D: */ \n}\n</code></pre>\n\n<p>But this is your last resort, right after getting some sort of JS debugger binding IE and tracing the error to its core. </p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
The following works in Firefox, but breaks in IE7 & 8:
```
$("#my-first-div, #my-second-div").hide();
```
so I have to do this:
```
$("#my-first-div").hide();
$("#my-second-div").hide();
```
Is this normal?
EDIT: ok, my actual real-life code is this:
```
$("#charges-gsm,#charges-gsm-faq,#charges-gsm-prices").html(html);
```
and my error is this
```
( IE8): Message: 'nodeName' is null or not an object
Line: 19 Char: 150 Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js
```
|
The location you specify states:
```
Message: 'nodeName' is null or not an object
Line: 19 Char: 150 Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js
```
That particular piece of jquery is:
```
nodeName:function(elem,name){
return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();
}
```
which is itself a closure created for the call to `jQuery.extend()`. So I would like to ask, if you do a "View source" or its IE equivalent, are there any other occurrences of the string "nodeName" that could be interfering with the jQuery one.
Can you also test the following by creating an xx.html file and opeing it in IE7/8? It works fine under Firefox 3 in Ubuntu, with or without the spaces following the commas in the selector.
```
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function(event){
$("#charges-gsm,#charges-gsm-faq,#charges-gsm-prices").html("xx")
event.preventDefault();
});
});
</script>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<hr>
<div id="charges-gsm">CHARGES-GSM</div>
<div id="charges-gsm-faq">CHARGES-GSM-FAQ</div>
<div id="charges-gsm-prices">CHARGES-GSM-PRICES</div>
</body>
</html>
```
|
186,883 |
<p>When deploying a ready to use erlang application I <strong>don't</strong> want the user to </p>
<ul>
<li>Find the right erl release on the
internet.</li>
<li>Install the erl vm</li>
<li>unzip and decide a location for the beam files (with the application)</li>
<li>read a readme</li>
<li>modify anything that even looks like a config file</li>
</ul>
<p>I have a couple of ideas of what could be a way but I would like to get some input.</p>
|
[
{
"answer_id": 186914,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 1,
"selected": false,
"text": "<p>Hmm, I can't seem to duplicate the problem in IE7 (both forms work fine for me). How does it break? Does it not hide either, or does it only hide the first one?</p>\n"
},
{
"answer_id": 186925,
"author": "Garry Shutler",
"author_id": 6369,
"author_profile": "https://Stackoverflow.com/users/6369",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried it without a space after the comma? <a href=\"http://docs.jquery.com/Selectors/multiple#selector1selector2selectorN\" rel=\"nofollow noreferrer\">The examples given in the specification have no space.</a></p>\n"
},
{
"answer_id": 186934,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 0,
"selected": false,
"text": "<p><em>Should</em> work, according to the <a href=\"http://docs.jquery.com/Selectors/multiple#selector1selector2selectorN\" rel=\"nofollow noreferrer\">documentation</a>. There's an outside chance you need to remove the trailing space character after the comma.</p>\n"
},
{
"answer_id": 187126,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": true,
"text": "<p>The location you specify states:</p>\n\n<pre><code>Message: 'nodeName' is null or not an object\n Line: 19 Char: 150 Code: 0\n URI: http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\n</code></pre>\n\n<p>That particular piece of jquery is:</p>\n\n<pre><code>nodeName:function(elem,name){\n return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();\n}\n</code></pre>\n\n<p>which is itself a closure created for the call to <code>jQuery.extend()</code>. So I would like to ask, if you do a \"View source\" or its IE equivalent, are there any other occurrences of the string \"nodeName\" that could be interfering with the jQuery one.</p>\n\n<p>Can you also test the following by creating an xx.html file and opeing it in IE7/8? It works fine under Firefox 3 in Ubuntu, with or without the spaces following the commas in the selector.</p>\n\n<pre><code><html>\n <head>\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function(){\n $(\"a\").click(function(event){\n $(\"#charges-gsm,#charges-gsm-faq,#charges-gsm-prices\").html(\"xx\")\n event.preventDefault();\n });\n });\n </script>\n </head>\n <body>\n <a href=\"http://jquery.com/\">jQuery</a>\n <hr>\n <div id=\"charges-gsm\">CHARGES-GSM</div>\n <div id=\"charges-gsm-faq\">CHARGES-GSM-FAQ</div>\n <div id=\"charges-gsm-prices\">CHARGES-GSM-PRICES</div>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 316942,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 0,
"selected": false,
"text": "<p>By chance, is one of your elements nested inside the other? </p>\n\n<p>ie: </p>\n\n<pre><code><div id=\"foo\">\n <div id=\"bar\"> \n <div id=\"baz\">\n </div>\n</div>\n</code></pre>\n\n<p>If so, you may be experiencing a pointer problem, where IE may have freed bar prior to you trying to work out that its a div. The behaviour of </p>\n\n<pre><code>$(\"#foo,#bar,#baz\").html(\"xx\"); \n</code></pre>\n\n<p>In this secenario is: </p>\n\n<ol>\n<li>Replace #foo with xx</li>\n<li>Replace #bar with xx</li>\n<li>Replace #baz with xx</li>\n</ol>\n\n<p>However, if at phases 2 & 3, #bar and #baz no longer exist, you are going to have a little fun. ( it doesn't matter if xx happens to contain a copy of #bar and #baz, they'll likely be different objects, and the initial objects that you're replacing have already been captured, just are no longer in the DOM :/ ) </p>\n\n<p>You can possibly suppress ( yes, gah, awful idea ) this error by encapsulating the procedure in a try/catch </p>\n\n<pre><code>try { \n $(\"#foo,#bar,#baz\").html(\"xx\"); \n}\ncatch( e ) \n{\n /* DO NOTHING D: */ \n}\n</code></pre>\n\n<p>But this is your last resort, right after getting some sort of JS debugger binding IE and tracing the error to its core. </p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15638/"
] |
When deploying a ready to use erlang application I **don't** want the user to
* Find the right erl release on the
internet.
* Install the erl vm
* unzip and decide a location for the beam files (with the application)
* read a readme
* modify anything that even looks like a config file
I have a couple of ideas of what could be a way but I would like to get some input.
|
The location you specify states:
```
Message: 'nodeName' is null or not an object
Line: 19 Char: 150 Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js
```
That particular piece of jquery is:
```
nodeName:function(elem,name){
return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();
}
```
which is itself a closure created for the call to `jQuery.extend()`. So I would like to ask, if you do a "View source" or its IE equivalent, are there any other occurrences of the string "nodeName" that could be interfering with the jQuery one.
Can you also test the following by creating an xx.html file and opeing it in IE7/8? It works fine under Firefox 3 in Ubuntu, with or without the spaces following the commas in the selector.
```
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function(event){
$("#charges-gsm,#charges-gsm-faq,#charges-gsm-prices").html("xx")
event.preventDefault();
});
});
</script>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<hr>
<div id="charges-gsm">CHARGES-GSM</div>
<div id="charges-gsm-faq">CHARGES-GSM-FAQ</div>
<div id="charges-gsm-prices">CHARGES-GSM-PRICES</div>
</body>
</html>
```
|
186,891 |
<p>If I am passing an object to a method, why should I use the ref keyword? Isn't this the default behaviour anyway?</p>
<p>For example:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(t);
Console.WriteLine(t.Something);
}
static public void DoSomething(TestRef t)
{
t.Something = "Bar";
}
}
public class TestRef
{
public string Something { get; set; }
}
</code></pre>
<p>The output is "Bar" which means that the object was passed as a reference.</p>
|
[
{
"answer_id": 186897,
"author": "Andrew",
"author_id": 826,
"author_profile": "https://Stackoverflow.com/users/826",
"pm_score": 2,
"selected": false,
"text": "<p>If you're passing a value, however, things are different. You can force a value to be passed by reference. This allows you to pass an integer to a method, for example, and have the method modify the integer on your behalf.</p>\n"
},
{
"answer_id": 186904,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 4,
"selected": false,
"text": "<p>With <code>ref</code> you can write:</p>\n\n<pre><code>static public void DoSomething(ref TestRef t)\n{\n t = new TestRef();\n}\n</code></pre>\n\n<p>And t will be changed after the method has completed.</p>\n"
},
{
"answer_id": 186907,
"author": "Scott Langham",
"author_id": 11898,
"author_profile": "https://Stackoverflow.com/users/11898",
"pm_score": 9,
"selected": true,
"text": "<p>Pass a <code>ref</code> if you want to change what the object is:</p>\n<pre><code>TestRef t = new TestRef();\nt.Something = "Foo";\nDoSomething(ref t);\n\nvoid DoSomething(ref TestRef t)\n{\n t = new TestRef();\n t.Something = "Not just a changed t, but a completely different TestRef object";\n}\n</code></pre>\n<p>After calling DoSomething, <code>t</code> does not refer to the original <code>new TestRef</code>, but refers to a completely different object.</p>\n<p>This may be useful too if you want to change the value of an immutable object, e.g. a <code>string</code>. You cannot change the value of a <code>string</code> once it has been created. But by using a <code>ref</code>, you could create a function that changes the string for another one that has a different value.</p>\n<p>It is not a good idea to use <code>ref</code> unless it is needed. Using <code>ref</code> gives the method freedom to change the argument for something else, callers of the method will need to be coded to ensure they handle this possibility.</p>\n<p>Also, when the parameter type is an object, then object variables always act as references to the object. This means that when the <code>ref</code> keyword is used you've got a reference to a reference. This allows you to do things as described in the example given above. But, when the parameter type is a primitive value (e.g. <code>int</code>), then if this parameter is assigned to within the method, the value of the argument that was passed in will be changed after the method returns:</p>\n<pre><code>int x = 1;\nChange(ref x);\nDebug.Assert(x == 5);\nWillNotChange(x);\nDebug.Assert(x == 5); // Note: x doesn't become 10\n\nvoid Change(ref int x)\n{\n x = 5;\n}\n\nvoid WillNotChange(int x)\n{\n x = 10;\n}\n</code></pre>\n"
},
{
"answer_id": 186910,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 4,
"selected": false,
"text": "<p>Since TestRef is a class (which are reference objects), you can change the contents inside t without passing it as a ref. However, if you pass t as a ref, TestRef can change what the original t refers to. i.e. make it point to a different object.</p>\n"
},
{
"answer_id": 186911,
"author": "Isak Savo",
"author_id": 8521,
"author_profile": "https://Stackoverflow.com/users/8521",
"pm_score": 2,
"selected": false,
"text": "<p>By using the <code>ref</code> keyword with reference types you are effectively passing a reference to the reference. In many ways it's the same as using the <code>out</code> keyword but with the minor difference that there's no guarantee that the method will actually assign anything to the <code>ref</code>'ed parameter. </p>\n"
},
{
"answer_id": 186928,
"author": "pezi_pink_squirrel",
"author_id": 24757,
"author_profile": "https://Stackoverflow.com/users/24757",
"pm_score": 3,
"selected": false,
"text": "<p>This is like passing a pointer to a pointer in C. In .NET this will allow you to change what the original T refers to, <em>personally</em> though I think if you are doing that in .NET you have probably got a design issue!</p>\n"
},
{
"answer_id": 186947,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": false,
"text": "<p>You need to distinguish between "passing a reference by value", and "passing a parameter/argument by reference".</p>\n<p>I've written a <a href=\"http://jonskeet.uk/csharp/parameters.html\" rel=\"noreferrer\">reasonably long article on the subject</a> to avoid having to write carefully each time this comes up on newsgroups</p>\n"
},
{
"answer_id": 186949,
"author": "Ricardo Amores",
"author_id": 10136,
"author_profile": "https://Stackoverflow.com/users/10136",
"pm_score": 6,
"selected": false,
"text": "<p>In .NET when you pass any parameter to a method, a copy is created. In value types means that any modification you make to the value is at the method scope, and is lost when you exit the method.</p>\n\n<p>When passing a Reference Type, a copy is also made, but it is a copy of a reference, i.e. now you have TWO references in memory to the same object. So, if you use the reference to modify the object, it gets modified. But if you modify the reference itself - we must remember it is a copy - then any changes are also lost upon exiting the method.</p>\n\n<p>As people have said before, an assignment is a modification of the reference, thus is lost:</p>\n\n<pre><code>public void Method1(object obj) { \n obj = new Object(); \n}\n\npublic void Method2(object obj) { \n obj = _privateObject; \n}\n</code></pre>\n\n<p>The methods above does not modifies the original object.</p>\n\n<p>A little modification of your example</p>\n\n<pre><code> using System;\n\n class Program\n {\n static void Main(string[] args)\n {\n TestRef t = new TestRef();\n t.Something = \"Foo\";\n\n DoSomething(t);\n Console.WriteLine(t.Something);\n\n }\n\n static public void DoSomething(TestRef t)\n {\n t = new TestRef();\n t.Something = \"Bar\";\n }\n }\n\n\n\n public class TestRef\n {\n private string s;\n public string Something \n { \n get {return s;} \n set { s = value; }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 30156549,
"author": "guneysus",
"author_id": 1766716,
"author_profile": "https://Stackoverflow.com/users/1766716",
"pm_score": 2,
"selected": false,
"text": "<p><code>ref</code> mimics (or behaves) as a global area just for two scopes:</p>\n\n<ul>\n<li>Caller</li>\n<li>Callee.</li>\n</ul>\n"
},
{
"answer_id": 31480539,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 3,
"selected": false,
"text": "<p>Think of variables (e.g. <code>foo</code>) of reference types (e.g. <code>List<T></code>) as holding <em>object identifiers</em> of the form "Object #24601". Suppose the statement <code>foo = new List<int> {1,5,7,9};</code> causes <code>foo</code> to hold "Object #24601" (a list with four items). Then calling <code>foo.Length</code> will ask Object #24601 for its length, and it will respond 4, so <code>foo.Length</code> will equal 4.</p>\n<p>If <code>foo</code> is passed to a method without using <code>ref</code>, that method might make changes to Object #24601. As a consequence of such changes, <code>foo.Length</code> might no longer equal 4. The method itself, however, will be unable to change <code>foo</code>, which will continue to hold "Object #24601".</p>\n<p>Passing <code>foo</code> as a <code>ref</code> parameter will allow the called method to make changes not just to Object #24601, but also to <code>foo</code> itself. The method might create a new Object #8675309 and store a reference to that in <code>foo</code>. If it does so, <code>foo</code> would no longer hold "Object #24601", but instead "Object #8675309".</p>\n<p>In practice, reference-type variables don't hold strings of the form "Object #8675309"; they don't even hold anything that can be meaningfully converted into a number. Even though each reference-type variable will hold some bit pattern, there is no fixed relationship between the bit patterns stored in such variables and the objects they identify. There is no way code could extract information from an object or a reference to it, and later determine whether another reference identified the same object, unless the code either held or knew of a reference that identified the original object.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93743/"
] |
If I am passing an object to a method, why should I use the ref keyword? Isn't this the default behaviour anyway?
For example:
```
class Program
{
static void Main(string[] args)
{
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(t);
Console.WriteLine(t.Something);
}
static public void DoSomething(TestRef t)
{
t.Something = "Bar";
}
}
public class TestRef
{
public string Something { get; set; }
}
```
The output is "Bar" which means that the object was passed as a reference.
|
Pass a `ref` if you want to change what the object is:
```
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(ref t);
void DoSomething(ref TestRef t)
{
t = new TestRef();
t.Something = "Not just a changed t, but a completely different TestRef object";
}
```
After calling DoSomething, `t` does not refer to the original `new TestRef`, but refers to a completely different object.
This may be useful too if you want to change the value of an immutable object, e.g. a `string`. You cannot change the value of a `string` once it has been created. But by using a `ref`, you could create a function that changes the string for another one that has a different value.
It is not a good idea to use `ref` unless it is needed. Using `ref` gives the method freedom to change the argument for something else, callers of the method will need to be coded to ensure they handle this possibility.
Also, when the parameter type is an object, then object variables always act as references to the object. This means that when the `ref` keyword is used you've got a reference to a reference. This allows you to do things as described in the example given above. But, when the parameter type is a primitive value (e.g. `int`), then if this parameter is assigned to within the method, the value of the argument that was passed in will be changed after the method returns:
```
int x = 1;
Change(ref x);
Debug.Assert(x == 5);
WillNotChange(x);
Debug.Assert(x == 5); // Note: x doesn't become 10
void Change(ref int x)
{
x = 5;
}
void WillNotChange(int x)
{
x = 10;
}
```
|
186,894 |
<p>I am looking for the best way to test if a website is alive from a C# application.</p>
<h3>Background</h3>
<p>My application consists of a <em>Winforms UI</em>, a backend <em>WCF service</em> and a <em>website</em> to publish content to the UI and other consumers. To prevent the situation where the UI starts up and fails to work properly because of a missing WCF service or website being down I have added an app startup check to ensure that all everything is alive.</p>
<p>The application is being written in C#, .NET 3.5, Visual Studio 2008</p>
<h3>Current Solution</h3>
<p>Currently I am making a web request to a test page on the website that will inturn test the web site and then display a result.</p>
<pre><code>WebRequest request = WebRequest.Create("http://localhost/myContentSite/test.aspx");
WebResponse response = request.GetResponse();
</code></pre>
<p>I am assuming that if there are no exceptions thown during this call then all is well and the UI can start.</p>
<h3>Question</h3>
<p>Is this the simplest, right way or is there some other sneaky call that I don't know about in C# or a better way to do it.</p>
|
[
{
"answer_id": 186915,
"author": "Robert Rouse",
"author_id": 25129,
"author_profile": "https://Stackoverflow.com/users/25129",
"pm_score": -1,
"selected": false,
"text": "<p>You'll want to check the status code for OK (status 200).</p>\n"
},
{
"answer_id": 186931,
"author": "Echostorm",
"author_id": 12862,
"author_profile": "https://Stackoverflow.com/users/12862",
"pm_score": 8,
"selected": true,
"text": "<pre><code>HttpWebResponse response = (HttpWebResponse)request.GetResponse();\nif (response == null || response.StatusCode != HttpStatusCode.OK)\n</code></pre>\n\n<p>As @Yanga mentioned, HttpClient is probably the more common way to do this now.</p>\n\n<pre><code>HttpClient client = new HttpClient();\nvar checkingResponse = await client.GetAsync(url);\nif (!checkingResponse.IsSuccessStatusCode)\n{\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 186936,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming the WCF service and the website live in the same web app, you can use a \"Status\" WebService that returns the application status. You probably want to do some of the following:</p>\n\n<ul>\n<li>Test that the database is up and running (good connection string, service is up, etc...)</li>\n<li>Test that the website is working (how exactly depends on the website)</li>\n<li>Test that WCF is working (how exactly depends on your implementation)</li>\n<li>Added bonus: you can return some versioning info on the service if you need to support different releases in the future.</li>\n</ul>\n\n<p>Then, you create a client on the Win.Forms app for the WebService. If the WS is not responding (i.e. you get some exception on invoke) then the website is down (like a \"general error\").<br>\nIf the WS responds, you can parse the result and make sure that everything works, or if something is broken, return more information.</p>\n"
},
{
"answer_id": 186951,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 3,
"selected": false,
"text": "<p>from the <a href=\"http://www.codeplex.com/NDiagnostics\" rel=\"noreferrer\">NDiagnostics</a> project on CodePlex...</p>\n\n<pre><code>public override bool WebSiteIsAvailable(string Url)\n{\n string Message = string.Empty;\n HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);\n\n // Set the credentials to the current user account\n request.Credentials = System.Net.CredentialCache.DefaultCredentials;\n request.Method = \"GET\";\n\n try\n {\n using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n {\n // Do nothing; we're only testing to see if we can get the response\n }\n }\n catch (WebException ex)\n {\n Message += ((Message.Length > 0) ? \"\\n\" : \"\") + ex.Message;\n }\n\n return (Message.Length == 0);\n}\n</code></pre>\n"
},
{
"answer_id": 3939689,
"author": "Maxymus",
"author_id": 447358,
"author_profile": "https://Stackoverflow.com/users/447358",
"pm_score": 4,
"selected": false,
"text": "<p>While using WebResponse please make sure that you close the response stream ie (.close) else it would hang the machine after certain repeated execution.\nEg </p>\n\n<pre><code>HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sURL);\nHttpWebResponse response = (HttpWebResponse)req.GetResponse();\n// your code here\nresponse.Close();\n</code></pre>\n"
},
{
"answer_id": 26860825,
"author": "NoloMokgosi",
"author_id": 2787567,
"author_profile": "https://Stackoverflow.com/users/2787567",
"pm_score": -1,
"selected": false,
"text": "<p>Solution from: <a href=\"https://stackoverflow.com/questions/7523741/how-do-you-check-if-a-website-is-online-in-c\">How do you check if a website is online in C#?</a></p>\n\n<pre><code>var ping = new System.Net.NetworkInformation.Ping();\n\nvar result = ping.Send(\"https://www.stackoverflow.com\");\n\nif (result.Status != System.Net.NetworkInformation.IPStatus.Success)\n return;\n</code></pre>\n"
},
{
"answer_id": 48791943,
"author": "Yanga",
"author_id": 3173214,
"author_profile": "https://Stackoverflow.com/users/3173214",
"pm_score": 3,
"selected": false,
"text": "<p>We can today update the answers using <a href=\"https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.118).aspx\" rel=\"noreferrer\">HttpClient()</a>:</p>\n\n<pre><code>HttpClient Client = new HttpClient();\nvar result = await Client.GetAsync(\"https://stackoverflow.com\");\nint StatusCode = (int)result.StatusCode;\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231/"
] |
I am looking for the best way to test if a website is alive from a C# application.
### Background
My application consists of a *Winforms UI*, a backend *WCF service* and a *website* to publish content to the UI and other consumers. To prevent the situation where the UI starts up and fails to work properly because of a missing WCF service or website being down I have added an app startup check to ensure that all everything is alive.
The application is being written in C#, .NET 3.5, Visual Studio 2008
### Current Solution
Currently I am making a web request to a test page on the website that will inturn test the web site and then display a result.
```
WebRequest request = WebRequest.Create("http://localhost/myContentSite/test.aspx");
WebResponse response = request.GetResponse();
```
I am assuming that if there are no exceptions thown during this call then all is well and the UI can start.
### Question
Is this the simplest, right way or is there some other sneaky call that I don't know about in C# or a better way to do it.
|
```
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response == null || response.StatusCode != HttpStatusCode.OK)
```
As @Yanga mentioned, HttpClient is probably the more common way to do this now.
```
HttpClient client = new HttpClient();
var checkingResponse = await client.GetAsync(url);
if (!checkingResponse.IsSuccessStatusCode)
{
return false;
}
```
|
186,916 |
<p>I have a python script that analyzes a set of error messages and checks for each message if it matches a certain pattern (regular expression) in order to group these messages. For example "file x does not exist" and "file y does not exist" would match "file .* does not exist" and be accounted as two occurrences of "file not found" category. </p>
<p>As the number of patterns and categories is growing, I'd like to put these couples "regular expression/display string" in a configuration file, basically a dictionary serialization of some sort.</p>
<p>I would like this file to be editable by hand, so I'm discarding any form of binary serialization, and also I'd rather not resort to xml serialization to avoid problems with characters to escape (& <> and so on...).</p>
<p>Do you have any idea of what could be a good way of accomplishing this?</p>
<p>Update: thanks to Daren Thomas and Federico Ramponi, but I cannot have an external python file with possibly arbitrary code.</p>
|
[
{
"answer_id": 186937,
"author": "Andrew Wilkinson",
"author_id": 2990,
"author_profile": "https://Stackoverflow.com/users/2990",
"pm_score": 2,
"selected": false,
"text": "<p>I think you want the <a href=\"http://docs.python.org/library/configparser.html#module-ConfigParser\" rel=\"nofollow noreferrer\">ConfigParser</a> module in the standard library. It reads and writes INI style files. The examples and documentation in the standard documentation I've linked to are very comprehensive.</p>\n"
},
{
"answer_id": 186990,
"author": "sheats",
"author_id": 4915,
"author_profile": "https://Stackoverflow.com/users/4915",
"pm_score": 3,
"selected": false,
"text": "<p>I've heard that <a href=\"http://www.voidspace.org.uk/python/configobj.html\" rel=\"nofollow noreferrer\" title=\"ConfigObj\">ConfigObj</a> is easier to work with than ConfigParser. It is used by a lot of big projects, IPython, Trac, Turbogears, etc... </p>\n\n<p>From their <a href=\"http://www.voidspace.org.uk/python/configobj.html#introduction\" rel=\"nofollow noreferrer\">introduction</a>:</p>\n\n<p>ConfigObj is a simple but powerful config file reader and writer: an ini file round tripper. Its main feature is that it is very easy to use, with a straightforward programmer's interface and a simple syntax for config files. It has lots of other features though :</p>\n\n<ul>\n<li>Nested sections (subsections), to any level</li>\n<li>List values</li>\n<li>Multiple line values</li>\n<li>String interpolation (substitution)</li>\n<li>Integrated with a powerful validation system\n\n<ul>\n<li>including automatic type checking/conversion</li>\n<li>repeated sections</li>\n<li>and allowing default values</li>\n</ul></li>\n<li>When writing out config files, ConfigObj preserves all comments and the order of members and sections</li>\n<li>Many useful methods and options for working with configuration files (like the 'reload' method)</li>\n<li>Full Unicode support</li>\n</ul>\n"
},
{
"answer_id": 187011,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 2,
"selected": false,
"text": "<p>If you are the only one that has access to the configuration file, you can use a simple, low-level solution. Keep the \"dictionary\" in a text file as a list of tuples (regexp, message) exactly as if it was a python expression:\n<pre><code>[\n(\"file .* does not exist\", \"file not found\"),\n(\"user .* not authorized\", \"authorization error\")\n]\n</pre></code>\nIn your code, load it, then eval it, and compile the regexps in the result:\n<pre><code>f = open(\"messages.py\")\nmessages = eval(f.read()) # caution: you must be <em>sure</em> of what's in that file\nf.close()\nmessages = [(re.compile(r), m) for (r,m) in messages]\n</pre></code>\nand you end up with a list of tuples (compiled_regexp, message).</p>\n"
},
{
"answer_id": 187045,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 5,
"selected": false,
"text": "<p>I sometimes just write a python module (i.e. file) called <code>config.py</code> or something with following contents:</p>\n\n<pre><code>config = {\n 'name': 'hello',\n 'see?': 'world'\n}\n</code></pre>\n\n<p>this can then be 'read' like so:</p>\n\n<pre><code>from config import config\nconfig['name']\nconfig['see?']\n</code></pre>\n\n<p>easy.</p>\n"
},
{
"answer_id": 187135,
"author": "davidavr",
"author_id": 8247,
"author_profile": "https://Stackoverflow.com/users/8247",
"pm_score": 2,
"selected": false,
"text": "<p>I typically do as Daren suggested, just make your config file a Python script:</p>\n\n<pre><code>patterns = {\n 'file .* does not exist': 'file not found',\n 'user .* not found': 'authorization error',\n}\n</code></pre>\n\n<p>Then you can use it as:</p>\n\n<pre><code>import config\n\nfor pattern in config.patterns:\n if re.search(pattern, log_message):\n print config.patterns[pattern]\n</code></pre>\n\n<p>This is what Django does with their settings file, by the way.</p>\n"
},
{
"answer_id": 187628,
"author": "Aaron Hays",
"author_id": 26505,
"author_profile": "https://Stackoverflow.com/users/26505",
"pm_score": 6,
"selected": true,
"text": "<p>You have two decent options:</p>\n\n<ol>\n<li>Python standard config file format\nusing <a href=\"http://docs.python.org/lib/module-ConfigParser.html\" rel=\"noreferrer\" title=\"ConfigParser\">ConfigParser</a></li>\n<li><a href=\"http://www.yaml.org/\" rel=\"noreferrer\" title=\"YAML\">YAML</a> using a library like <a href=\"http://pyyaml.org/\" rel=\"noreferrer\" title=\"PyYAML\">PyYAML</a></li>\n</ol>\n\n<p>The standard Python configuration files look like INI files with <code>[sections]</code> and <code>key : value</code> or <code>key = value</code> pairs. The advantages to this format are:</p>\n\n<ul>\n<li>No third-party libraries necessary</li>\n<li>Simple, familiar file format.</li>\n</ul>\n\n<p>YAML is different in that it is designed to be a human friendly data serialization format rather than specifically designed for configuration. It is very readable and gives you a couple different ways to represent the same data. For your problem, you could create a YAML file that looks like this:</p>\n\n<pre><code>file .* does not exist : file not found\nuser .* not found : authorization error\n</code></pre>\n\n<p>Or like this:</p>\n\n<pre><code>{ file .* does not exist: file not found,\n user .* not found: authorization error }\n</code></pre>\n\n<p>Using PyYAML couldn't be simpler:</p>\n\n<pre><code>import yaml\n\nerrors = yaml.load(open('my.yaml'))\n</code></pre>\n\n<p>At this point <code>errors</code> is a Python dictionary with the expected format. YAML is capable of representing more than dictionaries: if you prefer a list of pairs, use this format:</p>\n\n<pre><code>-\n - file .* does not exist \n - file not found\n-\n - user .* not found\n - authorization error\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>[ [file .* does not exist, file not found],\n [user .* not found, authorization error]]\n</code></pre>\n\n<p>Which will produce a list of lists when <code>yaml.load</code> is called.</p>\n\n<p>One advantage of YAML is that you could use it to export your existing, hard-coded data out to a file to create the initial version, rather than cut/paste plus a bunch of find/replace to get the data into the right format.</p>\n\n<p>The YAML format will take a little more time to get familiar with, but using PyYAML is even simpler than using ConfigParser with the advantage is that you have more options regarding how your data is represented using YAML.</p>\n\n<p>Either one sounds like it will fit your current needs, ConfigParser will be easier to start with while YAML gives you more flexibilty in the future, if your needs expand.</p>\n\n<p>Best of luck!</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15622/"
] |
I have a python script that analyzes a set of error messages and checks for each message if it matches a certain pattern (regular expression) in order to group these messages. For example "file x does not exist" and "file y does not exist" would match "file .\* does not exist" and be accounted as two occurrences of "file not found" category.
As the number of patterns and categories is growing, I'd like to put these couples "regular expression/display string" in a configuration file, basically a dictionary serialization of some sort.
I would like this file to be editable by hand, so I'm discarding any form of binary serialization, and also I'd rather not resort to xml serialization to avoid problems with characters to escape (& <> and so on...).
Do you have any idea of what could be a good way of accomplishing this?
Update: thanks to Daren Thomas and Federico Ramponi, but I cannot have an external python file with possibly arbitrary code.
|
You have two decent options:
1. Python standard config file format
using [ConfigParser](http://docs.python.org/lib/module-ConfigParser.html "ConfigParser")
2. [YAML](http://www.yaml.org/ "YAML") using a library like [PyYAML](http://pyyaml.org/ "PyYAML")
The standard Python configuration files look like INI files with `[sections]` and `key : value` or `key = value` pairs. The advantages to this format are:
* No third-party libraries necessary
* Simple, familiar file format.
YAML is different in that it is designed to be a human friendly data serialization format rather than specifically designed for configuration. It is very readable and gives you a couple different ways to represent the same data. For your problem, you could create a YAML file that looks like this:
```
file .* does not exist : file not found
user .* not found : authorization error
```
Or like this:
```
{ file .* does not exist: file not found,
user .* not found: authorization error }
```
Using PyYAML couldn't be simpler:
```
import yaml
errors = yaml.load(open('my.yaml'))
```
At this point `errors` is a Python dictionary with the expected format. YAML is capable of representing more than dictionaries: if you prefer a list of pairs, use this format:
```
-
- file .* does not exist
- file not found
-
- user .* not found
- authorization error
```
Or
```
[ [file .* does not exist, file not found],
[user .* not found, authorization error]]
```
Which will produce a list of lists when `yaml.load` is called.
One advantage of YAML is that you could use it to export your existing, hard-coded data out to a file to create the initial version, rather than cut/paste plus a bunch of find/replace to get the data into the right format.
The YAML format will take a little more time to get familiar with, but using PyYAML is even simpler than using ConfigParser with the advantage is that you have more options regarding how your data is represented using YAML.
Either one sounds like it will fit your current needs, ConfigParser will be easier to start with while YAML gives you more flexibilty in the future, if your needs expand.
Best of luck!
|
186,917 |
<p>I'm trying to catch a ClassCastException when deserializing an object from xml.</p>
<p>So,</p>
<pre><code>try {
restoredItem = (T) decoder.readObject();
} catch (ClassCastException e){
//don't need to crash at this point,
//just let the user know that a wrong file has been passed.
}
</code></pre>
<p>And yet this won't as the exception doesn't get caught. What would you suggest?</p>
|
[
{
"answer_id": 186977,
"author": "yanchenko",
"author_id": 15187,
"author_profile": "https://Stackoverflow.com/users/15187",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I can't use <code>instanceof</code> operator as the method is a parametrized one:</p>\n\n<pre><code>public T restore(String from){\n...\nrestoredItem = (T) decoder.readObject();\n...\n}\n</code></pre>\n\n<p>And generics in Java are compile-time only.</p>\n"
},
{
"answer_id": 187061,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 5,
"selected": true,
"text": "<p>The code in the question should give you an unchecked cast warning. Listen to -Xlint.</p>\n\n<p>All the compiler knows about T is its bounds, which it probably doesn't have (other than explicitly extending Object and a super of the null type). So effectively the cast at runtime is (Object) - not very useful.</p>\n\n<p>What you can do is pass in an instance of the Class of the parameterised type (assuming it isn't generic).</p>\n\n<pre><code>class MyReader<T> {\n private final Class<T> clazz;\n MyReader(Class<T> clazz) {\n if (clazz == null) {\n throw new NullPointerException();\n }\n this.clazz = clazz;\n }\n public T restore(String from) {\n ...\n try {\n restoredItem = clazz.cast(decoder.readObject());\n ...\n return restoredItem;\n } catch (ClassCastException exc) {\n ...\n }\n }\n}\n</code></pre>\n\n<p>Or as a generic method:</p>\n\n<pre><code> public <T> T restore(Class<T> clazz, String from) {\n ...\n try {\n restoredItem = clazz.cast(decoder.readObject());\n ...\n</code></pre>\n"
},
{
"answer_id": 187113,
"author": "Tobias Schulte",
"author_id": 969,
"author_profile": "https://Stackoverflow.com/users/969",
"pm_score": 2,
"selected": false,
"text": "<p>There will not be any ClassCastException, except when your T has some base:</p>\n\n<pre><code>public class GenericsTest\n{\n public static void main(String[] args)\n {\n System.out.println(cast(Integer.valueOf(0)));\n System.out.println(GenericsTest.<Long> cast(Integer.valueOf(0)));\n System.out.println(GenericsTest.<Long> cast(\"Hallo\"));\n\n System.out.println(castBaseNumber(Integer.valueOf(0)));\n System.out.println(GenericsTest.<Long> castBaseNumber(Integer.valueOf(0)));\n System.out.println(GenericsTest.<Long> castBaseNumber(\"Hallo\"));\n }\n\n private static <T extends Number> T castBaseNumber(Object o)\n {\n T t = (T)o;\n return t;\n }\n\n private static <T> T cast(Object o)\n {\n T t = (T)o;\n return t;\n }\n}\n</code></pre>\n\n<p>In the above example, there will be no ClassCastException in the first 5 calls to cast and castBaseNumber. Only the 6th call throws a ClassCastException, because the compiler effectively translates the cast() to return (Object) o and the castBaseNumber() to return (Number)o;. Wenn you write</p>\n\n<pre><code>String s = GenericsTest.<Long> cast(\"Hallo\");\n</code></pre>\n\n<p>You would get a ClassCastException, but not whithin the cast-method, but at the assignment to s.</p>\n\n<p>Therefore I do think, your \"T\" is not just \"T\", but \"T extends Something\". So you could check:</p>\n\n<pre><code>Object o = decoder.readObject();\nif (o instanceof Something)\n restoredItem = (T) o;\nelse \n // Error handling\n</code></pre>\n\n<p>But this will still lead to an error later, when the you use your class.</p>\n\n<pre><code>public Reader<T extends Number>{...}\n\nLong l = new Reader<Long>(\"file.xml\").getValue(); // there might be the ClassCastException\n</code></pre>\n\n<p>For this case only Tom's advise might help.</p>\n"
},
{
"answer_id": 188093,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 0,
"selected": false,
"text": "<p>If you can't use instaceof you might be able to use the isAssignableFrom method on Class</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15187/"
] |
I'm trying to catch a ClassCastException when deserializing an object from xml.
So,
```
try {
restoredItem = (T) decoder.readObject();
} catch (ClassCastException e){
//don't need to crash at this point,
//just let the user know that a wrong file has been passed.
}
```
And yet this won't as the exception doesn't get caught. What would you suggest?
|
The code in the question should give you an unchecked cast warning. Listen to -Xlint.
All the compiler knows about T is its bounds, which it probably doesn't have (other than explicitly extending Object and a super of the null type). So effectively the cast at runtime is (Object) - not very useful.
What you can do is pass in an instance of the Class of the parameterised type (assuming it isn't generic).
```
class MyReader<T> {
private final Class<T> clazz;
MyReader(Class<T> clazz) {
if (clazz == null) {
throw new NullPointerException();
}
this.clazz = clazz;
}
public T restore(String from) {
...
try {
restoredItem = clazz.cast(decoder.readObject());
...
return restoredItem;
} catch (ClassCastException exc) {
...
}
}
}
```
Or as a generic method:
```
public <T> T restore(Class<T> clazz, String from) {
...
try {
restoredItem = clazz.cast(decoder.readObject());
...
```
|
186,918 |
<p>My master page contains a list as shown here. What I'd like to do though, is add the "class=active" attribute to the list li thats currently active but I have no idea how to do this. I know that the code goes in the aspx page's page_load event, but no idea how to access the li I need to add the attribute. Please enlighten me. Many thanks.</p>
<pre><code><div id="menu">
<ul id="nav">
<li class="forcePadding"><img src="css/site-style-images/menu_corner_right.jpg" /></li>
<li id="screenshots"><a href="screenshots.aspx" title="Screenshots">Screenshots</a></li>
<li id="future"><a href="future.aspx" title="Future">Future</a></li>
<li id="news"><a href="news.aspx" title="News">News</a></li>
<li id="download"><a href="download.aspx" title="Download">Download</a></li>
<li id="home"><a href="index.aspx" title="Home">Home</a></li>
<li class="forcePadding"><img src="css/site-style-images/menu_corner_left.jpg" /></li>
</ul>
</div>
</code></pre>
|
[
{
"answer_id": 186926,
"author": "Adam Naylor",
"author_id": 17540,
"author_profile": "https://Stackoverflow.com/users/17540",
"pm_score": 0,
"selected": false,
"text": "<p>If they were runat=server you could use the attributes property.</p>\n"
},
{
"answer_id": 186976,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 1,
"selected": false,
"text": "<p>You could register a client script like this:</p>\n\n<p>(set id to the id of the li that you want to set to active)</p>\n\n<pre><code>ClientScript.RegisterStartupScript(this.GetType(), \"setActiveLI\", \"document.getElementById(\\\"\"+id+\"\\\").setAttribute(\\\"class\\\", \\\"active\\\");\", true);\n</code></pre>\n\n<p>This generates a JavaScript call on the page near the bottom after elements have already been rendered.</p>\n"
},
{
"answer_id": 186981,
"author": "Adam Naylor",
"author_id": 17540,
"author_profile": "https://Stackoverflow.com/users/17540",
"pm_score": 0,
"selected": false,
"text": "<p>In order to find that particular control it will need to be defined as public (in the generated designer)</p>\n\n<p>Or will need to be wrapped by a public get in the codebehind.</p>\n"
},
{
"answer_id": 187014,
"author": "Adam Naylor",
"author_id": 17540,
"author_profile": "https://Stackoverflow.com/users/17540",
"pm_score": 0,
"selected": false,
"text": "<p>You can expose the li's on the master page to any content pages by wrapping them in properties on the master page:</p>\n\n<pre><code>public GenericHtmlControl Li1\n{\n get\n {\n return this.LiWhatever;\n }\n}\n</code></pre>\n\n<p>Then on the content page:</p>\n\n<pre><code>MasterPage2 asd = ((MasterPage2)Page.Master).Li1.Attributes.Add(\"class\", \"bla\");\n</code></pre>\n\n<p>If i've got that right!</p>\n"
},
{
"answer_id": 187020,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 2,
"selected": false,
"text": "<p>The code below can be used to find a named control anywhere within the control hierarchy:</p>\n\n<pre><code>public static Control FindControlRecursive(Control rootControl, string id)\n{\n if (rootControl != null)\n {\n if (rootControl.ID == id)\n {\n return rootControl;\n }\n\n for (int i = 0; i < rootControl.Controls.Count; i++)\n {\n Control child;\n\n if ((child = FindControlRecursive(rootControl.Controls[i], id)) != null)\n {\n return child;\n }\n }\n }\n\n return null;\n}\n</code></pre>\n\n<p>So you could do something like:</p>\n\n<pre><code>Control foundControl= FindControlRecursive(Page.Master, \"theIdOfTheControlYouWantToFind\");\n((HtmlControl)foundControl).Attributes.Add(\"class\", \"active\");\n</code></pre>\n\n<p>Forgot to mention previously, that you do need runat=\"server\" on any control you want to be able to find in this way =)</p>\n"
},
{
"answer_id": 187023,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 6,
"selected": true,
"text": "<p>In order to access these controls from the server-side, you need to make them runat=\"server\"</p>\n\n<pre><code><ul id=\"nav\" runat=\"server\">\n <li class=\"forcePadding\"><img src=\"css/site-style-images/menu_corner_right.jpg\" /></li> \n <li id=\"screenshots\"><a href=\"screenshots.aspx\" title=\"Screenshots\">Screenshots</a></li>\n <li id=\"future\"><a href=\"future.aspx\" title=\"Future\">Future</a></li>\n <li id=\"news\"><a href=\"news.aspx\" title=\"News\">News</a></li>\n <li id=\"download\"><a href=\"download.aspx\" title=\"Download\">Download</a></li>\n <li id=\"home\"><a href=\"index.aspx\" title=\"Home\">Home</a></li>\n <li class=\"forcePadding\"><img src=\"css/site-style-images/menu_corner_left.jpg\" /></li>\n</ul>\n</code></pre>\n\n<p>in the code-behind:</p>\n\n<pre><code>foreach(Control ctrl in nav.controls)\n{\n if(!ctrl is HtmlAnchor)\n {\n string url = ((HtmlAnchor)ctrl).Href;\n if(url == GetCurrentPage()) // <-- you'd need to write that\n ctrl.Parent.Attributes.Add(\"class\", \"active\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 187388,
"author": "csgero",
"author_id": 21764,
"author_profile": "https://Stackoverflow.com/users/21764",
"pm_score": 1,
"selected": false,
"text": "<p>All the parts have already been provided in previous answers, but to put the whole thing together, you'll need to:\n<li> add the runat=\"server\" attribute to the <code><ul></code> and <code><li></code> elements\n<li> add a public method to do the work on the master page that can be called from the pages using the master page\n<li> call the method from the Page_Load of the pages</p>\n\n<p>Alternatively you could also add the code to the OnLoad(...) method of the master page, so you don't have to add the method call to the Page_Load on every page.</p>\n"
},
{
"answer_id": 193504,
"author": "Razor",
"author_id": 17211,
"author_profile": "https://Stackoverflow.com/users/17211",
"pm_score": 0,
"selected": false,
"text": "<p>I found a link that works using CSS and involves only changing the body tag's class attribute. This means there's no Javascript and there's no for loops or anything.</p>\n\n<pre><code>#navbar a:hover,\n .articles #navbar #articles a,\n .topics #navbar #topics a,\n .about #navbar #about a,\n .contact #navbar #contact a,\n .contribute #navbar #contribute a,\n .feed #navbar #feed a {\n background: url(/pix/navbarlinkbg.gif) top left repeat-x; color: #555;\n}\n\n....\n\n<body class=\"articles\" onload=\"\">\n\n<ul id=\"navbar\">\n <li id=\"articles\"><a href=\"/articles/\" title=\"Articles\">Articles</a></li>\n <li id=\"topics\"><a href=\"/topics/\" title=\"Topics\">Topics</a></li>\n <li id=\"about\"><a href=\"/about/\" title=\"About\">About</a></li>\n <li id=\"contact\"><a href=\"/contact/\" title=\"Contact\">Contact</a></li>\n <li id=\"contribute\"><a href=\"/contribute/\" title=\"Contribute\">Contribute</a></li>\n <li id=\"feed\"><a href=\"/feed/\" title=\"Feed\">Feed</a></li>\n</ul>\n</code></pre>\n\n<p>Read more here\n<a href=\"http://www.websiteoptimization.com/speed/tweak/current/\" rel=\"nofollow noreferrer\">http://www.websiteoptimization.com/speed/tweak/current/</a></p>\n"
},
{
"answer_id": 467514,
"author": "Bevan",
"author_id": 188790,
"author_profile": "https://Stackoverflow.com/users/188790",
"pm_score": 2,
"selected": false,
"text": "<p>Add runat=\"server\" on the li tags in the masterpage then add this to the appropriate page_load event to add the 'active' class to the li in the masterpage</p>\n\n<p>HtmlGenericControl li = HtmlGenericControl)Page.Master.FindControl(\"screenshots\");\nli.Attributes.Add(\"class\", \"active\");</p>\n"
},
{
"answer_id": 1508283,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Try this\nthe great example for future use. i know this thread is old, but for future queries...</p>\n\n<p><a href=\"http://community.discountasp.net/showthread.php?p=33271\" rel=\"nofollow noreferrer\">http://community.discountasp.net/showthread.php?p=33271</a></p>\n"
},
{
"answer_id": 10795178,
"author": "shivanand nagarabetta",
"author_id": 1423148,
"author_profile": "https://Stackoverflow.com/users/1423148",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks For the solution.</p>\n\n<p>Mininized code.</p>\n\n<p>Master page control can also find in the child page..</p>\n\n<p>i mean master page contains html contol</p>\n\n<p>and chilld page can find the master page html conrol like this</p>\n\n<pre><code>((HtmlControl)this.Master.FindControl(\"dpohome1\")).Attributes.Add(\"class\", \"on\");\n</code></pre>\n"
},
{
"answer_id": 58284225,
"author": "Azum",
"author_id": 12134103,
"author_profile": "https://Stackoverflow.com/users/12134103",
"pm_score": 0,
"selected": false,
"text": "<p>Simple logic and minimal code, I usually use the following code, especially in dynamic menu. Hope this helps.</p>\n\n<p>Create this method code in the code behind master page</p>\n\n<p>CODE BEHIND (C#)</p>\n\n<p><code>protected string SetCssClass(string page)\n{\n return Request.Url.AbsolutePath.ToLower().EndsWith(page.ToLower()) ? \"active\" : \"\";\n}</code></p>\n\n<p>In the menu list items you have created call this method passing the page name like this</p>\n\n<p>HTML PAGE (ASPX inline code)</p>\n\n<p><code><li id=\"screenshots\" class = \"<%= SetCssClass(\"screenshots.aspx\") %>\">\n<a href=\"screenshots.aspx\" title=\"Screenshots\">Screenshots</a></li></code></p>\n\n<p><code><li id=\"future\" class = \"<%= SetCssClass(\"future.aspx\") %>\">\n<a href=\"future.aspx\" title=\"Future\">Future</a></li>\n</code></p>\n\n<p>and so on.</p>\n\n<p>By this method, every time you add a page and link, you don't have to write code in every page. Just when you add the link in the master page, with every <code><li></code> invoke the <code>SetCssClass(pagename)</code> method call for setting class and it's done. (you can rename the method as per your ease. </p>\n\n<p>You can use longer codes if you are being paid per lines of code bcoz then this is just one line of code. (lol). Just kidding. Hope it helps.</p>\n\n<p>Note: I am ignoring other parts of the html code, you can include them also, that would work fine.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17211/"
] |
My master page contains a list as shown here. What I'd like to do though, is add the "class=active" attribute to the list li thats currently active but I have no idea how to do this. I know that the code goes in the aspx page's page\_load event, but no idea how to access the li I need to add the attribute. Please enlighten me. Many thanks.
```
<div id="menu">
<ul id="nav">
<li class="forcePadding"><img src="css/site-style-images/menu_corner_right.jpg" /></li>
<li id="screenshots"><a href="screenshots.aspx" title="Screenshots">Screenshots</a></li>
<li id="future"><a href="future.aspx" title="Future">Future</a></li>
<li id="news"><a href="news.aspx" title="News">News</a></li>
<li id="download"><a href="download.aspx" title="Download">Download</a></li>
<li id="home"><a href="index.aspx" title="Home">Home</a></li>
<li class="forcePadding"><img src="css/site-style-images/menu_corner_left.jpg" /></li>
</ul>
</div>
```
|
In order to access these controls from the server-side, you need to make them runat="server"
```
<ul id="nav" runat="server">
<li class="forcePadding"><img src="css/site-style-images/menu_corner_right.jpg" /></li>
<li id="screenshots"><a href="screenshots.aspx" title="Screenshots">Screenshots</a></li>
<li id="future"><a href="future.aspx" title="Future">Future</a></li>
<li id="news"><a href="news.aspx" title="News">News</a></li>
<li id="download"><a href="download.aspx" title="Download">Download</a></li>
<li id="home"><a href="index.aspx" title="Home">Home</a></li>
<li class="forcePadding"><img src="css/site-style-images/menu_corner_left.jpg" /></li>
</ul>
```
in the code-behind:
```
foreach(Control ctrl in nav.controls)
{
if(!ctrl is HtmlAnchor)
{
string url = ((HtmlAnchor)ctrl).Href;
if(url == GetCurrentPage()) // <-- you'd need to write that
ctrl.Parent.Attributes.Add("class", "active");
}
}
```
|
186,942 |
<p>I have this script:</p>
<pre><code>select name,create_date,modify_date from sys.procedures order by modify_date desc
</code></pre>
<p>I can see what procedures were modified lately.
I will add a "where modify_date >= "
And I'd like to use some system stored procedure, that will generate me :
drop + create scripts for the (let's say 5 matching) stored procedures</p>
<p>Can i do this somehow?</p>
<p>thanks</p>
<hr>
<p>ok. i have the final version:</p>
<p><a href="http://swooshcode.blogspot.com/2008/10/generate-stored-procedures-scripts-for.html" rel="nofollow noreferrer">http://swooshcode.blogspot.com/2008/10/generate-stored-procedures-scripts-for.html</a></p>
<p>you guys helped a lot</p>
<p>thanks</p>
|
[
{
"answer_id": 187063,
"author": "jdecuyper",
"author_id": 296,
"author_profile": "https://Stackoverflow.com/users/296",
"pm_score": 0,
"selected": false,
"text": "<p>You could use a cursor to iterate through each record: </p>\n\n<pre><code>DECLARE @spName NVARCHAR(128)\nDECLARE myCursor CURSOR FOR SELECT name FROM sys.procedures ORDER BY modify_date DESC\nOPEN myCursor\nFETCH NEXT FROM myCursor INTO @spName\nWHILE @@fetch_status = 0\nBEGIN\n -- Process each stored procedure with a dynamic query\n PRINT @spName\nFETCH NEXT FROM myCursor INTO @spName\nEND\nCLOSE myCursor\nDEALLOCATE myCursor\n</code></pre>\n"
},
{
"answer_id": 187095,
"author": "Jonas Lincoln",
"author_id": 17436,
"author_profile": "https://Stackoverflow.com/users/17436",
"pm_score": 3,
"selected": true,
"text": "<p>This ain't pretty, but it works. Run the output from it manually or execute it with sp_executesql.</p>\n\n<pre><code>SELECT OBJECT_DEFINITION(object_id), 'drop procedure [' + name + ']'\nFROM sys.procedures\nWHERE modify_date >= @date\n</code></pre>\n\n<p>You will have to worry about lost rights as well. </p>\n"
},
{
"answer_id": 187176,
"author": "Swoosh",
"author_id": 26472,
"author_profile": "https://Stackoverflow.com/users/26472",
"pm_score": 0,
"selected": false,
"text": "<p>meanwhile i did some digging, and seems like</p>\n\n<pre><code>sp_helptext 'my_stored_procedure'\n</code></pre>\n\n<p>is what i need, (plus the part that i already knew when i asked the question explained more by jdecuyper)</p>\n"
},
{
"answer_id": 187243,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": false,
"text": "<p>No cursor necessary (modify as desired for schemas, etc):</p>\n\n<pre><code>DECLARE @dt AS datetime\nSET @dt = '10/1/2008'\n\nDECLARE @sql AS varchar(max)\n\nSELECT @sql = COALESCE(@sql, '')\n + '-- ' + o.name + CHAR(13) + CHAR(10)\n + 'DROP PROCEDURE ' + o.name + CHAR(13) + CHAR(10)\n + 'GO' + CHAR(13) + CHAR(10)\n + m.definition + CHAR(13) + CHAR(10)\n + 'GO' + CHAR(13) + CHAR(10)\nFROM sys.sql_modules AS m\nINNER JOIN sys.objects AS o\n ON m.object_id = o.object_id\nINNER JOIN sys.procedures AS p\n ON m.object_id = p.object_id\nWHERE p.modify_date >= @dt\n\nPRINT @sql -- or EXEC (@sql)\n</code></pre>\n"
},
{
"answer_id": 187347,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 0,
"selected": false,
"text": "<p>This is best done in a more suitable language than SQL. Despite its numerous extensions such as T-SQL, PL/SQL, and PL/pgSQL, SQL is not the best thing for this task.</p>\n\n<p>Here is a link to a similar question, and my answer, which was to use SQL-DMO or SMO, depending on whether you have SQL 2000 or 2005.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/174515/how-do-you-copy-a-ms-sql-2000-database-programmatically-using-c#175062\">How to copy a database with c#</a></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26472/"
] |
I have this script:
```
select name,create_date,modify_date from sys.procedures order by modify_date desc
```
I can see what procedures were modified lately.
I will add a "where modify\_date >= "
And I'd like to use some system stored procedure, that will generate me :
drop + create scripts for the (let's say 5 matching) stored procedures
Can i do this somehow?
thanks
---
ok. i have the final version:
<http://swooshcode.blogspot.com/2008/10/generate-stored-procedures-scripts-for.html>
you guys helped a lot
thanks
|
This ain't pretty, but it works. Run the output from it manually or execute it with sp\_executesql.
```
SELECT OBJECT_DEFINITION(object_id), 'drop procedure [' + name + ']'
FROM sys.procedures
WHERE modify_date >= @date
```
You will have to worry about lost rights as well.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.